Is there a way to check whether a user is a group member when the user visits the group page? I have some blocks that should be hidden if an user is not a member.
1 Answer
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
-
Thanks! Where should I put this code? And is het possible to make a twig variabele, so I can do a if statement in a twig file? Feb 20, 2021 at 7:41
-
Oh, sorry, I didn't read your post clearly to see you were looking for block visibility based on membership. My code won't help with that.– JaypanFeb 20, 2021 at 8:11
-
-
2Nothing module based unfortunately, hopefully someone else will pop in. I've updated my post with a little more information, but implementing it requires an understanding of Drupal development, and how to create Drupal modules. The link provided explains how to create a condition plugin. These plugins are the options you have on block settings pages to determine whether a block should be shown or not.– JaypanFeb 20, 2021 at 8:16
-
1I created a tutorial that explains how to do what you want, though you'll need to first learn how to create Drupal modules to follow it. I've linked to it in my response above.– JaypanFeb 20, 2021 at 23:51