You are here

function sharemessage_entity_view in Share Message 8

Implements hook_entity_view().

File

./sharemessage.module, line 286
New Sharing Module.

Code

function sharemessage_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  foreach ($display
    ->getComponents() as $name => $component) {
    if (strstr($name, 'sharemessage__') !== FALSE) {
      list(, $id) = explode('__', $name, 2);

      // Ensure that there is a Share Message with the detected ID to load and
      // that the context's bundle is one of the extra field's list.
      // This is needed because the Share Message settings can be changed and
      // that might not be immediately reflected in the view display.

      /** @var \Drupal\sharemessage\ShareMessageInterface $sharemessage */
      if ($sharemessage = ShareMessage::load($id)) {
        if ($sharemessage
          ->getExtraFieldEntityType() == $entity
          ->getEntityTypeId() && (!$sharemessage
          ->getExtraFieldBundles() || in_array($entity
          ->bundle(), $sharemessage
          ->getExtraFieldBundles()))) {

          // Default to the entity type ID for the token type.
          $entity_type_id = $entity
            ->getEntityTypeId();

          // Some entity types have token types that do not match their entity
          // type ID. If the token module is available, use it to get the
          // correct token type. This is necessary for taxonomy_term/term, for
          // example.
          if (\Drupal::moduleHandler()
            ->moduleExists('token')) {
            $entity_type_id = \Drupal::service('token.entity_mapper')
              ->getTokenTypeForEntityType($entity
              ->getEntityTypeId());
          }

          // Add the runtime context to get the correct token context.
          $sharemessage
            ->setRuntimeContext([
            $entity_type_id => $entity,
          ]);
          $build[$name] = \Drupal::entityTypeManager()
            ->getViewBuilder('sharemessage')
            ->view($sharemessage);
        }
      }
    }
  }
}