2

In order to add a node to any group in Drupal 8, I use the following code.

$group->addContent($node, 'group_node:article');

Now, for removing content from a group, I have tried $group->removeContent($node, 'group_node:article'); and $group->removeContent($node); without success. All I obtained is the following error message.

Error: Call to undefined method Drupal\group\Entity\Group::removeContent() in Drupal\my_valetop_extras\Plugin\WebformHandler\CustomWebformHandler->submitForm()

Finally, I have managed to remove content from a group using this code.

$type = 'group_node:' . $node->getType();
$current_node = $group->getContent($type, ['entity_id' => $node_id]);
$content = array_values($current_node)[0];
$content->delete();

But believe I can remove a single node from a group with a simple line of code.

How can I achieve it?

2 Answers 2

1

I believe that function was overlooked by the developers. In the issues queue for the Group module, which is what your error message refers to, I can see that the inverse of addMember(), removeMember(), was added later in the project's life. It seems reasonable to suppose that the inverse of addContent() was also overlooked, with the only difference being that it has remained unimplemented to this day.

There are no functions with names hinting at content-removing behaviour evident in the module's GroupInterface definition, so I recommend opening a new issue with the project to let them know about the gap.

0

This was my approach for programmatically adding and removing a node from a group on update. A removeContent() function would be helpful. However for my situation, I had to check if the entity was in the Group anyways, which gave me the GroupContent object that I could delete to remove the entity from the group.

/**
 * Implements hook_ENTITY_TYPE_update().
 */
function hook_node_update(EntityInterface $entity) {
    ...
    if (!empty($group = Group::load(1))) {
      $type = 'group_node:' . $entity->getType();
      $group_content = false;
      // Search for this entity in the group.
      $group_content_search = $group->getContent($type, ['entity_id' => $entity->id()]);
      if (!empty($group_content_search)) {
        $group_content = reset($group_content_search);
      }
    
      // Add entity to group.
      $group->addContent($entity, $type);

      ...
    
      // Remove entity from group.
      if (!empty($group_content)) {
        $group_content->delete();
      }
    }
    ...

Your Answer

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