How to enable the configuration of node properties in view modes in Drupal 8

02/02/2017
How to enable the configuration of node properties in view modes in Drupal 8

The purpose of this Drupal 8’s snippet is to enable the configuration of some of the node properties in view modes via interface (as creation date, title, etcetera) in the different view modes of the content types, as this task cannot be performed by default. This will allow us, among other things, to modify its position within the content to be displayed or to apply a different formatter.

In this case scenario, the snippet described below will enable the date of creation field (created) for its configuration in different view modes in Drupal 8.

/**
* Implements hook_entity_base_field_info_alter().
*/
function my_module_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
 // Make created field configurable on view modes.
 if ($entity_type->id() == 'node' && !empty($fields['created'])) {
   $fields['created']->setDisplayConfigurable('view', TRUE); // This is the important part here.
 }
}

Snnipet’s effect on Drupal 8

Let’s have a look at two screenshots of the default view mode of a content type with two fields: ‘image’ and ‘body’ so we get to see the usefulness of this snnipet in a clearer way: 

Before altering the field property

before-alter.png

After altering the field property

after-alter.png