Creating pseudo-fields with the Extra Field module

3 minutes

Pseudo-Fields (Extra Fields) are display fields that you can create through code and they are manageable from the entity presentation management page.

Why use the Extra Field module?

Currently, to create a pseudo-field, we need to use 2 hooks:

  • hook_entity_extra_field_info: 
    To define the names of your fields and to which entities they apply.
  • hook_ENTITY_TYPE_view: 
    To display the fields that you defined with the previous hook.

The process is quite simple, just like with many hooks, but just one of the reasons why Drupal has been migrating this type of hook to Events or Plugins is because when you need to create many fields, everything becomes messy in your .module file, making your code less readable.

This is where the Extra Field module comes in, defining a type of Plugin that allows you to create pseudo-fields in a more organized way, and if you also install the Extra Field Plus module, you can define options for your fields, I'll show you an example.

What are we going to do?

To show you how we can use this module, I will create a Label/Title field for the node entity type, which is quite familiar to you, since the core of Drupal does not come with this field in the content presentation, and although it appears when using modules like Layout Builder or Display Suite, we will create it ourselves to learn a bit.

Here's the step-by-step process.

  1. Install the Extra Field module
  2. Vent to /admin/structure/types/manage/article/display/teaser and check if there is no field called Label for the summary presentation of articles.
  3. Create a module that will contain our code, we will call it my_fields, so we will create an empty folder with that name inside modules/custom.
  4. Add the file my_fields.info.yml that will look like the one I show you below

    
    name: 'My Fields'
    type: module
    description: 'Custom Display Fields'
    core: 8.x
    core_version_requirement: ^8 || ^9
    package: 'Custom'
    dependencies:
      - extra_field:extra_field
            
  5. Now we will create the file that will have the code for our field, which you should be able to see is much more readable and maintainable like this, this file should be located in src/Plugin/ExtraField/Display/Label.php and contains the following code:

    
        t('Label');
      }
    
      /**
       * @inheritdoc
       */
      public function getLabelDisplay() {
        return 'hidden';
      }
    
      /**
       * @inheritdoc
       */
      public function viewElements(ContentEntityInterface $entity) {
        $label = $entity->label();
    
        $element = array(
          '#type' => 'html_tag',
          '#tag' => 'h2',
          '#value' => $label,
        );
    
        return $element;
      }
    
    }
            
  6. The structure of our module should look like this:

    ExtraField module structure
  7. Clean the site's cache
  8. If now we go to /admin/structure/types/manage/article/display/teaser, you should see a new field available called Label

    Label Drupal Extra Field
  9. If you add this field to the presentation of your content, it will appear as the title in an h2 tag, you can also control this field's position from your site's administration

Analyze the code in the Label.php file


/**
 * Label Extra field with formatted output.
 *
 * @ExtraFieldDisplay(
 *   id = "entity_title", <- Field ID
 *   label = @Translation("Label"), <- Name shown in the Drupal UI
 *   bundles = { <- Types of entities the field will be available for.
 *     "node.*",
 *   },
 *   visible = false <- Default visibility
 * )
 */

public function getLabel() {
  return $this->t('Label');
}

...

public function getLabelDisplay() {
  return 'hidden';
}

public function viewElements(ContentEntityInterface $entity) {
  $label = $entity->label();

  $element = array(
    '#type' => 'html_tag',
    '#tag' => 'h2',
    '#value' => $label,
  );

  return $element;
}
        

This is the annotation of our field where we define its ID, name shown in the Drupal UI, types of entities the field will be available for, and default visibility. I prefer to keep the default visibility as false so that it can be set to true or false in the Drupal UI depending on the specific use case.

Conclusion

The Extra Field module allows us to structure our code better for our custom fields and you can see that this is much more maintainable than trying to put a view or any other HTML directly in the twig files or with functions like preprocess.

In a future article, I'll show you how to complement this field using the Extra Field Plus module.

Jidrone Drupal Developer
J. Ivan Duarte
Drupal Senior Developer

Share