Detailed explanation of the use of scenes in Yii2

*文
Release: 2023-03-19 07:36:01
Original
1394 people have browsed it

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'] ]; }
Copy after login

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']);
Copy after login

2. This is often used when updating data:

$bus_department = BusDepartment::findOne($id);
Copy after login

The method of using the scenario is:

$bus_department->setScenario('add_customer'); 或者 $bus_department->scenario = 'add_customer';
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!