8

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?

Bloodhound
  • 2,906
  • 11
  • 37
  • 71

1 Answers1

24

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:

arogachev
  • 33,150
  • 7
  • 114
  • 117