How to return errors from a model back to the template? I'm working on validation with Craft. I have a custom plugin that allows public submission. However, I want to make sure I can pass errors back to the template. The key is trying to make my code as "dynamic" as possible. Meaning I do not want to specify the errors one by one.

Here is my sample controller (keep in mind I don't care what the model says is required, trying to keep the code agnostic of the model.)

public function actionSave() {

    // require a post request
    $this-&gt;requirePostRequest();

    // assign specific fields we are listening for
    $post = craft()-&gt;request-&gt;getPost('fields');

    // create a new Request model
    $model = MyModel::populateModel($post);

    // validate the model attributes
    if ($model-&gt;validate()) {
        // save the record

        // redirect to posted url
    }

    $errors = $model-&gt;getAllErrors();

    craft()-&gt;urlManager-&gt;setRouteVariables(array(
        'errors'    =&gt; $errors
    ));

}


Using $model-&gt;getAllErrors() returns an array as listed below:

array
(
    0 =&gt; 'Name cannot be blank.'
    1 =&gt; 'Details cannot be blank.'
    2 =&gt; 'Email is not a valid email address.'
)


How would I return that array to specific fields in my template like so:

{% if errors.email is defined ? errors.email | length %}
    &lt;div data-alert class="alert"&gt;
        {{ errors.email }}
    &lt;/div&gt;
{% endif %}
If you use $model-&gt;getErrors() instead, it should return a multidimensional array of errors indexed by attribute name like so:

array(
    'email' =&gt; array(
        'First email error.',
        'Second email error.',
    ),
    'firstName' =&gt; array(
        'First firstName error.',
    ),
);


Or you can get errors specifically for an attribute like so:

$model-&gt;getErrors('email');


Then update the template to check for the errors, since it is now a multidimensional array that's returned.

{% if errors.email is defined ? errors.email | length %}
&lt;div data-alert class="alert"&gt;
    {% for error in errors.email %}
        {{ error }}
    {% endfor %}
&lt;/div&gt;
{% endif %}