- for each choice in the choice field, there is a field for providing more details
- the fields are basically all the same
- but these need to be unique fields on the django forms, since all are rendered to the page, only the visibility changes when you select different options
- when dynamically adding fields, it's important to preserve the correct field order, so that errors are reported in form order
- the value could be persisted to a single model field, since the fields are mutually exclusive
- but then you need to map back the appropriate field when passing
initial
- the conditional field's value is either required in all cases where the parent field is set, or it depends on the particular value
- values from the conditional fields that are not visible should be ignored
for choice_value, _ in self.STOPPED_REASON_CHOICES:
details_field_name = f"{choice_value}_details"
self.fields[details_field_name] = CharField(
required=False, label="Provide details"
)
if (
"stopped_reasons" in cleaned_data
and "other" in cleaned_data["stopped_reasons"]
):
if not cleaned_data.get("other_details"):
self.add_error(
"other_details", "Explain why this appointment cannot proceed"
)
for field_name, value in self.cleaned_data.items():
if field_name.endswith("_details") and value:
reasons_json[field_name] = value
{% for choice_value, _ in form.STOPPED_REASON_CHOICES %}
{% do form.stopped_reasons.add_conditional_html(choice_value, form[choice_value + "_details"].as_field_group()) %}
{% endfor %}