Unique Validation Not Working On Actionupdate

I’m pretty new to Yii, I’ve been working on it for about a week now so this issue is most likely something I’m missing, but it’s driving me crazy.

I’ve got a Unique validator on an email attribute in a User model.




public function rules()

{

	return array(

                ...

		array('email', 'required', 'on'=>'login, register, update'),

	        array('email','email'),

		array('email', 'unique'),

                ...

        );

}



This works great on my Register Action, but it doesn’t work on an Update Action and I get a MySql Exception:




CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'email@gmail.com' for key 'email_UNIQUE'. 



The client side validation for the email validation works on login, register, and update.

Any help is appreciated. I can post more relevant code if needed.

Thanks!

Have you already read this?

http://www.yiiframework.com/forum/index.php/topic/26057-how-to-validate-unique-field-on-client-side/

Hey Fabrizio,

Yes I have read that. Very similar symptoms actually. Ajax was working for validators like ‘email’->‘email’ and length, etc. , but not the unique validator.

I have found the problem though! …and it’s entirely my fault.

So what I had done previously was set up a DefaultScope like the following:




public function defaultScope()

    {

    	if (!Yii::app()->user->isGuest && !Yii::app()->user->admin) {

    		$condition = '(userID='.Yii::app()->user->id . ')';

			return array(

        		'condition'=>$condition,      

        	);

		}   

		else{

			return array(

        		'condition'=>'',        

        	);

		}      

    }



This was so that if a normal user would try to access the view/update page of another user they would get a 404 instead, but this was causing the issue because the logged in user could not select any other rows from the User table to check the unique constraint. If I log in as an "admin" then the unique validation works.

So, I can disable the default scope, but then all users can view and edit other users. Do you know of any better way of doing that, or a way around the unique issue?

Thanks!

So I’ve solved the problem altogether now. I’ve removed the DefaultScope which was causing the problem and replaced it with checks in certain actions. Like so:




        public function actionView($id)

	{

		if (Yii::app()->user->id != $id && !Yii::app()->user->admin) {

			throw new CHttpException(404,'The specified post cannot be found.');

		}

		$this->render('view',array(

			'model'=>$this->loadModel($id),

		));

	}



Now users are not able to view information on other users, but admins can, and the unique validator is working with ajax enabled or disabled.