1

I've been implementing a user account page with Craft Commerce and copied over the template found here: https://docs.craftcms.com/v3/dev/examples/user-profile-form.html#simple-profile

The issue is though that the form doesn't seem to show any errors for individual fields, you just get the generic error message in the flash response.

If you take the example from the above link and enter an intentionally invalid email address (e.g a random string) theres no error response for the email field, just a generic "Couldn't Save User." response.

I've tried dumping out {{ craft.app.session.get('error') }} in an attempt to see if theres some extra data and its just the above error.

Am I missing something here, or is it just not possible to get field based error messages out of Craft CMS / Craft Commerce?

1

Errors for the users/save-user action are recorded against the user object, not the session object. If the user is logged-out, the object is named user but if they are logged-in you must use currentUser.

Generally speaking you can retrieve errors from Yii objects in several ways, but for field-by-field errors, I prefer the simplicity of getFirstError() (You might also want to use getErrors() or getErrorSummary()). Here's what I'm using for each question:

{% set user = currentUser ?? user ?? null %}
...

<li class="{{ user is defined and user.getFirstError('email') ? 'has-error' }}">
    <label for="email">Email <em>&bull;</em></label>
    <input required id="email" type="email" name="email" value="{{ user is defined ? user.email }}">
    {% if user is defined and user.getFirstError('email') %}
        {% include '_partials/fieldErrors.twig' with { errors: user.getErrors('email') } %}
    {% endif %}
</li>

(You could of course use a macro instead of an include as many examples demonstrate).

fieldErrors.twig:

{% if errors %}
    <ul>
        {% for error in errors %}
            <li>{{ error }}</li>
        {% endfor %}
    </ul>
{% endif %}
| improve this answer | |
  • Hmm I think there must be something not quite configured correctly somewhere with my install then. Using the exact form example on the docs mentioned above returns no errors at all for the fields using your example, just the generic flash message. If I dump out user.getErrors() or user.getFirstError('email') when I've intentionally left an email field blank or put a random string in it always just returns an empty array. I'll keep digging! Thanks for taking the time to reply though – Sk446 Jul 7 at 10:34
  • Ah yes apologies, my example is for logged-out users. For logged-in users like the example form in the docs, you'll need to use currentUser. I'll update the answer. – James Smith Jul 7 at 10:46

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.