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

Adding API Support to Your Formatter

Last updated on
23 August 2021
To add support to your augmenter:
  1. Explicitly declare support by add the supportsDateAugmenter() method to your date formatter. In a typical use case it only needs to return TRUE, but if your formatter may need more than one set of configuration, you can return a keyed array instead. You can see an example of returning a keyed array in the Smart Date Recurring formatter.
  2. In your viewElements method, check for any enabled augmenters before processing the $items, with code like:
        // Look for the Date Augmenter plugin manager service.
        $augmenters = [];
        if (!empty(\Drupal::hasService('plugin.manager.dateaugmenter'))) {
          $dateAugmenterManager = \Drupal::service('plugin.manager.dateaugmenter');
          $config = $this->getThirdPartySettings('date_augmenter');
          $augmenters = $dateAugmenterManager->getActivePlugins($config);
          $entity = $items->getEntity();
        }
  3. Within your loop to process the $items and generate output, add code to apply any enabled augmenters, such as:
          if ($augmenters) {
            foreach ($augmenters as $augmenter_id => $augmenter) {
              // Use the enabled plugin to manipulate the output.
              $augmenter->augmentOutput(
                // The existing render array.
                $elements[$delta],
                // The start and end (optional), as DrupalDateTime objects.
                $item->start_date,
                $item->end_date,
                // An optional array of additional parameters.
                [
                  'entity' => $entity,
                  'settings' => $config['settings'][$augmenter_id],
                  'delta' => $delta,
                  'formatter' => $this,
                  'field_name' => $this->fieldDefinition->getName(),
                ]
              );
            }
          }
    

Note that in the above, the start and end may need to be changed to match the structure of data used by your formatter.

For the values being passed in:
  • $entity is the parent entity (node, taxonomy term, etc)
  • $delta is numerical key of the value
For the sake of the example above, $elements is the array being used to collect output render array, that will be returned by the viewElements function. You can see a simple implementation of the viewElements method that implements steps 2 and 3 in the Smart Date Duration formatter.

Help improve this page

Page status: No known problems

You can: