Handling Foreign Key Constraint

If you have used the databases Foreign Key support to impose a constraint, for example preventing a parent record being deleted when it has children records, you will get a CDbException thrown when such a delete attempt fails. I wanted a way to handle this, and what follows describes what I have done. I am new to Yii, so hope that if someone knows a better way they will add a comment explaining their approach.

In the controllers actionDelete function the CDbExceptio is caught as follows:




try{

    $this->loadModel()->delete();

}

    catch(CDbException $e)

{

} 



However, this gives no feedback to the user that an error has occurred, or what the nature of the error is. One solution is to disable Ajax and allow the controller to report the error. In admin.php stop the updates being handled by Ajax. This is done by adding to the zii.widgets.grid.CGridView’ array the parameter:


'ajaxUpdate'=>false,

Now in the controller’s actionDelete function change the redirect code as follows:




if(!isset($_GET['ajax']))

    $this->redirect(array('admin', 'CRUDError' => $e->getMessage()));

}



The error message is being passed as a URL parameter. I am not sure if this is the best way of doing this, but it works. Also note that the error message has not been sanitized. You will probably want to change this, as the exception messages are long and not at all user friendly.

To report the error in the controller add a variable:


public $errorMessage 

In the controller’s actionAdmin function set this variable:


$this->errorMessage  =  $_GET['CRUDError'];

In the admin.php view display the variable:


<?php echo $this->errorMessage ?>