[SOLVED] Model rules required fields

Hi there,

I have a user model which has two pages, one page to upload a logo and one page to update the rest of the users details.

The logo isn’t in the database attached to the user model, it’s just uploaded to the server, so I added it to my users model class as a public property, ie:


class User extends CActiveRecord

{

	public $logo;

	//...

}

And defined it in the rules, ie:


public function rules()

{

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

	// will receive user inputs.

	return array(

		array('email', 'required'),

		array('logo', 'file', 'types'=>'jpg, jpeg, gif, png'),

		//...

	}

}

This is great, and works perfectly for the logo upload, however when submitting the other user page, which is all their other details, it is throwing back the error:


1. Logo cannot be blank.

I haven’t set the logo to be ‘required’ for any form inputs, so I’m wondering why it’s insisting that I have a value for it?

I’ve also stumbled upon the exact same problem when adding a registration form with a password repeat on it. I’ve declared the password repeat field, and set it to compare with the main password field. I haven’t set it as ‘required’, simply:


class User extends CActiveRecord

{

	public $logo;

	public $password_repeat;


	//...


	public function rules()

	{

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

		// will receive user inputs.

		return array(

			array('email', 'required'),

			array('password', 'compare'),

			array('logo', 'file', 'types'=>'jpg, jpeg, gif, png'),

			//...

		}

	}

	//...

}

Even so, I’m now getting two errors on the main details form (which doesn’t have a password check or logo upload):


Logo cannot be blank.

Password must be repeated exactly.

Can someone point me in the right direction as to where I’m going wrong, and how I get these items to not be ‘required’?

Thanks,

Stu

CFileValidator.allowEmpty is set to false by default. But in you case I think you need to use scenarios:




array('logo', 'file', 'types'=>'jpg, jpeg, gif, png', 'on'=>'first_step'),



Hi Andy,

That’s very clever, thanks I hadn’t seen the allowEmpty attribute! That works perfectly, I suppose I need to set a ‘register’ scenario and have the password compare only run in that scenario to fix my other issue.

Ta for the hints,

Stu

thanks!

Sorry but i want to mentionned one thing for your "logo" file field.

You get “logo cannot be blank” because you didn’t add the “allowEmty” attribute in the CFileValidator.

You must do like that :

array(‘logo’, ‘file’, ‘types’=>‘jpg, jpeg, gif, png’, ‘on’=>‘first_step’,[color="#FF0000"]“allowEmpty”=>TRUE[/color]),

so validator can pass it as a null value.