1

In a plugin I am using registerSiteRoutes to route URL requests to a controller to handle some user validation before rendering the appropriate template. For example:

public function registerSiteRoutes()
{
    return array(
        'some-path-to/(?P<template>template-name)/(?P<entryId>\d+)' => array('action' => 'myPlugin/handleRequest'),
    );
}

The handleRequest controller looks something like this:

public function actionHandleRequest(array $variables = array())
{
    if (!craft()->request->isSiteRequest())
    {
        throw new HttpException(404);
    }

    // Do some conditional checks

    // If everything is OK, load requested template
    if (craft()->myPlugin->doChecks($userId, $entry))
    {
        $variables['entry'] = $entry;
        $this->renderTemplate('statement/_'.$variables['template'], $variables);
    }
}

The rendered template includes a form that submits to another action controller in the plugin to handle creation of a number of entries based on the submitted values.

How can I pass the error messages (if any) back to the submitted form (that is accessed via the site route set in the plugin)?

I've tried removing the site route and accessing the template directly and this works. However, it also means that I need to add in a load of conditional logic to control access to the template in the template itself. I'd rather extract the logic into a plugin controller as I did before as it makes the templates a lot cleaner and separates out the logic.

2

Not really a direct answer to your question, but you could also perhaps remove the additional controller routing business and move your conditional logic into a plugin variable (or service method called from your variable).

{% if craft.myPlugin.everythingsOk(entry) %}
    // everything's ok, render template
{% endif %}

Your variable:

public function everythingsOk($entry)
{
    // Do some conditional checks

    if (craft()->myPlugin->doChecks($userId, $entry))
    {
        return true;
    }
    return false;
}
  • Ah, that's a different way of thinking about it. I was primarily using the routing method as it enforces a check for a logged in user by default as only logged in users can access action controllers so I got an {% if currentUser %} check for free. It does make the error checking more complicated though, so your idea is probably better overall, thanks! – Steve Rowling Apr 20 '15 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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