my model rules are like this
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]
];
}
while creating a new user i need email and password required, but during update i need only username required. how can i do this?
First of all, it's better to add scenarios as constants to model instead of hardcoded strings, for example:
const SCENARIO_CREATE = 'create';
Then you can use it like this:
[['email','password'], 'required', 'on' => self::SCENARIO_CREATE],
Another way is to describe it in scenarios()
method:
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios[self::SCENARIO_CREATE] = ['email', 'password'];
return $scenarios;
}
That way you need to specify all safe attributes for each scenario.
Finally, don't forget to set needed scenario after creating new model instance.
$model = new User;
$model->scenario = User::SCENARIO_CREATE;
...
Official docs:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With