I cant get this to work.

I'm doing a post to a controller action. From that action I'm doing a lot of validations, db insert, file uploads etc.

Coming from Laravel Im used to is doing like this: (example with no real variables or methods. Just for visual presentation)

  return redirect("controller-url")->withErrors([$model->errors]);
// Next steps...

From what I can read in the docs Craft recommend posting to the same page to handle errors and pass the model down to the view, but then doing a page refresh will do the same again so I dont like that.

My Controller is like this :

Index (Renders index template)

public function actionIndex()


public function actionPost()
    return $this->redirect("url-to-index-action");

So the setError() works fine but I want to the pass all the errors from the model to the index action after a redirect and then down to the twig template. How?

1 Answer 1


In Yii2 there is no such a thing as "redirectWithErrors". Usually you have 2 scenarios

  1. There are validation errors -> display the form again with those errors
  2. Successful -> redirect

The first one doesn't require a redirect. You just return null in your controller and Yii2 will route the to the url specified via GETparameter.

So you can have a form like this.

<form method="post" action="myUrl">
    <input type="hidden" name="action" value="mycontroller/save">

Yii2 will do the following

  1. Route to your controller and hit the save action
  2. When you redirect or return a valid object of type yii\web\Response or a string that can be converted into that it will return the Response
  3. When you don't return something it will route the request a second time with your get param myUrl, that can be treated as you routeWithErrors function because you set the errors Craft::$app->getUrlManager()->setRouteParams(['model' => $model]) and have then access to these parameters.

If you really dislike this, you could use return Craft::runAction('controller/action', $parameters); to run a controller action with certain values

Edit Usually you want to leave action="myUrl" blank and don't insert it. That way Yii2 will automatically reload the current route so you can dispaly your errors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.