SoFunction
Updated on 2025-03-10

Tutorial for using scenarios in Yii 2.0

Preface

Anyone who is familiar with the Yii framework knows that flexible usage scenarios can achieve twice the result with half the effort!

For example, if you add or modify ordinary data, you need to verify two of the fields, while modifying only requires verifying one of the fields; there is another situation, which is also what we are using now. The same table (same model) may be used in different project branches, but the verification of member variables by unused project branches is different, and the usage scenario can be easily done;

Scene use

1. The use of simple scenes in Yii2 is explained here:https:///article/

2. However, for beginners, they may still not be able to use it flexibly:

 public function rules()
 {
 return [
  [['name', 'account', 'pwd'], 'string', 'max' => 11],
  ['account','required','message'=>'Username cannot be empty'],
  ['pwd','required','message'=>'Password cannot be empty','on'=>'add_customer']
 ];
 }

For the verification rules and scenarios that specify some member variables in rules and their belongings, the above writing method is recommended. Of course, you can directly define a method named scenerios in the class;

How to use:

1. If you need to new a new object, use a certain scenario and directly use:

 $bus_department = new BusDepartment(['scenario' => 'add_customer']);

2. This is often used when updating data:

 $bus_department = BusDepartment::findOne($id);

The use scenario is:

 $bus_department->setScenario('add_customer'); or $bus_department->scenario = 'add_customer';

In this way, when operating the current object, the rules will be verified according to the set scene.

Summarize

The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.