3

When working with a custom form that posts to a plugin function - what's the best way to return errors that would be displayed like the forgot password code example below

    {% if errors is defined %}
        <ul class="errors">
            {% for error in errors %}
                <li>{{ error }}</li>
            {% endfor %}
        </ul>
    {% endif %}
4

I just return the form model object back to the template. Yii has built in validation and error handling within the models themselves. In the example email is the instance of your form's model.

The template:

{% if email is not defined %}
    {% set email = craft.postmaster.email() %}
{% endif %}

{% for error in email.getAllErrors() %}
    <p>{{ error }}</p>
{% endfor %}

<p>
    <label for="toEmail">To Email</label><br>
    <input type="text" id="toEmail" name="toEmail" value="{{ email.toEmail }}" />
    {% if email.getError('toEmail') %}
    <label for="toEmail">{{ email.getError('toEmail') }}</label>
    {% endif %}
</p>

The controller:

$model = new Postmaster_EmailFormModel(craft()->request->getPost());

if(!$model->validate())
{ 
    // Prepare a flash error message for the user.
    craft()->userSession->setError(Craft::t('The email could not be sent.'));

    craft()->urlManager->setRouteVariables(array(
        'email' => $model
    ));
}
else
{
    $event = new Event($this, array(
        'email' => $model
    ));

    craft()->postmaster_forms->onEmailFormSend($event);

    $this->redirect(craft()->request->getPost('redirect'));
}
| improve this answer | |

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.