Skip to main content

Devbit

Render field with given formatter type programmatically

You want to print out a field in a given formatter type.
$field_render_array = $entity->{$field_name}->view([
  'type' => 'default_formatter', // Replace with desired formatter type.
  'label' => 'hidden', // If you want to hide the label of the field (optional).
  'settings' => [
    'trim_length' => 100, // Example for textfields: Trim the text to 100 characters.
  ],
]);

Issue:

You want to print out a field in a given formatter type.

Solution:

An easy way would be to use the configuration on the view display of your entity and select the wanted field formatter there. But in some cases (e.g. you don't want to render the field on the node where it is defined) this does not work.

This snippet shows you how to do it programmatically (for example in a preprocess hook). 

As fields themselves do not have a `view()` method, we need to manipulate the render array of a field item list you get when loading an entity.

Michael Ebert

Michael Ebert

Backend Developer / DevOps

Ihre Drupal-Website zukunftssicher machen

Wir prüfen Ihr System und zeigen, was Sie für AI, Wartung und Upgrades brauchen.