2

If I have a field of checkboxes, I'd like to be able to access them by the name of each checkbox as the variable name, and the 0 or 1 checked state as the value. Said variables need to be accessible beyond the for loop.

For example (doesn't work):

{% for checkbox in checkboxes %}
    {% set {{ checkbox }} = checkbox.selected %}
{% endfor %}

I've looked into things and seen answers mentioning _context, attribute(), and the like, but haven't been able to get anything to work.

In short, if I have a checkboxes field with a single checkbox whose name is my_checkbox, label is "My Checkbox", and is checked in an entry, I'd like to be able to use {{ my_checkbox }} to output "1" (i.e. it's checked).

  • You want to dynamically create Twig variables with the names based on selected labels in a checkbox field? – Brad Bell Aug 18 '17 at 22:01
  • I believe so, yes. I think in PHP it's called "variable variables"...? – Sandwich Aug 18 '17 at 23:41
  • I can't image the use-case for this. :) But I don't think it'll be possible from Twig alone. Are you comfortable with PHP/Craft plugins? – Brad Bell Aug 18 '17 at 23:56
  • The use case was to be able to refer to the checkbox value outside the for loop. I've since reread the docs for Checkboxes and found entry.checkboxFieldHandle.contains('tequila'). >.< – Sandwich Aug 19 '17 at 16:09
  • Ahh... would you mind adding what worked for you as an official answer? – Brad Bell Aug 20 '17 at 17:30
2

So I had missed the entry.checkboxFieldHandle.contains('tequila') line in the docs, which allows me to access the checkbox values outside the for loop.

| improve this answer | |

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.