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).

5
  • You want to dynamically create Twig variables with the names based on selected labels in a checkbox field?
    – Brad Bell
    Commented Aug 18, 2017 at 22:01
  • I believe so, yes. I think in PHP it's called "variable variables"...?
    – Sandwich
    Commented Aug 18, 2017 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
    Commented Aug 18, 2017 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
    Commented Aug 19, 2017 at 16:09
  • Ahh... would you mind adding what worked for you as an official answer?
    – Brad Bell
    Commented Aug 20, 2017 at 17:30

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.