How can I handle foreign key constraints in my app? I have an ON DELETE RESTRICT constraint. At the moment I get a CDbException when I try to delete a record - I presume I need to catch the exception somehow? Sorry I’m not too clued up in this area!
Also the CGridView will need to handle the constraint via the AJAX delete call - can a flash message be displayed?
try
{
$this->loadModel()->delete();
Yii::app()->user->setFlash('success', "The User has been deleted successfully.");
}
catch(CDbException $e)
{
Yii::app()->user->setFlash('error', "The User could not be deleted.");
}
This works fine and the flash message is displayed on the normal delete, but how do I get it to display a flash message on the AJAX delete?
Right, so basically with the AJAX delete we don’t send a ‘flash’ message but instead it should be a CJSON response? Man, I can’t get my head around this. I have done it like this:
Controller:
try
{
$this->loadModel()->delete();
Yii::app()->user->setFlash('success', "The User has been deleted successfully.");
}
catch(CDbException $e)
{
Yii::app()->user->setFlash('error', "The User could not be deleted.");
echo CJSON::encode(array(
'message'=>"The User could not be deleted.",
));
exit;
}
Well, I am not 100% sure that is possible to do it.
I successfully did such kind of flash messages in ajax, the trick is to include in the ajax response some javascript code that displays the flash message.
In my example, in case of ajax response I send back a json array with 2 fields, the html to relplace and the flash message.
Your case is more difficoult, because you are working with CGridView, wich complicates the situation.
Maybe a very rogue solution can be to write, in case of exception, some javascript directly in the cell of the cgridView, something like:
<script type="text/javascript">
setFlash('success', 'The User could not be deleted.');
</script>
This script should be echoed INSIDE the grid view, so when CGridView will replace the table, you will get the flash.
Its just the standard CGridView - I haven’t configured it in any special way. The delete button is part of the CButtonColumn and this auto-generates the jQuery function I posted above. The only way I can think of putting in the ‘dataType’=>‘json’ is by editing the core framework file.
Youll see how to setup the buttons individually. Maybe is best to make the button call a function on click that makes the correspondent ajax actions and handles its response.