Advertising sustains the DA. Ads are hidden for members. Join today

Creating a computed field

Last updated on
7 November 2023

This documentation needs work. See "Help improve this page" in the sidebar.

This documentation is for version 4.x of the Computed Field module.

To create a computed field, you need two things:

  1. A computed field plugin to generate the values of the field. This is created in PHP code. You can use an existing one if there is one that serves your purpose.
  2. A computed field config to store the settings. This is created in the admin UI, the same as normal fields.

Creating a plugin

A computed field plugin is a custom class. This needs to go in a custom module.

The simplest way to create the custom module and the plugin is using Module Builder:

  1. Install Module Builder
  2. Go to /admin/config/development/module_builder/, and follow the instructions to analyse your site's code
  3. At admin/config/development/module_builder/, create a new module
  4. Enter the basic details for your module and save the form
  5. Go to the 'Plugins' tab
  6. Click 'Add a plugins item'
  7. Select the 'Computed field' variant
  8. Enter the basic details for your plugin
  9. Save and generate the module
  10. Write all the module files

You will now need to examine the generated plugin file. Some methods may be removed depending on your use case.

The code that produces the value for the field should go in the computeValue() method. If your field is single-valued, you can use the SingleValueTrait to simplify the return value.

Once your plugin is ready, enable your module. If you've added it to an existing custom module, clear caches.

Creating a computed field

  1. In the 'Manage fields' page for an entity type bundle, select 'Add a computed field'.
  2. You should see your plugin in the options for the field.
  3. You can configure your field in the display settings, the same as a normal field.

Other methods

Computed field plugins can also automatically declare computed fields - this is referred to as 'automatically attaching'. Doing this means you don't have control in the admin UI, but it means your field is present as soon as a module is enabled. This can be useful for example if you want to include computed fields in a contrib module.

Another advantage is that declaring a computed field as a base field works around some limitations Drupal core has with base fields, including use in Views and presence in JSONAPI output.

Help improve this page

Page status: Needs work

You can: