Skip to content

Commit 4e55159

Browse files
committed
Ensure form errors are rendered in a logical order
If multiple fields have errors, we should render them in the order the fields appear on the page. Non-field errors should display last. Previously we were relying on `form.errors` to decide the order, which means that errors were displayed in the order they happened to be added in.
1 parent a8faf51 commit 4e55159

2 files changed

Lines changed: 11 additions & 2 deletions

File tree

manage_breast_screening/record_a_mammogram/forms.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,12 @@ def __init__(self, *args, **kwargs):
6868
for field_name, _ in self.STOPPED_REASON_CHOICES:
6969
self.fields[f"{field_name}_details"] = forms.CharField(required=False)
7070

71+
# Ensure that the field order matches the order we want to render in
72+
details_fields = [
73+
f"{field_name}_details" for field_name, _ in self.STOPPED_REASON_CHOICES
74+
]
75+
self.order_fields(["stopped_reasons"] + details_fields + ["decision"])
76+
7177
stopped_reasons = forms.MultipleChoiceField(
7278
choices=STOPPED_REASON_CHOICES,
7379
required=True,

manage_breast_screening/templates/wizard_step.jinja

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,11 @@
1717
{% if form.errors %}
1818
{% set ns = namespace(errors=[]) %}
1919

20-
{% for field, messages in form.errors | items %}
21-
{% set ns.errors = ns.errors + [{"text": ",".join(messages), "href": "#" ~ messages.field_id}] %}
20+
{% for field in form %}
21+
{% set ns.errors = ns.errors + [{"text": ",".join(field.errors), "href": "#" ~ field.auto_id}] %}
22+
{% endfor %}
23+
{% for error_list in form.non_field_errors() %}
24+
{% set ns.errors = ns.errors + [{"text": ",".join(error_list)}] %}
2225
{% endfor %}
2326

2427
{{ errorSummary({

0 commit comments

Comments
 (0)