How do I set a condition to only show a block to members of a group?
Question
I use the Drupal Group module. Is there a way to check if a logged-in user is an groupmember or not when the user visits the grouppage? I have some blocks that should be hidden if an user is not a member.
La solution
Programmatically you can use Group::getMember()
to determine if an account is a member of a group.
if ($group->getMember(\Drupal::currentUser())) {
// the current user is a member of the group.
}
Note that Group::getMember()
returns a GroupMembership
entity.
You could then create a condition plugin, using the above methodology to determine if the current user is a member of the group. I've created a tutorial on how to use the Conditions API to create conditions plugins, using this example of a condition where a member is a member of the group: https://www.jaypan.com/tutorial/custom-block-visibility-plugins-and-condition-plugin-api