1

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

1 Answer 1

4

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

6
  • 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.
    – Jaypan
    Feb 20, 2021 at 8:11
  • Oh, do you have any other suggestions for me? Feb 20, 2021 at 8:11
  • 2
    Nothing 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.
    – Jaypan
    Feb 20, 2021 at 8:16
  • 1
    I 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.
    – Jaypan
    Feb 20, 2021 at 23:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.