Drupal Group模块,以编程方式将用户添加到具有特定角色的组中

问题描述 投票:0回答:1

此问题与Drupal 8 Group modulehttps://www.drupal.org/project/group

相关

我很困惑,并且需要有关如何以编程方式将用户添加到具有特定角色的组的帮助。我正在尝试通过Feed导入将用户分配到组和角色,但无法弄清楚如何。详细地说,假设我们有两个组DEV和QA。 DEV属于组类型A,QA属于组类型B。两个组类型A和B都具有角色X,Y和Z(组角色)。现在,我有一个用户$ account,我希望将其添加到具有角色Y的QA组中。有人可以提供帮助并说明以编程方式实现此目标的方式吗?代码示例/代码片段将特别有用。

drupal module drupal-8 drupal-modules
1个回答
1
投票

这里有些旧代码可能会有所帮助。不得不从git中挖掘出来,几年前删除了该项目不再需要的东西。可能已弃用!

您正在加载组并使用$ group-> addMember()函数。我刚刚添加了该成员,但您可以添加第二个参数,该参数是一个关联数组,可以指示要添加的角色。

$new_user = \Drupal\user\Entity\User::load($some_user_id);

// Get the group entity.
$gid = $form_state->getValue('gid');
$group = \Drupal::entityTypeManager()
  ->getStorage('group')
  ->load($gid);

// Add user as a member of the group.
$group->addMember($new_user);

// Set the owner of the group to be the user.
$group->set('uid', $new_user_id);

// Save changes to group. Anything below here should only be changes to
// Group Content.
$group->save();
$tags = $group->getCacheTagsToInvalidate();
Cache::invalidateTags($tags);
© www.soinside.com 2019 - 2024. All rights reserved.