Unique validator - ignore current value on update

Hi all,

I have an update form for user information. All data that has been filled out and is displayed in the form (as default value of field). The email address is both unique and required. If I load the form and save it without altering the email address, it tells me that email address already has already been taken. Is that a bug in the Yii or did I do something wrong?

Thanks…

Model


array('email', 'unique'),

Form


	<div class="row">

		<?php echo $form->labelEx($model,'email'); ?>

		<?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>100)); ?>

		<?php echo $form->error($model,'email'); ?>

	</div>

Cheers…

if u make any field to be ‘unique’ u cannot save the same value of that field in more than one record.

u r getting this error as u r trying to save the same email id again in a new record.

Ok, I thought the unique validator would check whether this is about updating an existing record (doesn’t have to be unique) or inserting a new record.

That is not entirely true. You can if you load the record from the DB and just apply the new attributes. Now if your emailaddress didn’t change, the unique validator won’t fail.

This works:




if($id)

  $user = User::model()->findByPk($id)

else

  $user = new User;

$user->attributes = $_POST['UserForm'];

$user->save();



This doesn’t:




$user = new User;

$user->attributes = $_POST['UserForm'];

if($id)

  $user->id = $id;

$user->save();



well yes u can always update the same row as many times u want.

may be i should have added ‘same value in the new record’, to avoid confusion.

In any case CUniqueValidators exclude the the actual record while checking for unicity.

That allows to update any fields safely, so if you don’t change the email, you will not have error, if you change the email to another already used email, you will have the error as expected.

Thanks guys, works now.

This can work:

array(‘field_name’, ‘unique’,‘on’=>‘insert’, ‘message’=>‘Field Name already exist’) once you create the record

array(‘field_name’, ‘unique’,‘on’=>‘update’, ‘message’=>‘Field Name already exist’) once you want to update the record and you want it to be unique