Show All Back-end Validation Errors From an “Entry Form” Submission
Problem
I have an entry form on the front-end of my site that users can publicly submit to create entries in my channel. After the form submits, instead of listing out each erroneous field’s error under the field itself, how do I get a list of all the errors in one go? The example shown in the docs only shows how to get an error per field but not in one big list like:
Errors:
- First Name cannot be blank.
- My Custom Field cannot be blank.
- Etc cannot be blank.
Solution
Use this code:
{% if entry is defined and entry.getErrors()|length %}
<ol>
{% for list in entry.getErrors() %}
{% for error in list %}
<li>{{ error }}</li>
{% endfor %}
{% endfor %}
</ol>
{% endif %}
First, we’re checking if the entry is defined, because if there’s an error, the entry
variable will be sent back when the page reloads. This variable isn’t available though when initially arriving at the page.
Second, we’re going to run the getErrors()
method to get an array of errors back (if there are errors). Since it returns an array, we use |length
to see if there’s anything in it.
An example of this returned array would look like this:
array(2) {
["title"]=>
array(1) {
[0]=>
string(22) "Title cannot be blank."
}
["myCustomField"]=>
array(1) {
[0]=>
string(32) "My Custom Field cannot be blank."
}
}
You can see they are arrays within an array. Thus, not only do you need to loop through the fields in the top array, you then need to loop through each of the errors associated with that field. In most cases, there will only be one error per field, but it’s possible there could be more.
Discussion
Add whatever classes you need to style the error message, throw it in a macro, add more HTML if you want, but you mainly need to check for existing errors and then loop through them and that’s it.
It should be noted that you have no control how the messages come back from the server or if you can wrap part of the message in HTML for special styling.
Submitted by Ryan White on 16th July, 2018