<p>So, it turns out (as is often the case) that posting the problem makes you look at it in a fresh light, and as such I found my own solution.</p>

<p>What I needed to do (leaving this here in case someone else has a similar problem and come looking for help) was to make the following change to my rendering-controller:</p>

<p><strong>old</strong></p>

<pre><code>public function actionRenderCreateRecordCompany()
{
  $this-&gt;renderPluginTemplate('coverapp/recordCompanyCreate');
}
</code></pre>

<p><strong>new</strong></p>

<pre><code>public function actionRenderCreateRecordCompany(array &amp;variables = array())
{
  $this-&gt;renderPluginTemplate('coverapp/recordCompanyCreate');
}
</code></pre>

<p>I guess this makes sense - I didn't include it originally as my route never passed any variables to it - but of course when I use <code>setRouteVariables</code> in my controller-action I need something on the receiving end to catch it.</p>

CC BY-SA 3.0
2016-10-31T12:12:27.153Z
2016-10-31T12:12:27.153Z
Fuglsetrampen
<p>This has me a bit stumped.</p>

<p>I have two forms - posting to two different actions within the same controller. On error I am attempting to have them both display a flash-notice, as well as pass the model back to my template so that I can display the errors to the user.</p>

<p>This works as intended for one of my forms/actions, but not for the other - well, that is, the flash-message works for both, but for the latter form/action <code>model</code> is undefined in my template.</p>

<p>Some examples (I've stripped out some code to not clutter the question):</p>

<p><strong>Working action</strong></p>

<pre><code>public function actionCreateArtist()
{
  $this-&gt;requirePostRequest();
  $request = craft()-&gt;request-&gt;getPost();
  $model   = new CoverApp_ArtistModel();
  $model-&gt;setAttributes($request);
  if ($model-&gt;validate() &amp;&amp; craft()-&gt;coverApp_data-&gt;createArtist($model)) {
    craft()-&gt;userSession-&gt;setNotice('Artist created.');
    $this-&gt;redirectToPostedUrl();
  }
  craft()-&gt;userSession-&gt;setError('Unable to create artist');
  craft()-&gt;urlManager-&gt;setRouteVariables(array('model' =&gt; $model));
}
</code></pre>

<p><strong>Working form</strong></p>

<pre><code>&lt;form method="POST" class="styled-form"&gt;
  {{ getCsrfInput() }}
  &lt;input type="hidden" name="action" value="coverApp/data/createArtist"&gt;
  &lt;input type="hidden" name="redirect" value="coverapp/record-company/{{ companyId }}"&gt;
  &lt;input type="submit" value="Create artist"&gt;
&lt;/form&gt;
{{ model is defined ? 'Yes' : 'No' }}
{% set error = craft.session.getFlash('error', false, false) %}
{% if error and model is defined %}
  &lt;div&gt;
    &lt;ul&gt;
      {% for errorType in model.getErrors() %}
        {% for error in errorType %}
          &lt;li&gt;- {{ error }}&lt;/li&gt;
        {% endfor %}
      {% endfor %}
    &lt;/ul&gt;
  &lt;/div&gt;
{% endif %}
</code></pre>

<p>The example above outputs "Yes" and any errors that happened during validation/save, per-example name already taken.</p>

<p><strong>Action I am struggling with</strong></p>

<pre><code>public function actionCreateRecordCompany()
{
  $this-&gt;requirePostRequest();
  $request = craft()-&gt;request-&gt;getPost();
  $model   = new CoverApp_RecordCompanyModel();
  $model-&gt;setAttributes($request);
  if ($model-&gt;validate() &amp;&amp; craft()-&gt;coverApp_data-&gt;createRecordCompany($model)) {
    craft()-&gt;userSession-&gt;setNotice('Record company created.');
    $this-&gt;redirectToPostedUrl();
  }
  craft()-&gt;userSession-&gt;setError('Unable to create record-company');
  craft()-&gt;urlManager-&gt;setRouteVariables(array('model' =&gt; $model));
}
</code></pre>

<p><strong>Form I am struggling with</strong></p>

<pre><code>&lt;form method="POST" class="styled-form"&gt;
  {{ getCsrfInput() }}
  &lt;input type="hidden" name="action" value="coverApp/data/createRecordCompany"&gt;
  &lt;input type="hidden" name="redirect" value="coverapp"&gt;
  &lt;input type="submit" value="Create record-company"&gt;
&lt;/form&gt;
{{ model is defined ? 'Yes' : 'No' }}
{% set error = craft.session.getFlash('error', false, false) %}
{% if error and model is defined %}
  &lt;div&gt;
    &lt;ul&gt;
      {% for errorType in model.getErrors() %}
        {% for error in errorType %}
          &lt;li&gt;- {{ error }}&lt;/li&gt;
        {% endfor %}
      {% endfor %}
    &lt;/ul&gt;
  &lt;/div&gt;
{% endif %}
</code></pre>

<p>The above outputs 'No' and none of the errors that happened during validation/save, per example name already taken.</p>

<p>To further obfuscate the problem, if I have no errors during validation/save everything works peachy - which at least leads me to believe that my models are fine.</p>

<p>Any ideas?</p>

<p><strong><em>Update 31/10/2016</em></strong></p>

<p><strong>registerCpRoutes</strong></p>

<pre><code>public function registerCpRoutes()
{
  return array('coverapp/record-company/create' =&gt; array('action' =&gt; 'coverApp_Rendering/renderCreateRecordCompany'),
  'coverapp/record-company/(?P&lt;companyId&gt;[\d]+)/createArtist' =&gt; array('action' =&gt; 'coverApp_Rendering/renderCreateArtist'));
}
</code></pre>

<p><strong>rendering-controller</strong></p>

<pre><code>public function actionRenderCreateRecordCompany()
{
  $this-&gt;renderPluginTemplate('coverapp/recordCompanyCreate');
}

public function actionRenderCreateArtist(array $variables = array())
{
  $this-&gt;renderPluginTemplate('coverapp/artistCreate', $variables);
}

private function renderPluginTemplate($template, $variables = array())
{
  $oldMode = craft()-&gt;templates-&gt;getTemplateMode();
  craft()-&gt;templates-&gt;setTemplateMode(TemplateMode::Site);
  if (!$templatePath = craft()-&gt;templates-&gt;findTemplate($template)) {
    throw new Exception(Craft::t('Could not find template with path: ' . $template));
  }
  else {
    $templateContent   = file_get_contents($templatePath);
    $templateExtension = IOHelper::getExtension($templatePath, 'html');
  }
  craft()-&gt;templates-&gt;setTemplateMode($oldMode);
  if ($output = craft()-&gt;templates-&gt;renderString($templateContent, $variables)) {
    if (!HeaderHelper::isHeaderSet('Content-Type')) {
      HeaderHelper::setContentTypeByExtension($templateExtension);
    }
    HeaderHelper::setHeader(array('charset' =&gt; 'utf-8'));
    if (in_array(HeaderHelper::getMimeType(), array('text/html', 'application/xhtml+xml'))) {
      $headHtml = craft()-&gt;templates-&gt;getHeadHtml();
      $footHtml = craft()-&gt;templates-&gt;getFootHtml();
      if ($headHtml) {
        if (($endHeadPos = mb_stripos($output, '&lt;/head&gt;')) !== FALSE) {
          $output = mb_substr($output, 0, $endHeadPos) . $headHtml . mb_substr($output, $endHeadPos);
        }
        else {
          $output .= $headHtml;
        }
      }
      if ($footHtml) {
        if (($endBodyPos = mb_stripos($output, '&lt;/body&gt;')) !== FALSE) {
          $output = mb_substr($output, 0, $endBodyPos) . $footHtml . mb_substr($output, $endBodyPos);
        }
        else {
          $output .= $footHtml;
        }
      }
    }
    ob_start();
      echo $output;
      craft()-&gt;end();
    }
}
</code></pre>

CC BY-SA 3.0
2016-10-27T13:50:45.580Z
For the second form, is there another controller action that is getting called to render the form in the first place? (It’s possible to have a request get routed to a controller action using the [registerCpRoutes](https://craftcms.com/docs/plugins/hooks-reference#registerCpRoutes) hook.)
Brandon Kelly
CC BY-SA 3.0
2016-10-31T09:36:48.253Z
@BrandonKelly: Original post updated with code from both registerCpRoutes and the rendering-controller
Fuglsetrampen
<plugin-development><form><controller><error-handling>
Trouble passing errors back to form through setRouteVariables
# Trouble passing errors back to form through setRouteVariables

(Asked by: username_0 on 2016-10-26)

This has me a bit stumped.
I have two forms - posting to two different actions within the same controller. On error I am attempting to have them both display a flash-notice, as well as pass the model back to my template so that I can display the errors to the user.
This works as intended for one of my forms/actions, but not for the other - well, that is, the flash-message works for both, but for the latter form/action model is undefined in my template.
Some examples (I've stripped out some code to not clutter the question):
Working action
public function actionCreateArtist()
{
  $this->requirePostRequest();
  $request = craft()->request->getPost();
  $model   = new CoverApp_ArtistModel();
  $model->setAttributes($request);
  if ($model->validate() && craft()->coverApp_data->createArtist($model)) {
    craft()->userSession->setNotice('Artist created.');
    $this->redirectToPostedUrl();
  }
  craft()->userSession->setError('Unable to create artist');
  craft()->urlManager->setRouteVariables(array('model' => $model));
}

Working form

  {{ getCsrfInput() }}
  
  
  

{{ model is defined ? 'Yes' : 'No' }}
{% set error = craft.session.getFlash('error', false, false) %}
{% if error and model is defined %}
  
    
      {% for errorType in model.getErrors() %}
        {% for error in errorType %}
          - {{ error }}
        {% endfor %}
      {% endfor %}
    
  
{% endif %}

The example above outputs "Yes" and any errors that happened during validation/save, per-example name already taken.
Action I am struggling with
public function actionCreateRecordCompany()
{
  $this->requirePostRequest();
  $request = craft()->request->getPost();
  $model   = new CoverApp_RecordCompanyModel();
  $model->setAttributes($request);
  if ($model->validate() && craft()->coverApp_data->createRecordCompany($model)) {
    craft()->userSession->setNotice('Record company created.');
    $this->redirectToPostedUrl();
  }
  craft()->userSession->setError('Unable to create record-company');
  craft()->urlManager->setRouteVariables(array('model' => $model));
}

Form I am struggling with

  {{ getCsrfInput() }}
  
  
  

{{ model is defined ? 'Yes' : 'No' }}
{% set error = craft.session.getFlash('error', false, false) %}
{% if error and model is defined %}
  
    
      {% for errorType in model.getErrors() %}
        {% for error in errorType %}
          - {{ error }}
        {% endfor %}
      {% endfor %}
    
  
{% endif %}

The above outputs 'No' and none of the errors that happened during validation/save, per example name already taken.
To further obfuscate the problem, if I have no errors during validation/save everything works peachy - which at least leads me to believe that my models are fine.
Any ideas?
Update 31/10/2016
registerCpRoutes
public function registerCpRoutes()
{
  return array('coverapp/record-company/create' => array('action' => 'coverApp_Rendering/renderCreateRecordCompany'),
  'coverapp/record-company/(?P[\d]+)/createArtist' => array('action' => 'coverApp_Rendering/renderCreateArtist'));
}

rendering-controller
public function actionRenderCreateRecordCompany()
{
  $this->renderPluginTemplate('coverapp/recordCompanyCreate');
}

public function actionRenderCreateArtist(array $variables = array())
{
  $this->renderPluginTemplate('coverapp/artistCreate', $variables);
}

private function renderPluginTemplate($template, $variables = array())
{
  $oldMode = craft()->templates->getTemplateMode();
  craft()->templates->setTemplateMode(TemplateMode::Site);
  if (!$templatePath = craft()->templates->findTemplate($template)) {
    throw new Exception(Craft::t('Could not find template with path: ' . $template));
  }
  else {
    $templateContent   = file_get_contents($templatePath);
    $templateExtension = IOHelper::getExtension($templatePath, 'html');
  }
  craft()->templates->setTemplateMode($oldMode);
  if ($output = craft()->templates->renderString($templateContent, $variables)) {
    if (!HeaderHelper::isHeaderSet('Content-Type')) {
      HeaderHelper::setContentTypeByExtension($templateExtension);
    }
    HeaderHelper::setHeader(array('charset' => 'utf-8'));
    if (in_array(HeaderHelper::getMimeType(), array('text/html', 'application/xhtml+xml'))) {
      $headHtml = craft()->templates->getHeadHtml();
      $footHtml = craft()->templates->getFootHtml();
      if ($headHtml) {
        if (($endHeadPos = mb_stripos($output, '')) !== FALSE) {
          $output = mb_substr($output, 0, $endHeadPos) . $headHtml . mb_substr($output, $endHeadPos);
        }
        else {
          $output .= $headHtml;
        }
      }
      if ($footHtml) {
        if (($endBodyPos = mb_stripos($output, '')) !== FALSE) {
          $output = mb_substr($output, 0, $endBodyPos) . $footHtml . mb_substr($output, $endBodyPos);
        }
        else {
          $output .= $footHtml;
        }
      }
    }
    ob_start();
      echo $output;
      craft()->end();
    }
}

**Tags:** plugin-development, form, controller, error-handling
> **Comments:**
> **username_1**: For the second form, is there another controller action that is getting called to render the form in the first place? (It’s possible to have a request get routed to a controller action using the [registerCpRoutes](https://craftcms.com/docs/plugins/hooks-reference#registerCpRoutes) hook.)  
> **username_0**: @BrandonKelly: Original post updated with code from both registerCpRoutes and the rendering-controller  

---

## 1 answers

### Answer by username_0 on 2016-10-31. Score: 1 | Accepted answer

So, it turns out (as is often the case) that posting the problem makes you look at it in a fresh light, and as such I found my own solution.
What I needed to do (leaving this here in case someone else has a similar problem and come looking for help) was to make the following change to my rendering-controller:
old
public function actionRenderCreateRecordCompany()
{
  $this->renderPluginTemplate('coverapp/recordCompanyCreate');
}

new
public function actionRenderCreateRecordCompany(array &variables = array())
{
  $this->renderPluginTemplate('coverapp/recordCompanyCreate');
}

I guess this makes sense - I didn't include it originally as my route never passed any variables to it - but of course when I use setRouteVariables in my controller-action I need something on the receiving end to catch it.


---

