Very very newbie question

I’m almost embarassed to be asking this question because I suspect the answer is staring me in the face. I’m writing my first yii application, learning as I go along. I’ve set-up the following rule for one of my models -


			array('password', 'required', 'on'=>'create'),

However, when testing, it appears not to work as I expected - ‘password’ seems to be optional on either creation or update while I want it to be required for creation but optional for update. If I change the rule to read ‘on’=>‘update’ it works fine, although the wrong way round for my purposes.

Am I doing something blindingly stupid?


First of all, welcome to the forum!

That is because probably you don’t set any rule for ‘password’ on update scenario, therefore, it is ‘not safe’ to set on update so you can’t assign a value to it

Try to add other rule like array(‘password’,‘length’,‘max’=>64) or some other rule

check out this wiki

Thanks Gustavo. I think I’m already doing something along those lines. Here’s the full set of rules I’ve got, including one restricting the password length -

	public function rules()


		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('name, address1, city, postcode, admin_email', 'required'),

			array('password', 'required', 'on'=>'create'),

                        array('admin_email', 'email'),

                        array('admin_email', 'unique', 'attributeName'=>'admin_email'),

			array('name, website', 'length', 'max'=>255),

			array('address1, address2, address3, city, admin_email', 'length', 'max'=>100),

			array('postcode, sic', 'length', 'max'=>10),

			array('phone', 'length', 'max'=>20),

			array('password', 'length', 'max'=>32),

			array('id, admin_id, name, description, address1, address2, address3, city, postcode, website, phone, sic, admin_email, password', 'safe', 'on'=>'search'),



I see

You are probably not specifying the scenario when creating the model, like new myModel(‘create’)

‘insert’ is the default scenario, when inseting a new record

try to specify the scenario like above and everyhing will work as expected

Thanks Gustavo. I’m probably being a bit dim but would you be able to explain a bit more about what you think I should be doing?

Hey Gordon

You need to specify the ‘create’ scenario when creating the model


$model=new myModel('create');

the default scenario is ‘insert’, when you don’t specify it, when you create a new model

after you find a record, the scenario is changed to ‘update’ and that is why your code is working if you change the rule to ‘update’

OK. So as an alternative, I changed the rule to -

array('password', 'required', 'on'=>'insert'),

which seems to work.

Many thanks