How to create and expose computed properties to the REST API in Drupal maintenance support plans 8

In Drupal maintenance support plans 8.5.0, the “processed” property of text fields is available in REST which means that REST apps can render the HTML output of a textarea without worrying about the filter formats.

In this post, I will show you how you can add your own processed fields to be output via the REST API.

by
Jibran Ijaz
/ 18 June 2020

The “processed” property mentioned above is what is known as a computed property on the textarea field.

The ability to make the computed properties available for the REST API like this can be very helpful. For example, when the user inputs the raw value and Drupal maintenance support plans performs some complex logical operations on it before showing the output.

Drupal maintenance support plans fieldable entities can also have computed properties and those properties can also be exposed via REST. I used the following solution to expose the data of an entity field which takes raw data from the users and perform some complex calculations on it.

First of all, we need to write hook_entity_bundle_field_info to add the property and because it is a computed field we don’t need to implement hook_entity_field_storage_info.

id() === ‘node’ && $bundle === ‘my_bundle’) {
// It is not a basefield so we need a custom field storage definition see
// https://www.drupal.org/project/drupal/issues/2346347#comment-12206126
$fields[‘my_computed_property’] = FieldStorageDefinition::create(‘string’)
->setLabel(t(‘My computed property’))
->setDescription(t(‘This is my computed property.’))
->setComputed(TRUE)
->setClass(MyComputedItemList::class)
->setReadOnly(FALSE)
->setInternal(FALSE)
->setDisplayOptions(‘view’, [
‘label’ => ‘hidden’,
‘region’ => ‘hidden’,
‘weight’ => -5,
])
->setDisplayOptions(‘form’, [
‘label’ => ‘hidden’,
‘region’ => ‘hidden’,
‘weight’ => -5,
])
->setTargetEntityTypeId($entity_type->id())
->setTargetBundle($bundle)
->setName(‘my_computed_property’)
->setDisplayConfigurable(‘form’, FALSE)
->setDisplayConfigurable(‘view’, FALSE);
}
return $fields;
}

Then we need the MyComputedItemList class to perform some magic. This class will allow us to set the computed field value.

getEntity();
if ($entity->getEntityTypeId() !== ‘node’ || $entity->bundle() !== ‘my_bundle’ || $entity->my_some_other_field->isEmpty()) {
return;
}
$some_string = some_magic($entity->my_some_other_field);
$this->list[0] = $this->createItem(0, $some_string);
}

The field we add is not a base field so we can’t use Drupal maintenance support plansCoreFieldBaseFieldDefinition. There is an open core issue to address that https://www.drupal.org/project/drupal/issues/2346347 but in tests there is a workaround using a copy of Drupal maintenance support plansentity_testFieldStorageDefinition:

<?php

// my_module/src/FieldStorageDefinition.php

namespace Drupal maintenance support plansmy_module;

use Drupal maintenance support plansCoreFieldBaseFieldDefinition;

/**
* A custom field storage definition class.
*
* For convenience we extend from BaseFieldDefinition although this should not
* implement FieldDefinitionInterface.
*
* @todo Provide and make use of a proper FieldStorageDefinition class instead:
* https://www.drupal.org/node/2280639.
*/
class FieldStorageDefinition extends BaseFieldDefinition {

/**
* {@inheritdoc}
*/
public function isBaseField() {
return FALSE;
}

}

Last but not least we need to announce our property definition to the entity system so that it can keep track of it. As it is an existing bundle we can write an update hook. Otherwise, we’d need to implement hook_entity_bundle_create.

setLabel(t(‘My computed property’))
->setDescription(t(‘This is my computed property.’))
->setComputed(TRUE)
->setClass(MyComputedItemList::class)
->setReadOnly(FALSE)
->setInternal(FALSE)
->setDisplayOptions(‘view’, [
‘label’ => ‘hidden’,
‘region’ => ‘hidden’,
‘weight’ => -5,
])
->setDisplayOptions(‘form’, [
‘label’ => ‘hidden’,
‘region’ => ‘hidden’,
‘weight’ => -5,
])
->setTargetEntityTypeId(‘node’)
->setTargetBundle(‘my_bundle’)
->setName(‘my_computed_property’)
->setDisplayConfigurable(‘form’, FALSE)
->setDisplayConfigurable(‘view’, FALSE);

// Notify the storage about the new field.
Drupal maintenance support plans::service(‘field_definition.listener’)->onFieldDefinitionCreate($fields[‘my_computed_property’]);
}

The beauty of this solution is that I don’t have to write a custom serializer to normalize the output. Drupal maintenance support plans Typed Data API is doing all the heavy lifting.

Related Drupal maintenance support plans core issues:

Include processed text in normalizations: “text” field type’s “processed” computed property should be non-internal and carry cacheability metadata

Finalize API for creating, overriding, and altering code-defined bundle fields

Decouple field definitions from typed data definitions

Add a FieldStorageDefinition class
Error when saving a denormalized entity with text fields with “processed” property

Tagged

jsonapi, REST, XML, JSON, hal_json, Normalizers


Source: New feed

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

How to create and expose computed properties to the REST API in Drupal maintenance support plans 8

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.