How can I programmatically add users to an organic group?
-
Welcome to Drupal Answers! Since the question is about code, we expect to see the code you wrote so far. If you are asking a question about code before attempting to write code, you are asking the question too early.– apaderno ♦Feb 10, 2022 at 20:06
-
i have tried this but not working ..$membership = Og::createMembership($gid, $account);$membership->save();– ankurFeb 11, 2022 at 7:32
1 Answer
Something like the following should work; replace $userId
& $groupId
with approriate values
// Get a User entity via ID
$user = \Drupal\user\Entity\User::load($userId);
// Get a Group entity via ID
$group = \Drupal\group\Entity\Group::load($groupId);
// Add member and save
$group->addMember($user);
$group->save();
You can use the following to get the currently logged in userID
$userId = \Drupal::currentUser()->id()
-
Getting error like "Error: Class 'Drupal\group\Entity\Group' not found "i think this above solution for Group module but want to add in Organic Group module (og_group) not in the Group module.– ankurFeb 10, 2022 at 13:30