Saturday, 1 October 2016

Create Validation using Scenarios in Yii2 Application

In this post i will show you how to create a simple custom validation using scenarios attribute in yii2 application.Yii2 model is designed in very flexible way for dynamic logic based on scenario. A model supports only one scenario and its named default (by default).ex on user registeration we will get username ,email and password. At the time of login we need only username and password. So the same model is using two type of validation here one is based on login and other is registeration so we can handle this using scenarios.

Yii2 Scenarios


Register Scenario - Required - username, password, email
Login Scenario - Required - username, email

Step 1: Create a model class where rules function contain this code of validation rule.

<?php
class User extends Model
{
    public $name;
    public $email;
    public $password;
    
    public function rules(){
        return [
            [['name','email','password'],'required'],
            ['email','email'],
            [['name', 'email', 'password'], 'required', 'on' => 'register'],
            ];
    }
    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios['login'] = ['name','password'];//Scenario Values Only Accepted
        return $scenarios;
    }
}
?>

Step 2: After setting the validation rule you can call the scenarios like this.

<?php
class UserController extends Controller
{
    
    public function  actionLogin(){
        $model = new User;
        $model->scenario = 'login';
    }
    
    public function  actionRegister(){
        $model = new User(['scenario' => 'register']);
    }
}
?>

For more example you can read this post in yii2 framework.I hope you like the post and please comment if you need any help related to this post.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts