<blockquote>
  <p>How to redirect with error messages?</p>
</blockquote>

<p>Generally speaking, then answer is "you don't".  You redirect on success, but if there is an error (validation or otherwise), you add those to your model, call <code>setRouteVariables</code> and let the request continue as usual.  That will reload the current page and you can pull the errors out of the model from Twig.</p>

<p>You can see the general workflow for this in a controller action in all of Craft's controllers at <code>craft/app/controllers</code>.</p>

<pre><code>class SomeController extends BaseController
{
    public function actionDoSomething()
    {
        $myModel = new MyModel();
        $myModel-&gt;myProperty = 1;

        // Validate the model
        if ($myModel-&gt;validate())
        {
            // Pass it to the service.
            if (craft()-&gt;myService-&gt;doSomething($myModel))
            {
                // Success!
                $this-&gt;redirectToPostedUrl();
            }
        }

        // Return the model back to the template so the errors can be displayed.
        craft()-&gt;urlManager-&gt;setRouteVariables(array(
            'model' =&gt; $myModel
        ));
    }
}
</code></pre>

CC BY-SA 3.0
2015-10-21T18:06:43.370Z
> craft()->urlManager->setRouteVariables(array(

It always goes to 404. I don't know why. my Form's POST URL is: `http://site.craft.dev/actions/pluginName/Controller/actionMethod`
Volatil3
CC BY-SA 3.0
2015-10-21T18:18:06.513Z
You're using a hidden input named 'action', correct? http://buildwithcraft.com/docs/plugins/controllers#posting-to-controller-actions
Brad Bell
CC BY-SA 3.0
2015-10-21T18:34:56.560Z
Not at all. I have defined no routes or anything other. I have explicitly called the URL for testing purpose.
Volatil3
CC BY-SA 3.0
2015-10-21T18:37:05.530Z
Let me re-phrase. You're supposed to be using a hidden input named 'action' (see the docs I linked to) instead of setting the value in the action of the `<form>` tag.
Brad Bell
CC BY-SA 3.0
2015-10-21T18:50:49.180Z
`Unable to resolve the request http://site.craft.dev/actions/pluginName/Controller/actionMethod`
Volatil3
CC BY-SA 3.0
2015-10-21T18:58:18.377Z
```
<input type="hidden" name="action" value="http://site.craft.dev/actions/pluginName/Controller/actionMethod">
  <input type="hidden" name="redirect" value="http://site.craft.dev/admin/pluginname">
```
Volatil3
CC BY-SA 3.0
2015-10-21T19:08:31.667Z
Ok I omitted the absolute URL and it seems to redirect as it's supposed to. Now how do I print error? in `validate()` I wrote something like: *$this->addError('logs', Craft::t('Invalid Error'));*
Volatil3
CC BY-SA 3.0
2015-10-21T19:28:11.030Z
OK figured out. By setting relative URL and using `craft()->userSession->setFlash('error', $errors[0]);` did the trick. Pls update your answer so that I accept.
Volatil3
CC BY-SA 3.0
2015-10-21T16:09:11.513Z
2015-10-21T16:09:11.513Z
Brad Bell
<p>If validation fails in plugin, how can I redirect it bank to previous URL with errors?</p>

<pre><code>craft()-&gt;urlManager-&gt;setRouteVariables(array(
    'errors'    =&gt; $errors
));
</code></pre>

<p>gives 404</p>

<p><em>My Controller:</em></p>

<p>

<pre><code>class DB_LogsController extends BaseController
{
    protected $allowAnonymous = true;
    public function actionStoreDances()
    {
        $this-&gt;requirePostRequest();
        $f = craft()-&gt;request-&gt;getPost('logs');
        $dances = new DB_LogsModel();

        $errors = $dances-&gt;getAllErrors();
        craft()-&gt;urlManager-&gt;setRouteVariables(array(
            'errors'    =&gt; $errors
        ));
        $redirectUrl = '';
        //$this-&gt;redirect('http://db.craft.dev/admin/db/',true);
    }
}
</code></pre>

<plugin-development><url>
How to redirect with error messages?
# How to redirect with error messages?

(Asked by: username_0 on 2015-10-21)

If validation fails in plugin, how can I redirect it bank to previous URL with errors?
craft()->urlManager->setRouteVariables(array(
    'errors'    => $errors
));

gives 404
My Controller:

class DB_LogsController extends BaseController
{
    protected $allowAnonymous = true;
    public function actionStoreDances()
    {
        $this->requirePostRequest();
        $f = craft()->request->getPost('logs');
        $dances = new DB_LogsModel();

        $errors = $dances->getAllErrors();
        craft()->urlManager->setRouteVariables(array(
            'errors'    => $errors
        ));
        $redirectUrl = '';
        //$this->redirect('http://db.craft.dev/admin/db/',true);
    }
}

**Tags:** plugin-development, url

---

## 1 answers

### Answer by username_1 on 2015-10-21. Score: 2

How to redirect with error messages?

Generally speaking, then answer is "you don't".  You redirect on success, but if there is an error (validation or otherwise), you add those to your model, call setRouteVariables and let the request continue as usual.  That will reload the current page and you can pull the errors out of the model from Twig.
You can see the general workflow for this in a controller action in all of Craft's controllers at craft/app/controllers.
class SomeController extends BaseController
{
    public function actionDoSomething()
    {
        $myModel = new MyModel();
        $myModel->myProperty = 1;

        // Validate the model
        if ($myModel->validate())
        {
            // Pass it to the service.
            if (craft()->myService->doSomething($myModel))
            {
                // Success!
                $this->redirectToPostedUrl();
            }
        }

        // Return the model back to the template so the errors can be displayed.
        craft()->urlManager->setRouteVariables(array(
            'model' => $myModel
        ));
    }
}

> **Comments:**
> **username_0**: > craft()->urlManager->setRouteVariables(array(  It always goes to 404. I don't know why. my Form's POST URL is: `http://site.craft.dev/actions/pluginName/Controller/actionMethod`  
> **username_1**: You're using a hidden input named 'action', correct? http://buildwithcraft.com/docs/plugins/controllers#posting-to-controller-actions  
> **username_0**: Not at all. I have defined no routes or anything other. I have explicitly called the URL for testing purpose.  
> **username_1**: Let me re-phrase. You're supposed to be using a hidden input named 'action' (see the docs I linked to) instead of setting the value in the action of the `<form>` tag.  
> **username_0**: `Unable to resolve the request http://site.craft.dev/actions/pluginName/Controller/actionMethod`  
> **username_0**: ``` <input type="hidden" name="action" value="http://site.craft.dev/actions/pluginName/Controller/actionMethod">   <input type="hidden" name="redirect" value="http://site.craft.dev/admin/pluginname"> ```  
> **username_0**: Ok I omitted the absolute URL and it seems to redirect as it's supposed to. Now how do I print error? in `validate()` I wrote something like: *$this->addError('logs', Craft::t('Invalid Error'));*  
> **username_0**: OK figured out. By setting relative URL and using `craft()->userSession->setFlash('error', $errors[0]);` did the trick. Pls update your answer so that I accept.  

---

