Home > Article > Backend Development > Detailed explanation of the use of scenes in Yii2
This article mainly introduces to you the relevant information about the use of scenarios in Yii 2.0. The introduction in the article is very detailed and has a certain reference and learning value for everyone. Friends who need it can follow the editor to learn together. I hope to be helpful.
Preface
Anyone familiar with the Yii framework knows that flexible usage scenarios can achieve twice the result with half the effort!
For example, when adding or modifying ordinary data, two of the fields need to be verified for new additions, while only one of the fields needs to be verified for modifications; there is another situation, which we are using now, the same table ( The same model) may be used in different project branches, but different project branches verify member variables differently. In this case, the usage scenario can be easily solved;
Scenario usage
public function rules() { return [ [['name', 'account', 'pwd'], 'string', 'max' => 11], ['account','required','message'=>'用户名不能为空'], ['pwd','required','message'=>'密码不能为空','on'=>'add_customer'] ]; }
For the verification rules and scenarios of specified member variables in rules, the above writing method is still recommended. Of course, you can also directly define a method named scenarios in the class. Method;
How to use:
1. If you need to create 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 method of using the scenario is:
$bus_department->setScenario('add_customer'); 或者 $bus_department->scenario = 'add_customer';
In this way, when operating the current object, the rules will be verified according to the set scenario. .
Related recommendations:
Detailed explanation of restful api authorization verification of yii2
Detailed explanation of how Yii2 implements a custom independent validator
How to use join and joinwith multi-table association queries in Yii2
The above is the detailed content of Detailed explanation of the use of scenes in Yii2. For more information, please follow other related articles on the PHP Chinese website!