Skip to main content
Start of main content.

Overriding base field labels and descriptions of Drupal Entities without custom code

by lee.rowlands /

Share this post on social media

Have you ever had a project where you've used a core or contributed module but been asked to make slight changes to base fields? Find out how to use a little-known feature of core to make these changes with only configuration.

You may not be aware, but Drupal core has a mechanism for changing base field definitions without code, but other than for nodes, there's no real UI to make use of this API.

If you've ever changed the label of the Title field for a node-type and then exported your configuration, you've probably seen a core.base_field_override file pop up in the exported files.

These config entities can be used to modify base fields on a per-bundle basis.

Drupal core uses them to change the label of the Title field for a given node-type or the default state of the 'Promoted to front page' field.

But the same mechanism can be used for any entity-type.

So how do you go about using this feature.

Well, you've got two options - one is to use the Base Field Override UI module. This lets you change the title and description via a UI. 

But there are more properties a field override can contain, such as default values, required state and even field settings. For those cases, you need to revert to editing YML. But first you need a mechanism to generate the YML.

At present, the simplest way to do that is using Drush to evaluate the following.

drush php-eval "\Drupal::service('entity_field.manager')->getBaseFieldDefinitions({entity_type})[{field_name}]->getConfig({bundle})->save();" 

Just substitute the entity type ID, field name and bundle.

E.g. to export the YML of the 'info' (label) field on the block content entity from 'Block description' for a block-type called 'gallery' you would run

drush php-eval "\Drupal::service('entity_field.manager')->getBaseFieldDefinitions('block_content')['info']->getConfig('gallery')->save();" 

Once that is done, you can run drush config:export -y to export your configuration and you should see a new core.base_field_override.block_content.gallery.info.yml in your config export folder.

You can now edit this file and make the changes you need, and then re-import it using drush config:import -y.

If the entity-type you need to override doesn't support bundles, just use the entity type ID in place of the bundle, e.g. for the User entity, use user for both the entity type ID and bundle.

The advantage of this approach is you don't need to keep an extra module around (Base Field Override UI) just for one-off changes.

Thanks to Adam Bramley for reminding me of this feature. I have a slack comment from him pinned in my saved items and refer to it all the time!