2

If you have a checkbox field on an entry type, how do you display all the selected values for an entry in a template with twig?

Using this for page permissions via user groups. We have a plugin that adds a new field type "user groups". It lists all groups (which we have many) on the admin page of each entry. We want to check which groups will have access and then limit the page to users in that group only.

edit: not using a standard checkbox field but a new field (via plugin). https://github.com/quebecstudio/usergroupfield

1 Answer 1

1

You get all available options with the options attribute and you can check if it is selected in the current entry with option.selected

{% for opt in entry.checkboxFieldHandle.options %}
    <label>
        <input name="fields[checkboxFieldHandle][]" type="checkbox" value="{{ opt.value }}">
        {{ opt.label }}
        {% if opt.selected %}
            I'm selected
        {% endif %}
    </label>
{% endfor %}

But to be honest I don't really understand your second part

Edit
As for your field, you can display all the selected values with

{% set selectedUserGroupIds = entry.userGroupFieldHandle %}
{% for userGroupId in selectedUserGroupIds %}
    {% set usergroup = craft.userGroups.getGroupById(userGroupId) %}
    {{ usergroup.name }}
{% endfor %}
6
  • Maybe it's the field I'm using but that standard methodology is not working. I am using this plugin: github.com/quebecstudio/usergroupfield It creates a new field called usergroups and when added to a "section" it shows all the user groups in the system with empty checkboxes beside each. Hoping to use this to create very flexible page permissions (i.e. edit entry 1 and assign user group A,B, and F, then only users in groups A,B or F can access this page).
    – Max
    Commented Dec 20, 2017 at 20:55
  • Yes you can do this with the plugin. But you don't need to display the selected values in your frontend to achieve that. Commented Dec 20, 2017 at 21:00
  • Hi Robin, was trying to display the values selected as a visual check to make sure it was grabbing the right data. There's not a ton of documentation around that plugin so I'm not sure exactly how to get it working as desired.
    – Max
    Commented Dec 20, 2017 at 22:06
  • Well, I'm not really sure what you want... entry.userGroupFieldHandle contains an array with all selected usergroup ids and an empty string if nothing was selected. You can check if it is not empty, loop through the results and get the selected group by id Commented Dec 21, 2017 at 8:37
  • I did get the id's to display, but not sure how to translate that into giving permissions. Thanks for your help.
    – Max
    Commented Dec 21, 2017 at 20:14

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.