How to Create a Pseudofield In Drupal

Using just two functions

Sergio Guardiola Herrador
2 min readMay 2, 2024
Photo by Rubaitul Azad on Unsplash

Pseudofields are similar to normal fields, except they are used to render something simple, maybe just some text or HTML. Unlike normal fields, they don’t have field settings or form settings.

To create a pseudofield, we just need to use two functions: hook_entity_extra_field_info and hook_ENTITY_TYPE_view.

In this example, I’m creating a field called my_own_pseudo_field (replace it with your field ID) for all node types that will just render some simple markup: “This is my custom content”.

You need to place this code in the *.module file of your module and clear the Drupal cache. Then, go to the content types where you have added your field and in the manage display page, move the field where you want it to appear:

use Drupal\node\Entity\NodeType;

/**
* Implements hook_entity_extra_field_info().
*/
function my_module_entity_extra_field_info() {
$extra = [];

foreach (NodeType::loadMultiple() as $bundle) {
$extra['node'][$bundle->Id()]['display']['my_own_pseudo_field'] = [
'label' => t('My own field'),
'description' => t('This is my own pseudo-field'),
'weight' => 100,
'visible' => TRUE,
];
}

return $extra;
}
use \Drupal\Core\Entity\EntityInterface;
use \Drupal\Core\Entity\Display\EntityViewDisplayInterface;

/**
* Implements hook_ENTITY_TYPE_view().
*/
function my_module_node_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
if ($display->getComponent('my_own_pseudo_field')) {
$build['my_own_pseudo_field'] = [
'#type' => 'markup',
'#markup' => 'This is my custom content',
];
}
}

👉 Find out more about me here: https://sergioguardiola.net 🔥

--

--

Sergio Guardiola Herrador

I write articles in English and Spanish, mostly about programming, technology, travel, money, investing. You can find me here: https://sergioguardiola.net