I created a custom module using the example in:


When a node is created, it is associated with a group:


Here is my module. I created in my template a reference field to the group field_group_reference

How to insert the title of the group in the message ?

Thank you


 * @file
 * Holds hook implementation for the Message Activity Stream module.

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\node\Entity\Node;
use Drupal\comment\Entity\Comment;
use Drupal\user\Entity\User;
use Drupal\message\Entity\Message;

 * Implements hook_group_insert().
function message_activity_stream_group_insert(Node $node) {
  $message = Message::create(['template' => 'mas_create_node', 'uid' => $node->get('uid')]);
  $message->set('field_group_reference', $node);
  $message->set('field_published', $node->isPublished());

For this, you need to know that a node can be in multiple groups and there is also a midlevel entity between a node an a Group called a GroupContent entity.

To retrieve the Groups for a given node you can use this code:

 $plugin_id = 'group_node:' . $node->bundle();

 // Only act if there are group content types for this node type.
 $group_content_types = GroupContentType::loadByContentPluginId($plugin_id);

  // Load all the group content for this node.
  $group_contents = \Drupal::entityTypeManager()
        'type' => array_keys($group_content_types),
        'entity_id' => $node->id(),

  /** @var \Drupal\group\Entity\GroupInterface[] $groups */
  $groups = [];
  foreach ($group_contents as $group_content) {
    /** @var \Drupal\group\Entity\GroupContentInterface $group_content */
    $group = $group_content->getGroup();
    $groups[$group->id()] = $group;

You can see this code in action in gnode_node_access() which works out access permissions for a node by checking the Groups it is attached to.

Now you have a list of groups, you can load the first one from the list and use its title.

  $group = reset($groups);
  $title = empty($group) ? '' : $group->label();
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy