I have 1 table "tabl_a" which has a primary key "id" .Another table "tabl_b" has a column named "a_id" which is a foreign key of "id" column in table "tabl_a".
Now whenever I delete "id" from "tabl_a" I want it to check if there are any values in "table_b" for that element if there are then it should not delete it.
function beforeDelete(){
if( $this->relationName !== array() )//by relationName I mean the name of the relation between the models
return false;
return parent::beforeDelete();
}
Now when I try to delete it and if it is not deleted I want to show a message that it is not deleted. How can I show it . when it is deleted I show a message in the fashion below:
public function actionDelete($id)
{
//if(Yii::app()->request->isPostRequest)
//{
$del="Removed";
// we only allow deletion via POST request
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin','ss'=>$ss,));
//}
//else
// throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
In your controller action handle it as below. Assume you have set up relationship between two tables.
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
try
{
// we only allow deletion via POST request
$model=$this->loadModel($id);
$model->delete();
}
catch (CDbException $e)
{
if (1451 == $e->errorInfo[1])
{
// Your message goes here
$msg = 'Site deletion failed.Please delete nodes belongs to this Site first.';
}
else
{
$msg = 'Site deletion failed';
}
if (isset($_GET['ajax']))
{
throw new CHttpException(400, $msg);
}
else
{
Yii::app()->user->setFlash('error', $msg);
}
}
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}