Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defect in afterAction in Yii

when i use redirect in an action , afterAction method (in controller.php) does not work !! how can i fix this problem ?

note:i can not use beforeAction because i am generating a variable in my action and i use this 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;

    }
like image 498
hesam shafiee Avatar asked Oct 27 '25 03:10

hesam shafiee


1 Answers

Let's start with "why is it not working?". Because CController::redirect() is defined like this:

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 CHttpRequest::redirect() is defined like this:

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 there's two things you can do.

1) Use redirect($url, false) to avoid the termination

2) extend the redirect method 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);
    }
}
like image 142
h2ooooooo Avatar answered Oct 28 '25 18:10

h2ooooooo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!