How To Deal With Cdbexceptions

Hi,

I’m using AR to save a record. I have a duplicate key contraint on a couple of columns.

When i use:


			$model = new Record;

			$model->user_id = (int) $id;

			$model->friend_id = (int) Yii::app()->user->id;

			

			if($model->save()){

 				

				echo 'Record Added</div>';

		

			} else {

			

				echo 'Something went wrong';

				

			}



This works fine, but not if Integrity constraint violation occurs. What’s the correct way to deal with this.

try and catch?

The correct way is to understand why do you have this constraint, whether you really need it and why duplicate key situation occurs.

If it’s ok to you (constrains really must exist and users shouldn’t submit such data) consider using “unique” validator in your model.

From the UI designer standpoint you shouldn’t allow the user to perform actions that will cause errors. This is an example when you know that might happen and can prevent it.

For example, if a user is choosing both values from dropdown lists you should filter their contents in such way that choosing an existing pair is impossible.

A little off topic:

The same goes for action buttons, if it can’t be performed don’t let user click the button and then display an error message, just make that button disabled, optionally with a note next to it or in a popover why it is so.

Thank you. I actually had answered this in a previous situation and forgot about it.

I used http://www.yiiframework.com/extension/unique-attributes-validator/

Thanks for setting me straight.