Commit 54d7fcc5 authored by Mamadou Diao Diallo's avatar Mamadou Diao Diallo Committed by Diao Diallo
Browse files

Issue #3301536 by diaodiallo: Update group assignment after content update

parent 36459f28
Loading
Loading
Loading
Loading
+43 −0
Original line number Diff line number Diff line
@@ -59,3 +59,46 @@ function content_to_group_node_insert(Drupal\node\NodeInterface $node) {
  }
}

/**
 * Implement hook_node_update
 */
function content_to_group_node_update(Drupal\node\NodeInterface $node) {
  $config = \Drupal::service('config.factory')
    ->getEditable('content_to_group.settings');
  $types = array_keys($config->get('types'));
  if (in_array($node->bundle(), $types)) {
    $contentToGroupUtility = new ContentToGroupUtility(\Drupal::entityTypeManager());
    $field = $contentToGroupUtility->getGroupField($node);
    if ($field !== NULL) {
      if ($node->id()) {
        $route_name = \Drupal::routeMatch()->getRouteName();
        if ($route_name != 'entity.group_content.create_form') {
          $gid = $node->get($field)
            ->getValue()[0]["target_id"];
          $group = Group::load($gid);
          if ($group !== NULL) {
            $type = 'group_node:' . $node->getType();
            // Check if its not already in the group
            $relation = $group->getContentByEntityId($type, $node->id());
            if (!$relation) {
              // Search other existing relations
              $group_contents = $contentToGroupUtility->getGroupContent($node);
              // add to new group
              $group->addContent($node, $type);
              // Remove other relations
              if ($group_contents) {
                foreach ($group_contents as $group_content) {
                  $group_content->delete();
                  Drupal::logger('content_to_group')
                    ->notice('Removed ' . $node->getType() . ': "' . $node->label() . '" from group: "' . $group_content->getGroup()
                        ->label() . '"');
                }
              }
            }
          }
        }
      }
    }
  }
}
+13 −0
Original line number Diff line number Diff line
@@ -44,4 +44,17 @@ class ContentToGroupUtility {
    return $group_field;
  }

  /**
   * Get the group content.
   */
  public function getGroupContent($node) {
    $group_contents = $this->entityTypeManager->getStorage('group_content')
      ->loadByEntity($node);
    if ($group_contents !== NULL) {
      return $group_contents;
    }

    return NULL;
  }

}