1

I'm trying to use a REST resource that accepts a node title and returns a JSON interpretation of a single field. This requires raw HTML that I can then use in DOMDocument. To get the rendered value of a node programmatically with filters applied I tried:

$field_value = $node->get('body')->getValue();

However this doesn't apply any of the filters such as converting newlines/carriage returns into <br/> or striping out unwanted HTML tags. I don't intend to send this to a Twig template so I need the rendered value in a string rather than a render array.

How can I do that?

0

2 Answers 2

2

When you use Drupal in a site-building capacity, you use the Manage Display to configure field/layout configuration. What you're actually doing is choosing and configuring plugins to do the formatting for you, information that Drupal then uses to render an entity.

But when you're manually rendering entities or fields of entities, all this work you have to do yourself. When you do ->getValue() or ->value, what you're doing is extracting the raw value from the field, usually a programmatic representation of the value that's stored in the database. Entities also do not carry formatting on their own, that's information stored separate from the entity (e.g. display configuration) - a good example of separation of concerns, entity data vs entity display information.

You have choices though:

2

Thanks to everyone who helped out. In the end this is what I did to get the field to render with the filters applied.

/** @var \Drupal\node\NodeViewBuilder */
$view_builder = $this->entityTypeManager->getViewBuilder('node');

$field_render_array = $view_builder->viewField($node->get('body'), 'full');
// Deprecated switch to render service.
$html = render($field_render_array);
2
  • Alternatively you can do this
    – No Sssweat
    Jan 4, 2023 at 21:26
  • 1
    Just be aware that going this route, you're rendering the field as configured in the "full" display of node (the same display that dictates how a field appears when rendered as a node page). This means that if someone were to change how the body field renders on the Full display (e.g. from all of the text to just the summary), it might unintentionally change how it's rendered on your REST resource as well. If you want to stick with this approach, I suggest you create a dedicated view mode for your REST resource, and use it instead of "full".
    – Joseph
    Jan 8, 2023 at 6:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.