On this page
Creating a computed field
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:
- 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.
- 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:
- Install Module Builder
- Go to /admin/config/development/module_builder/, and follow the instructions to analyse your site's code
- At admin/config/development/module_builder/, create a new module
- Enter the basic details for your module and save the form
- Go to the 'Plugins' tab
- Click 'Add a plugins item'
- Select the 'Computed field' variant
- Enter the basic details for your plugin
- Save and generate the module
- 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
- In the 'Manage fields' page for an entity type bundle, select 'Add a computed field'.
- You should see your plugin in the options for the field.
- 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
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion