Delete Validation In Yii

Table relationship

Table 1- Employee

id

name

position

department_id

Table 2- Department

id

name

One department can have many employee…,

so here is the question it is possible to make a validation before you delete a data in the department table once some employee data is already attach to it.

Like…, error message: You cannot delete this data

Useful post. Thanks for it!

Use InnoDB and add a foreign key constraint to the Employee table:


ALTER TABLE Employee ADD CONSTRAINT employee_department FOREIGN KEY (department_id) REFERENCES Department (id)

Then check for error code 1217 when deleting:




try

{

	$department->delete();

}

catch(CDbException $e)

{

	// Cannot delete or update a parent row: a foreign key constraint fails

	if($e->errorInfo[1] == 1217)

	{

		echo 'You cannot delete this data';

	}

	else

		throw $e;

}



I had a similar situation and did it by using the "onBeforeDelete" event of the AR model. The AR model raises the onBeforeDelete event prior to deleting a record. If the $event class "isValid" variable comes back as false the deletion is not performed. I got the idea from this blog post

The implementation of my solution was fairly simple. I added two methods to my AR model class.




class Topic extends CActiveRecord

{

   public function init() {

      $this->attachEventHandler('onBeforeDelete',array($this,'deletePermission'));

   }


   public function deletePermission($event) {

     // tkey is the primary key in this model (Topic) and the foreign key in the related table (Suggestion)

     $x = $event->sender->tkey; //retrieve key value of the record that is being deleted

     $t = Suggestion::model()->count("tkey = $x"); //Count all records from related table with this key value

     $event->isValid = (intval($t) == 0); //allow delete only when there are no related records

   }


}