Grav CMS: how to access form labels from template (checkboxes)

151 views Asked by At

With a form including a checkboxes field and an email or save action set up, is there a way to access the individual checkboxes' labels from within the template?

So far, I've only been able to access the ids and values of the checkboxes, like so:

{%- for field in form.fields -%}
    {%- set value = form.value(field.name) -%}
    {%- if field.type == "checkboxes" -%}
        {%- for key in in value|keys -%}
            {{- key ~ ": " ~ value[key] ~ "\r\n" -}}
        {%- endfor -%}
    {%- endif -%}
{%- endfor -%}
1

There are 1 answers

0
passerby On

To get the default values and labels of a checkboxes field, you could try the following:

The field definition of the form:

fields:
   ...
   myfield:
      type: checkboxes
      label: A 'checkboxes' field
      default:
            option1: true
            option2: false
      options:
            option1: Option 1
            option2: Option 2
      use: keys

Inside Twig template:

{% for field in form.fields %}
   {% if field.type == 'checkboxes' %}
      {% for key, label in field.options %}
         <p>{{ label ~ ': ' ~ (field.default[key] ? 'true' : 'false') }}</p>
      {% endfor %}
   {% endif %}
{% endfor %}

Result in browser:

enter image description here