2

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);
    }
}

1 Answer 1

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
        ));
    }
}
8
  • > 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
    Commented Oct 21, 2015 at 18:06
  • You're using a hidden input named 'action', correct? buildwithcraft.com/docs/plugins/…
    – Brad Bell
    Commented Oct 21, 2015 at 18:18
  • Not at all. I have defined no routes or anything other. I have explicitly called the URL for testing purpose.
    – Volatil3
    Commented Oct 21, 2015 at 18:34
  • 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
    Commented Oct 21, 2015 at 18:37
  • Unable to resolve the request http://site.craft.dev/actions/pluginName/Controller/actionMethod
    – Volatil3
    Commented Oct 21, 2015 at 18:50

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.