12.12.2025 | Michael Ebert

Render field with given formatter type programmatically

my_module.module
$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.