I’m noob in Yii and trying to learn it. Following Building a Blog System using Yii and made some customizations. Got some strange issues with afterDelete(). In summary, there some actions which perfectly works using afterSave(), but not working with afterDelete().
Made model and CRUD ‘category’ with relation to post model HAS_MANY. I want to set all posts category_id to 0 when category is deleted, so implementation in category model:
//doesn't work
protected function afterDelete()
{
parent::afterDelete();
Post::model()->updateAll(array('category_id'=>0), ('category_id='.$this->id));
}
public function actionDelete($id)
{
$this->loadModel($id)->delete();
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
public function loadModel($id)
{
$model=Category::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
and post controller:
public function actionDelete($id)
{ //delete only via POST request
if(Yii::app()->request->isPostRequest)
{
$this->loadModel($id)->delete();
if(!isset($_GET['ajax']))
$this->redirect(array('index'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
private $_model;
public function loadModel($id)
{ // if model not loaded yet
if($this->_model===null)
{
//and is given post id
//somebody tries to access post in url
if(isset($_GET['id']))
{
// load model depending on role
// if user is guest
// give him only published or archived posts not drafts
if(Yii::app()->user->isGuest)
$condition='status='.Post::STATUS_PUBLISHED
.' OR status='.Post::STATUS_ARCHIVED;
else
// user is owner - give him all posts
$condition='';
// find posts for guest or owner
$this->_model=Post::model()->findByPk($_GET['id'], $condition);
}
//not found any posts matched that condition
if($this->_model===null)
throw new CHttpException(404,'The requested page does not exist.');
}
//give them posts
return $this->_model;
}