PHP Composer package to resolve Drupal Entities as simple Object/Array of fields

vishwac09

Vishwa Chikate

Posted on September 23, 2022

PHP Composer package to resolve Drupal Entities as simple Object/Array of fields

The article covers the implementation / working of the Entity Convert PHP library which i have created to reduce the need to write custom utility/helper functions or classes to get the value from fields associated with the Entities.

Entities constitute one of the major features of a Drupal framework. The default Entities which Drupal comes configured with are the Content-Types (Nodes), Taxonomies (Vocabulary), Files (Image, Text) and the User account. Almost every project will use some or all of the above mentioned entities at some phase during the project’s development lifecycle.

Idea -:

Multiple times we need to access the values of the Entity instances created in the application. For example consider some scenarios below.

  • Working on a custom implementation of a listing page which shows list of nodes/contents created by multiple users along with their additional details such as first/ last name, occupation, company etc

  • Feature where we need to post some data to an external site/application via HTTP REST invocation by picking some field values attached to an entity instance.

  • Exposing HTTP REST endpoints from the application which return’s data to the consumer when they are invoked.

With every case above we will need to load the corresponding entity using the default API provided by the *Drupal Core, *then access the field values and perform the associated action which can be anything ranging from constructing a view, populating values, designing a REST response, create a schema to insert into a SQL table or else to update some values in a random table.

Working -:

Let’s consider a Content type “Cars”, Taxonomy “Brands” created in the application, with “Cars” referring to the taxonomy term’s created under the “Brands” vocabulary.

Also assuming the following field types associated with the “Cars” entity.

  • Boolean

  • Integer, Decimal

  • List Integer / Decimal / Text

  • File / Images / Taxonomy / Content

  • Timestamp / Date

  • Link, Email

Drupal Way

How field values are accessed normally in the code.

$node = Node::load(1);
$field_boolean_value = $node->get('field_boolean_value')->value;

// Accessing the values of BaseFields is easy.
$nid = $node->id();
$title = $node->getTitle();
$type = $node->getType();
$isPromoted = $node->isPromoted();
Enter fullscreen mode Exit fullscreen mode

Accessing the value of fields associated with a Node entity.

Boolean field

$field_boolean_value = $node->get('field_bool_multi_value')->value;

var_dump($field_boolean_value);

string(1) "1"
Enter fullscreen mode Exit fullscreen mode

DateTime Field

$field_datetime_multi_value = $node->get('field_datetime_multi_value')->value;

var_dump($field_datetime_multi_value);

string(19) "2022-08-31T00:31:28"
Enter fullscreen mode Exit fullscreen mode

Date Field

$field_date_multi_value = $node->get('field_date_multi_value')->value;

var_dump($field_date_multi_value);

array(2) { [0]=> array(1) { ["value"]=> string(10) "2022-08-14" } [1]=> array(1) { ["value"]=> string(10) "2022-08-31" } }
Enter fullscreen mode Exit fullscreen mode

Email Field

$field_email_multi_value = $node->get('field_email_multi_value')->value;

var_dump($field_email_multi_value);

array(2) { [0]=> array(1) { ["value"]=> string(24) "[test@abc.com](mailto:test@abc.com)" } [1]=> array(1) { ["value"]=> string(25) "[test@def.com](mailto:test@def.com)" } }
Enter fullscreen mode Exit fullscreen mode

List Text Field

$field_listtext_multi_value = $node->get('field_listtext_multi_value')->getValue();

var_dump($field_listtext_multi_value);

array(2) { [0]=> array(1) { ["value"]=> string(5) "apple" } [1]=> array(1) { ["value"]=> string(4) "ball" } }
Enter fullscreen mode Exit fullscreen mode

File Field

$field_file_multi_value = $node->get('field_file_multi_value')->value;

var_dump($field_file_multi_value);

array(1) { [0]=> array(3) { ["target_id"]=> string(1) "3" ["display"]=> string(1) "1" ["description"]=> string(8) "CSV File" } }
Enter fullscreen mode Exit fullscreen mode

Accessing the field values associated with an entity using the default API is easy but repeating the same code/syntax again and again is irritating. Moreover we end up writing duplicate code for various entities in different custom modules.

A good solution to the above problem is to write a single helper/utility class or a set of them, in a custom module which will do the job of extracting the values from fields associated with the given entity instance.

Instead of creating a new module for it, i though to experiment with a simple stateless PHP composer library to achieve the same functionality, and which is also easy to port to any new Drupal 8/9 project.

Using the library

Include the namespace “DrupalUtils\EntityConvert\EntityConvert” in the file; in which you would like to use the “EntityConvert” libraries API.

Get response as array of field => values

Get response as an object

If the response is an object, all available fields/values can be accessed as a property.

API

The methods toArray / toObject(instance, strict_type) accepts 2 arguments.

- instance = Loaded instance object of the type Node/User/Taxonomy/File.

- strict_type = Boolean: Returned response has all data types preserved.
Enter fullscreen mode Exit fullscreen mode

When we get value from field attached to an Entity, Drupal will usually return all values as string. Sending second parameter as true, the library will typecast all possible values to it correct data type.

Entity Convert library method API

Installation

Add the package via composer

composer require drupal-utils/entity-convert:0.0.1-alpha || 0.0.2-alpha
Enter fullscreen mode Exit fullscreen mode

Final Notes

The library is still in its initial phases of development, hence current it is in its alpha release phase. There can be various use cases which i might have missed during the development.

If you wish to support the package or provide with any additional feedback within the package implementation or encounter any bug/s please don’t forget to raise an issue in Github.

Getting involved, Fork the project if you have any idea to contribute to or if you find some improvement area.

Github -: https://github.com/vishwac09/entity-convert

Packagist -: https://packagist.org/packages/drupal-utils/entity-convert

Thanks

💖 💪 🙅 🚩
vishwac09
Vishwa Chikate

Posted on September 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related