Israel Saramento 28 Feb, 2023
3 Good reasons to use pseudo fields

What are pseudo fields?

They are a type of field that we can attach to any type of content, they are display fields that don't have data, and we can create a custom data for it or pull from another source.

3 Good Reasons to use Pseudo Fields?

1 - Easily render a field from another content through a content reference field.
2 - No need to create more templates and "hardcoded data" into it. If it's appropriate in your case try using pseudo fields, instead of adding more and more data in a Twig template until it has so much stuff going on that no one knows what that template does and it becomes unsustainable.
3 - Can be moved in the “Manage display” as a normal field to easily choose where to display.

How to create a pseudo field?

Basically, we need 2 steps to create and use them.

First step: We need to create the “empty shell” that will be displayed in the “manage display” form. We can do that with a simple hook called hook_entity_extra_field_info:

For this we need to use the NodeType class in our file.
use Drupal\node\Entity\NodeType;

Now we have the new field that is created only for the blog content type decided by the bundle we chose. The name of the field is set in the “Label”, and the machine name in our example is “my_pseudo_field”.

pseudo-fileds-

Second step: To send data to this field we are going to using a hook_entity_type_view like this:

For the second step we need other 2 main classes in our file:
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
And the following class to load the entity we want to pull data from:
use Drupal\node\Entity\Node;

In the example above, we want to render a field from another content using a content reference field, for example, in our blog content type we have a reference to the article content type, and we want the content from the field description from the article content.

We pull “field description” values to be rendered from an article page. The way this field will be rendered is determined by the view mode we choose, in our case, it is rendering using the ‘Full’ view mode from the article content type.

In the $build['my_pseudo_field'], we can choose another approach to create this field, for example:

We can have custom field properties.

Or we can even render multiple fields inside the pseudo field.

And that's it! Now we have an article field inside our blog content type.

If this gets too complicated for you. Get in touch with us and we can assist you!
 


References:
- Hook entity extra field info 
- Hook entity type view
- Creating pseudo fields in Drupal 8
- Display and form pseudo fields in Drupal 8 and 9
- Drupal Pseudo Field