Defect in AfterAction in Yii
when i use redirect in action, afterAction method (in controller .php) doesn't work! how can i fix this problem?
note: I cannot use beforeAction because I am generating a variable in my Activity and I am using that in afterAction thanks in advance ...
public function actionHsh()
{
$this->hesam= 502;
$this->redirect(array('charge/printMyCharge'));
}
And in CController
protected function afterAction($action)
{
$number = $this->hesam= 502;
}
+3
source to share
2 answers
Let's start with "why doesn't this work?" Since it is CController::redirect()
defined as follows:
public function redirect($url,$terminate=true,$statusCode=302)
{
if(is_array($url))
{
$route=isset($url[0]) ? $url[0] : '';
$url=$this->createUrl($route,array_splice($url,1));
}
Yii::app()->getRequest()->redirect($url,$terminate,$statusCode);
}
and is CHttpRequest::redirect()
defined as follows:
public function redirect($url,$terminate=true,$statusCode=302)
{
if(strpos($url,'/')===0 && strpos($url,'//')!==0)
$url=$this->getHostInfo().$url;
header('Location: '.$url, true, $statusCode);
if($terminate)
Yii::app()->end(); // Notice this? We only stop when $terminate is true
}
Essentially, you can do two things.
1) Use redirect($url, false)
to avoid completion
2) extend the method redirect
in your controller:
class Foo extends CController
{
public function redirect($url,$terminate=true,$statusCode=302)
{
if (method_exists($this, 'afterAction')) {
$this->afterAction(null);
}
parent::redirect($url,$terminate,$statusCode);
}
}
+4
source to share