Hi All,
I am new to Yii and MVC style coding so I was wondering where I should put some code that reports an error back to the user.
I have a simple schema with a one to many relationship enforced by the db with a "RESTRICT" for ON DELETE
1 color -> many Collectors
I would like to display a nice popup error to the user if they try and delete a color that is being used in the foreign key by Collectors.
I tried putting some code in the BeforeDelete() method of Color’s model. But I could not work out a way to display a dialog from there and it really didnt seem to be the right place.
// public function beforeDelete()
// {
// if(parent::BeforeDelete())
// {
// $c=$this->countCollectorsUsingColor();
// if($c>0)
// {
// return false;
// }
// }
//
// return true;
// }
I then tried creating a method in Colors model that returned count of references and called that from ColorsController actionDelete method - There the popup is kinda of shown but becomes a whole page and not a popup.
public function countCollectorsUsingColor()
{
return count(Collector::model()->findAll("color_id=".$this->id));
}
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
$model=$this->loadModel($id);
$count=$model->countCollectorsUsingColor();
if($count>0)
{
$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
'id'=>'mydialog',
// additional javascript options for the dialog plugin
'options'=>array(
'title'=>'Cannot delete color because referenced by collectors',
'autoOpen'=>true,
'modal'=>true,
'width'=>'auto',
'height'=>'auto',
),
));
echo "Cannot delete this color because:";
echo "There are $count collectors using this color.";
echo "Please edit them first.";
echo $this->renderPartial('_formDialog', array('model'=>$model));
$this->endWidget('zii.widgets.jui.CJuiDialog');
// the link that may open the dialog
// echo CHtml::link('open dialog', '#', array( 'onclick'=>'$("#mydialog").dialog("open"); return false;',));
}
else
{
// 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'));
}
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
So the real question is how and where should I do this properly. I would like to keep the "Confirm Delete" option from the menu in thee generated view code and then display an error saying that something like "This color is used X times"
Either a CJuiDialog or the JNotify solutions would be cool.
TIA
Adrian