Drupal base field -- what is it and when do you need to create one?

What is a Drupal base field?

Base fields are fields that are available to all nodes like title, uid or date created.  Base fields are not limited to nodes, but to any entity like user, paragraphs, menu, blocks, block_content, etc.

It is automatically available to all existing nodes and for the ones that will be created in the future.

What could be some use case for creating a base field?

If you want to add a boolean base field called "Exclude from search" or a text base field called "Search priority keyword" to all nodes are some of the possible use case for using a base field.

 

Let's do it:

1.  Create the field in node add/edit by using hook_entity_base_field_info().

Base field hook

base field for all nodes

2. Add storage for this node using hook_update_N().

By default, there is no storage yet for this new field.  Values are not saved yet, and we have to create a storage like so:

hook_update_N

After executing updb, a new column in node_field_data will be added.

new column

This new field can be accessed like the title field, $node->get('exclude_from_search').

 

For form and view display settings you can use EntityDisplayRepositoryInterface::getFormDisplay and EntityDisplayRepositoryInterface::getViewDisplay.