How to prevent duplicate key error

Hello,

My app bombs when a user trys to add a record that already exists.

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

How can I capture this error and display a nice message to the user.

I would have a function that validates whether there is already an entry with the same data on the database… if count()>0 then… display the nice error.

I resolved this.




try {

if($model->save())

	$this->redirect(array('view','id'=>$model->ID));

}

catch(CDbException $e) {

	$model->addError(null, $e->getMessage());

}



Nice approach… congrats

You have set the "exist" validator for that field right?

http://www.yiiframework.com/doc/api/1.1/CExistValidator

This is new to me, can you explain how?

Check the documentation for the validation rules - http://www.yiiframew…alidation-rules

"exist" validator checks that the entered value exists in a database, this is good for entering FK fields…

for your problem you need the "unique" validator - http://www.yiiframew…UniqueValidator

in your model, something like:




public function rules()

{

  return array(

   ...

   array('id','unique','message'=>'{attribute}:{value} already exists!'),

   ...

  );

} 



That looks much cleaner.

Thanks for sharing.

This way the value is checked before getting to the save() function so that the database does not return an error…

if you use ajax validation the error message is displayed as soon as the user enters a value that already exists and leaves that field…

I will have to try it using the ajax validation.

Thanks

Yii is great.

Do I need to do anything else for ajax to work?

In my controller, I uncommented this:

// Uncomment the following line if AJAX validation is needed

	$this->performAjaxValidation($model);

But nothing happens.

Update:

Never-mind, I forgot to enable it in the _form.php

Thanks

That work fine but how to do if I have two ids?




public function rules()

{

  return array(

   ...

   array('id1,id2','unique','message'=>'{attribute}:{value} already exists!'),// is not working correctly

   ...

  );

} 



If you have to checke the univocity of the couple of ID, you have to write a custom validator, I guess that CUnique validator doesn’t help in this case.

Thx for your answear!

Could someone explain how he/she did in this kind of situation?