Yii Framework Forum: Handling Foreign Key Constraint - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Handling Foreign Key Constraint A way to handle exceptions arising from a DB Foreign Key constraints. Rate Topic: -----

#1 User is offline   Mike (UK) 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 16
  • Joined: 01-August 10
  • Location:Exeter, UK

Posted 10 August 2010 - 11:20 AM

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 ?>

0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users