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

Developer documentation

Last updated on
24 January 2020

Module page: https://www.drupal.org/project/computed_field_plugin

Computed fields

You don't need this module to create computed fields, see the doc here : https://www.drupal.org/docs/8/api/entity-api/dynamicvirtual-field-values-using-computed-field-property-classes

What this minimalist module does is simply provide a way to create computed fields via the Plugin API and a new field type called computed_render_array.

Tips

Your computed fields will be available for any view mode available in the display of your entity type / bundle.

You can also create custom field formatters for your computed_render_array fields (see our default formatter for a working example).

Code example

Plugin file

Simple implementation example: return the creation date of the entity.

Notice that we use our custom ComputedSingleItemTrait and singleComputeValue(), but you can still use the core ComputedItemListTrait and computeValue() if it fits your needs better.

<?php

namespace Drupal\my_module\Plugin\ComputedField;

use Drupal\computed_field_plugin\Traits\ComputedSingleItemTrait;
use Drupal\Core\Field\FieldItemList;

/**
 * Class TestComputedField.
 *
 * @ComputedField(
 *   id = "test_computed_field",
 *   label = @Translation("Test computed field"),
 *   type = "computed_render_array",
 *   entity_types = {"node"},
 *   bundles = {"page"}
 * )
 */
class TestComputedField extends FieldItemList {

  use ComputedSingleItemTrait;

  /**
   * Handle single value.
   *
   * @return mixed
   *   Returns the computed value.
   */
  protected function singleComputeValue() {
    $creation_date = $this->getEntity()->get('created')->value;

    return [
      'value' => $creation_date,
    ];
  }

}
  • The entityTypes and bundles annotation properties expect an array; leave empty to allow all.
  • The label annotation property defines the field label, as for any normal field.
  • The expected return value is a render array, as you can guess from the name computed_render_array.

Twig

If you need to call directly your field in a twig template, simply use the plugin id like any field machine name. For example in the node.html.twig, we can use our field like this:

{{ content.test_computed_field }}

Aaaand that's pretty much it!

Help improve this page

Page status: No known problems

You can: