Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use of user group field in element queries with multiple groups #23

Open
wallacio opened this issue Feb 16, 2025 · 2 comments
Open

Use of user group field in element queries with multiple groups #23

wallacio opened this issue Feb 16, 2025 · 2 comments
Labels

Comments

@wallacio
Copy link

wallacio commented Feb 16, 2025

Question

Given the situation where:
a) a user can belong to multiple groups
b) an entry with this User Group Field can have many user groups checked
c) the checked groups in b) dictate which user groups can see that entry

I'd like to be able to retrieve, via an element query, entries that the current user is allowed to see. Given the example in the docs:

{% set userGroup = craft.app.userGroups.getGroupByHandle('myUserGroup') %}

{% set articlesQuery = craft.entries()
    .section("news")
    .userGroupFieldHandle( userGroup.uid )
    .orderBy("postDate DESC")
    .limit(6)
%}

This doesn't appear to work if the User Group Field uses checkboxes (at least, an element query doesn't return anything even when passing a valid UID as a basic string as a parameter in the element query like the example above).

Is there anything I can pass to the User Group Field in an element query, or a way to form the query in such a way that it'll do what I want? I've tried pasting in valid UIDs as a string and as an array of strings to at least see if it's possible, even before working out the user's permission groups UIDs to use those instead (Sticking in canAccess would be nice, but...)

Essentially, I need a "get me all the entries in section 'news' that have the intersection of the user's groups and the entry's checked values in the User Groups field".

@engram-design
Copy link
Member

Can you confirm what Craft version you're on? This is working for Craft 4, but not for Craft 5.

Fixed for the next release. To get this early, run composer require verbb/user-group-field:"dev-craft-5 as 4.0.0".

@wallacio
Copy link
Author

Sorry Josh, completely forgot to add version!!
Yes, Craft 5.6.6 (User Group Field 4.0.0).

I've updated the dependency and this seems to be working a treat. As per standard element queries, it's possible to pass in an array of group UIDs if the user belongs to many.

Great job, thanks for a really quick answer and fix. Appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants