Latest news:

Sahih al-Bukhari (সহীহ বুখারী) is a free Hadith application for android. This application is advertisement free. Download now

Yii2 Scenarios validate only create Action

Yii2 Scenarios validate only create Action

Yii2 model scenarios can be used differently. Lets say, we have a model as Customer 
Which can be used to store customer sign-in inputs, 
but it can be also used for the customer sign-up purpose. 
In different scenarios, Yii2 model can be used in multiple business rules and logic.
the email attribute may be required during customer sign-up, 
but not required customer sign-in.

Yii2 model uses the yii\base\Model::$scenario property to track the scenario. 
By default, Yii2 model supports only a single scenario as default scenario. 
Below code shows two ways of setting the scenario of Yii2 model on controller section:

$model = new Customer;
$model->scenario = Customer::SCENARIO_LOGIN;
$model = new Customer(['scenario' => User::SCENARIO_LOGIN]);

in many cases, we need a rule to be applied only in particular scenarios. 
To do so, we can specify the rule property as like below example:

in model file:
public function rules()
    return [
        ['title', 'required', 'on' => 'create']

in controller file:
public function actionCreate()
     $model = new Item();
     $model->scenario = 'create';

Tags : PHP, Yii, Yii2,

Views : 2560

Subscribe Us

Follow Us