-1

I installed the Message module on my site :

https://www.drupal.org/project/message

And I created a custom module from the Message Example sub-module.

Here is the content of the message_activity_stream.info.yml file :

name: Message Activity Stream
type: module
description: "Message Activity Stream for working with the message module."
# core: 8.x
package: Message
dependencies:
 - message
 - token
 - group
 - node
 - commerce_store
 - commerce_product
 - comment

# Information added by Drupal.org packaging script on 2018-04-23
version: '8.x-1.0-rc2'
core: '8.x'
project: 'message'
datestamp: 1524519795

Here is the content of the message_activity_stream.module file :

<?php

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

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\group\Entity\Group;
use Drupal\node\Entity\Node;
use Drupal\comment\Entity\Comment;
use Drupal\commerce_store\Entity\Store;
use Drupal\commerce_product\Entity\Product;
use Drupal\user\Entity\User;
use Drupal\profile\Entity\Profile;
use Drupal\message\Entity\Message;

/**
 * Implements hook_profile_insert().
 */
function message_activity_stream_profile_insert(Profile $profile) {
  $message = Message::create(['template' => 'mas_create_node', 'uid' => $profile->get('uid')]);
  $message->set('field_profile_reference', $profile);
  $message->set('field_published', $profile->isPublished());
  $message->save();
}

/**
 * Implements hook_commerce_store_insert().
 */
function message_activity_stream_commerce_store_insert(Store $commerce_store) {
  $message = Message::create(['template' => 'mas_create_store', 'uid' => $commerce_store->get('uid')]);
  $message->set('field_store_reference', $commerce_store);
  $message->save();
}

/**
 * Implements hook_commerce_product_insert().
 */
function message_activity_stream_commerce_product_insert(Product $commerce_product) {
  $message = Message::create(['template' => 'mas_create_product', 'uid' => $commerce_product->get('uid')]);
  $message->set('field_product_reference', $commerce_product);
  $message->set('field_published', $commerce_product->isPublished());
  $message->save();
}

/**
 * Implements hook_group_insert().
 */
function message_activity_stream_group_insert(Group $group) {
  $message = Message::create(['template' => 'mas_create_group', 'uid' => $group->get('uid')]);
  $message->set('field_group_reference', $group);
  $message->save();
}

/**
 * Implements hook_node_insert().
 */
function message_activity_stream_node_insert(Node $node) {
  $message = Message::create(['template' => 'mas_create_node', 'uid' => $node->get('uid')]);
  $message->set('field_node_reference', $node);
  $message->set('field_published', $node->isPublished());
  $message->save();
}

/**
 * Implements hook_comment_insert().
 */
function message_activity_stream_comment_insert(Comment $comment) {
  $message = Message::create(['template' => 'mas_create_comment', 'uid' => $comment->getOwnerId()]);
  $message->set('field_comment_reference', $comment);
  $message->set('field_published', $comment->isPublished());
  $message->save();
}

/**
 * Implements hook_user_insert().
 */
function message_activity_stream_user_insert(User $account) {
  Message::create(['template' => 'mas_user_register', 'uid' => $account->id()])->save();
}

/**
 * Implements hook_commerce_store_update().
 */
function message_activity_stream_commerce_store_update(Store $commerce_store) {
  if (empty($commerce_store->original)) {
    return;
  }

  message_activity_stream_update_message_status($commerce_store);
}

/**
 * Implements hook_commerce_product_update().
 */
function message_activity_stream_commerce_product_update(Product $commerce_product) {
  if (empty($commerce_product->original)) {
    return;
  }

  message_activity_stream_update_message_status($commerce_product);
}

/**
 * Implements hook_group_update().
 */
function message_activity_stream_group_update(Group $group) {
  if (empty($group->original)) {
    return;
  }

  message_activity_stream_update_message_status($group);
}

/**
 * Implements hook_node_update().
 */
function message_activity_stream_node_update(Node $node) {
  if (empty($node->original)) {
    return;
  }

  message_activity_stream_update_message_status($node);
}

/**
 * Implements hook_comment_update().
 */
function message_activity_stream_comment_update(Comment $comment) {
  if (empty($comment->original)) {
    return;
  }

  message_activity_stream_update_message_status($comment);
}

/**
 * Set message entity published field when it changes in the related entity.
 *
 * @param \Drupal\Core\Entity\ContentEntityBase $entity
 *   The entity object.
 */
function message_activity_stream_update_message_status(ContentEntityBase $entity) {
  if ($entity->isPublished() == $entity->original->isPublished()) {
    return;
  }

  $query = \Drupal::entityQuery('message');

  $field = 'field_' . $entity->getEntityType()->id() . '_reference';
  $query->condition($field . '.target_id', $entity->id());

  $results = $query->execute();

  if (empty($results)) {
    return;
  }

  $messages = Message::loadMultiple($results);

  foreach ($messages as $message) {
    $message->set('field_published', $entity->isPublished());
    $message->save();
  }
}

Here is the content of the message_activity_stream.tokens.inc file :

<?php

/**
 * @file
 * Place holder for the Message Activity Stream module.
 */

/**
 * Implements hook_token_info().
 *
 * We need this part until the token module will be exported to Drupal 8.
 */
function message_activity_stream_token_info() {
  $type = [
    'name' => t('Message Activity Stream'),
    'description' => t('Tokens for the Message Activity Stream module.'),
    'needs-data' => 'message',
  ];

  // User relate tokens.
  $message['user-name'] = [
    'name' => t("Author name"),
    'description' => t("The related author name."),
  ];

  $message['user-url'] = [
    'name' => t("Author url"),
    'description' => t("The related author URL."),
  ];

  // Comment relate tokens.
  $message['comment-url'] = [
    'name' => t("Comment url"),
    'description' => t("The comment url."),
  ];

  // Node related tokens.
  $message['node-render'] = [
    'name' => t("Rendered node"),
    'description' => t("The related node rendered to HTML."),
  ];

  $message['node-title'] = [
    'name' => t("Node title"),
    'description' => t("The related node title."),
  ];

  $message['node-url'] = [
    'name' => t("Node URL"),
    'description' => t("The related node URL."),
  ];

  return [
    'types' => ['message' => $type],
    'tokens' => [
      'message' => $message,
    ],
  ];
}

/**
 * Implements hook_tokens().
 */
function message_activity_stream_tokens($type, $tokens, array $data = [], array $options = []) {
  $token_service = \Drupal::token();

  $url_options = ['absolute' => TRUE];
  if (isset($options['langcode'])) {
    $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
    $langcode = $options['langcode'];
  }
  else {
    $langcode = NULL;
  }
  $sanitize = !empty($options['sanitize']);

  $replacements = [];

  if ($type == 'message' && !empty($data['message'])) {
    /** @var \Drupal\message\Entity\Message $message */
    $message = $data['message'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        // Simple key values on the comment.
        case 'user-name':
          $replacements[$original] = $message->getOwner()->label();
          break;

        case 'user-url':
          if ($message->getOwner()) {
            $replacements[$original] = $message->getOwner()->url();
          }
          break;

        case 'node-title':
          if ($message->bundle() == 'mas_create_comment') {
            $replacements[$original] = $message->field_comment_reference->entity->getCommentedEntity()->label();
          }
          else {
            $replacements[$original] = $message->field_node_reference->get(0)->entity->label();
          }
          break;

        case 'node-url':
          if ($message->bundle() == 'mas_create_comment') {
            $replacements[$original] = $message->field_comment_reference->entity->getCommentedEntity()->url();
          }
          else {
            $replacements[$original] = $message->field_node_reference->get(0)->entity->url();
          }
          break;

        case 'node-render':
          if ($message->bundle() == 'mas_create_comment') {
            $entity = $message->field_comment_reference->entity->getCommentedEntity();
          }
          else {
            $entity = $message->field_node_reference->get(0)->entity;
          }

          $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity->getEntityTypeId());
          $message_view = $view_builder->view($entity, 'teaser');
          $replacements[$original] = \Drupal::service('renderer')->renderRoot($message_view);
          break;

        case 'comment-url':
          $replacements[$original] = $message->field_comment_reference->entity->id();
          break;
      }
    }
  }

  return $replacements;
}

Drupal Commerce is installed on my site.

Here is my question :

Currently:

  • a message is created when a new node is created.

  • a message is created when a new comment is created.

  • a message is created when a new user registers.

What I want to do :

  • a message is created when a new store is created.

  • a message is created when a new product is created.

  • a message is created when a new group is created.

How to create a message when a new store is created ?

enter image description here

I created a message template "Message Activity Stream - Create store" with the machine name mas_create_store

enter image description here

I created a message template "Message Activity Stream - Create product" with the machine name mas_create_product

enter image description here

I created a message template "Message Activity Stream - Create group" with the machine name mas_create_group

enter image description here

  • Did you check the error log /admin/reports/dblog? You should be at least be getting a $group is not defined error. – No Sssweat Sep 8 '18 at 22:36
  • What exactly is your problem here? have you not been able to successfully create message on none of the hooks that you already have? or are you looking for a hook for when a new store is created? – No Sssweat Sep 8 '18 at 22:48
  • @NoSssweat I updated my question. I want at first. Create a message when a new store is created. – user89255 Sep 8 '18 at 23:02
  • I guess you could just have said, how to run some code when a new store is created? – No Sssweat Sep 9 '18 at 0:55
  • @NoSssweat I do not know how to code in php. I'm looking for a tutoreil to create a message after creating a store – user89255 Sep 9 '18 at 3:54
0

What you are already doing is that you implement hook_ENTITY_TYPE_insert() for ENTITY_TYPE = node. See the documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_insert/8.6.x

In your module that's the function message_activity_stream_node_insert(Node $node) { line in the message_activity_stream.module file.

From what I read you want to implement it (also) for entity types: commerce_store, commerce_product and group. Remember to rebuild the cache after implementing hooks.

Then the only remaining part will be to adjust following part accordingly, depends on the template's machine name to use and fields you want to set:

$message = Message::create(['template' => 'TEMPLATE_MACHINE_NAME', 'uid' => $entity->get('uid')]);

// @todo: Set fields you want, ie. field_store_reference
$message->save()
  • entity type machine name is commerce_store not store, so message_activity_stream_store_insert should become message_activity_stream_commerce_store_insert. commerce_product must be adjusted accordingly. group is correct as it is. – zaporylie Sep 9 '18 at 18:23
  • There's more issues to the current state of your code though, ie. $store doesn't have Store::isPublished() method. – zaporylie Sep 9 '18 at 18:34
  • Check dblog - you should see some errors whenever you add new store. – zaporylie Sep 9 '18 at 18:34
  • The Message::create(['id' => ...]) part refers to id of the newly created Message entity. You should never arbitrarily set it to any value - let Entity API set it for you. In the example from my answer uid of the message equals to uid of the store/product/group. uid is the id of the user creating new entity. use statements looks more or less ok. – zaporylie Sep 9 '18 at 19:04
  • @zapotylie I updated my question with the module file. I tested and the messages work when a store or a group is created. But when a product is created, the message is not created. I do not see any error in my module. There is this PHP error in the logs pastebin.com/K0Z7d6Cg – user89255 Sep 9 '18 at 20:21

Your Answer

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