Drawing from our example on implementing hook_entity_view(), there's a neat little technique we can use to empower our site builders further with respect to that disclaimer message. This is by turning it into a pseudo field. By doing this, site builders will be able to choose the bundles it should show on, as well as the position relative to the other fields, all through the UI in the Manage Display section:
So, there are two things we need to do for this. First, we need to implement hook_entity_extra_field_info() and define our pseudo field:
/** * Implements hook_entity_extra_field_info(). */ function module_name_entity_extra_field_info() { $extra = []; foreach (NodeType::loadMultiple() as $bundle) { $extra['node'][$bundle->id()]['display']['disclaimer'] = [ 'label' => t('Disclaimer'), 'description' => t('A general disclaimer'), 'weight' => 100, 'visible' => TRUE, ]; } return $extra; }
As you can see, we loop through all the available node types and for the node entity display list, we add our disclaimer definition with some defaults to use. The weight and visibility will, of course, be overridable by the user, per node bundle.
Next, we need to go back to our hook_entity_view() implementation and make some changes. Because we know we want this applied to Node entities only, we can implement the more specific hook instead:
/** * Implements hook_ENTITY_TYPE_view(). */ function module_name_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) { if ($display->getComponent('disclaimer')) { $build['disclaimer'] = [ '#markup' => t('The content provided is for general information purposes only.'), ]; } }
In this case we don't need to check for view modes or entity types, but rather use the entity view display configuration object to check for the existence of this extra disclaimer field (technically called a component). If found, we simply add our markup to the $build array. Drupal will take care of things like weight and visibility to match whatever the user has set through the UI, and that's it. Clearing the cache, we should still see our disclaimer message, but we can now control it a bit from the UI.