yii2 redirect in controller action does not work?

Andreas picture Andreas · May 27, 2014 · Viewed 108.4k times · Source

I am posting a form to /user/save in order to save user data. The problem occurs when i try to redirect the user if the $_SERVER['REQUEST_METHOD'] is NOT 'post'.

My user controller code

namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\MyUser;

class UserController extends Controller {

public function actionSave() {

    if(!Yii::$app->request->getIsPost()) {
       $this->redirect('/user/index',302);
       exit(0);
   }

   //do something to save user submitted data       
}

}//~CLASS

The is no way to get the redirection to work. Although !Yii::$app->request->getIsPost() is false the call to $this->redirect does nothing!

Any help appreciated.

Answer

Dency G B picture Dency G B · May 28, 2014

In Yii2 we need to return() the result from the action.I think you need to add a return in front of your redirect.

  return $this->redirect(['user/index']);