As far as I know there is no way to assign a 'group' using an entries fieldType
. What I would likely do is create a category group called 'User Groups' (userGroups) that mirror my groups, with fields for 'title' and 'groupId'.
- Group Title 1 -> 1,
- Group Title 2 -> 2,
- Group Title 3 -> 3,
- etc.
(Unfortunately, I think the only way to get the groupId is to look in the database craft_usergroups
table. Although the code below could probably be adapted to use the group handle if needed.)
Then create a categories fieldType called 'authorizedGroups', and add it to the video channel's fieldLayout
(or wherever else you need it). The client would then be able to select groups via the authorizedUserGroups
field that have authorization to the video.
In your template(s) you can then check for videos related to the authorizedGroups
that match the currentUser.group
and display content accordingly.
First, on your videos index page you would only want to only show links to the videos that the user has authorization to view.
{% if currentUser %}
{# create an array of the currentUser.groups Ids #}
{% set currentUserGroupIds = [] %}
{% for group in currentUser.groups %}
{% set currentUserGroupIds = currentUserGroupIds|merge([group.id]) %}
{% endfor %}
{# find all userGroupCategories that match currentUserGroupIds #}
{% set userGroupCategories = craft.categories.group('userGroups').find({
groupId: currentUserGroupIds
}) %}
{# find all the videos related to userGroupCategories #}
{% set entries = craft.entries.section('videos').relatedTo(userGroupCategories) %}
<ul>
{% for entry in entries %}
<li><a href={{ entry.url }}>{{ entry.title }}</a></li>
{% endfor %}
</ul>
{% endif %}
Then on the video detail page you would use a conditional that redirects any unauthorized users to a 401 page (or to any other page that you choose).
{% set userIsAuthorized = false %}
{% for group in entry.authorizedUserGroups %}
{% if currentUser.isInGroup( group.groupId ) %}
{% set userIsAuthorized == true %}
{% endif %}
{% endfor %}
{% if not userIsAuthorized %}
{% redirect 401 %}
{% endif %}
{# display video #}
...
Update: There was a significant code error that did not account for the fact that user.groups returns an array of groups rather than a single group. I rewrote the code to handle this. Untested, and probably still contains errors, but should be closer at least.