Fetching Drupal entities and fields in custom modules is a critical part of building complex Drupal applications that require custom functionality. By understanding how to access and manipulate entities and fields programmatically, developers can create powerful and flexible modules that can handle a wide range of data-driven tasks. 

In this article, we will share tips and easy methods on fetching reference entity fields using entity API that will help you simplify your custom module development process.

Fetch Drupal Reference Entities in Custom Modules

Getting Back to Basics

What are Entities?

Entities are the most core part of Drupal and it is important to understand what they are and how they work. They are objects that represent anything from users and nodes to taxonomy terms. Each entity has their own properties and can be customized or extended to fit the needs of a website.

What are Fields?

Fields make it easy to manage complex content structures. They are used to collect and display a variety of data like text, images, date and more which can be associated with an entity. For example, a content node can have multiple fields like a title, summary, body, image etc.

What are Nodes?

A node is a basic unit of content in Drupal. It can be a blog post, a product, a news article or an event. Each node has its own properties and can be organized into different types (or content types). A node can be used to create, edit, delete or categorize content.

Drupal Entity Reference Fields

Entity reference fields provide relationships between entities in Drupal. It stores references to another entity (a node, user, taxonomy, etc.). An example of a relationship would be:

  • A taxonomy term associated with a content type or user account.
  • A parent content that references a child content element.

It is commonly used in views and adding view relationships makes it quite easy to use reference fields. But the problem arises when fetching values of the reference fields in your custom module and custom theme.

The common method used to get a referenced entity is very long, so I will take you through a shorter solution.

For example, let's say we have a node object with a reference taxonomy field named field_specbee_term.

How it is usually done:

Method 1:

// $id = Node ID
// $field = 'field_specbee_term'; // field name for term reference field
$node = Drupal\node\Entity\Node::load($id);


// To get first value from multivalue field used first() method.
$reference_item = $node->get($field)->first();


// \Drupal\Core\Entity\Plugin\DataType\EntityReference.
$entity_reference = $reference_item->get('entity');


// \Drupal\Core\Entity\Plugin\DataType\EntityAdapter.
$entity_adapter = $entity_reference->getTarget();


// \Drupal\Core\Entity\EntityInterface.
$referenced_entity = $entity_adapter->getValue();

Here, $referenced_entity is the referenced entity object.

Now alternatively, instead of using the above tedious method 1, here is an easier way of doing it.

Method 2:

$referenced_entity = $node->field_specbee_term->entity;

However, if you want to fetch all the values from the multivalue field, Method 2 will not work.

For loading the entire list of reference entities as objects will use the below method which is a type of array.

$referenced_entities = $node->get('field_specbee_term')->referencedEntities();

This method can be used for image reference as well. 

Let’s see an example of how we can get an image URL from a node with a specific image style.

// $fid = File ID
$file = Drupal\file\Entity\File::load($fid);

// Alternatively you can use direct node field.
$file = $node->field_image->entity;

$image_uri = $file->getFileUri();  // Get origin image URI.
$style = ImageStyle::load('thumbnail');  // Load image style "thumbnail".
$uri = $style->buildUri($image_uri); // Get URI.
$url = $style->buildUrl($image_uri); // Get URL.

Now let’s understand how to retrieve any field values and which method is preferred for different scenarios.

// $id = Node ID
$node = Node::load($id);
$node->get(FIELDNAME)->value; //  ALL VALUES - WON'T WORK IN REFERENCE FIELDS
$node->get(FIELDNAME)->getValue(); //  ALL VALUES
$node->get(FIELDNAME)->getString(); //  ALL VALUES

1. value :

This will return the actual value of the field but it will not work for any referenced field. 

2. getValue() :

When you need to get values of a field, whether it is a single-value or multi-value field, you can use this method. It will return an array of field values. 

3. getString() :

This method will return the value of a single-value field, and if it is a multi-valued field it will return comma-separated values.

Note: Sometimes when using getString(), if there is no value present, it will throw an error. This can be tackled by using the hasvalue() function before using the getString() function.

Final Thoughts

Fetching Drupal reference entities is an essential skill for Drupal developers. With the Entity API, you can easily load and manipulate entities and their fields, making your custom module development process more efficient and streamlined. However, if you need expert assistance with Drupal development, our team of experienced developers is here to help. Contact us today to learn more about our Drupal development services and how we can help you build powerful Drupal websites and applications that meet your unique needs.

Contact us

LET'S DISCUSS YOUR IDEAS. 
WE'D LOVE TO HEAR FROM YOU.

CONTACT US