Search code examples
phpvalidationmodelyii2

yii2 validation rules on update


I have a model and validation rules for it:

class User extends ActiveRecord implements IdentityInterface
{
 ...
public function rules()
{
    return [
        [['username', 'password', 'email'], 'required', 'on' => 'insert'],
        [['password', 'email'], 'required', 'on' => 'update'],
    ]
}

Actually the code produces no validators. When I remove 'on' section, everything goes well.

Digging in official documentation and search thru The Web didn't help me to understand what is the issue, and why can't I have custom required fields sets for different actions.


Solution

  • The Scenario is not automaticaly setted by Yii2 ActiveRecord. If you need a specific scenario you must create it and assign in the model.

    E.g. for update ...

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios['update'] = ['password', 'email'];//Scenario Values Only Accepted
        return $scenarios;
    }
    

    Also you can set scenario in your actionUpdate

    public function actionUpdate($id)
    {
       $model = $this->findModel($id);
       $model->scenario = 'update';
      ........
    }