there is a User model

here's the rule

public function rules() { return [ ['username', 'required'], //['username', 'match', 'pattern' => '#^(p{L}|p{Zs}|p{N}|,|-|_ | |)+$#i'], ['username', 'unique', 'targetClass' => self::className(), 'message' => 'This username has already been taken.'], ['username', 'string', 'min' => 2, 'max' => 255], ['email', 'required'], ['email', 'email'], ['email', 'unique', 'targetClass' => self::className(), 'message' => 'This email address has already been taken.'], ['email', 'string', 'max' => 255], ['status', 'integer'], ['status', 'default', 'value' => self::STATUS_ACTIVE], ['status', 'in', 'range' => array_keys(self::getStatusesArray())], ]; } 

there is a need to allow the user to change only the nick question, and how, in this case, disable the email check because the model is not validated due to the fact that either the email is not unique or it needs to be filled out?

  • You need to make scripts and write down for each of them separate validation rules. Or, in the request to prescribe some additional parameter and catch it in the block-condition of validation. - withoutname
  • @withoutname and there is somewhere suitable information on the scenarios, and not the one that offers of the documentation - Sergalas
  • I generally looked here here, yiiframework.com.ua/ru/doc/guide/2/structure-models/… . But in the end I didn’t use it in production, bypassed the scripts with the help of beforeAction in the controller. - withoutname

1 answer 1

You can use scripts to solve the problem.

Add a script inside the model as follows:

 const SCENARIO_UPDATE = 'updateInfo'; 

You also need to declare validation attributes in the scenarios() function:

 public function scenarios() { return [ self::SCENARIO_UPDATE => ['username', //... ], //... ]; } 

Before using the model, declare the script:

 $model->scenario = User::SCENARIO_UPDATE; 

We specify in the rules that the validation of the email is not used when the SCENARIO_UPDATE script:

 [['email'], 'required', 'when' => function(){ return !$this->scenario == self::SCENARIO_UPDATE; }], 
  • @LAV, instead of editing the answer (not general), it is better to leave a comment with your comments. - insolor