How to define a script in Yii2?

My model rules are like

public function rules()
        {
            return [
                [['email','password'], 'required'],
                [['email'],'unique'],
                [['status','role_id','created_by', 'updated_by', 'is_deleted'], 'integer'],
                [['created_at', 'updated_at'], 'safe'],
                [['first_name', 'last_name', 'email', 'username','location','address','about_me'], 'string', 'max' => 200],
                [['phone'], 'string', 'max' => 100]
            ];
        }

when creating a new user, I need an email and a password, but during the update I only need a username. How can i do this?

+4
source share
1 answer

First of all, it is better to add scripts as constants to the model instead of hard-coded lines, for example:

const SCENARIO_CREATE = 'create';

Then you can use it as follows:

[['email','password'], 'required', 'on' => self::SCENARIO_CREATE],

Another way is to describe it in a method scenarios():

public function scenarios()
{
    $scenarios = parent::scenarios();
    $scenarios[self::SCENARIO_CREATE] = ['email', 'password'];

    return $scenarios;
}

Therefore, you need to specify all the safe attributes for each scenario.

Finally, be sure to install the necessary script after creating a new instance of the model.

$model = new User;
$model->scenario = User::SCENARIO_CREATE;
...

Official documents:

+11
source

All Articles