Upon node save, I want to take the value of a text field that uses a custom input filter and save the HTML-ified final version (what the input filter renders) in a second field.

I have two text fields:

  • Field text_main (which is never actually displayed, avoiding the performance penalty of rendering the field)
  • Field text_main_display (which is displayed publicly)

The field text_main uses a custom input filter that is very slow to run. So, I want to get the rendered output of the field after running the input filter and save it to the field text_main_display.

 * Implements hook_ENTITY_TYPE_presave()
function MYMODULE_node_presave(NodeInterface $entity) {
  switch ($entity->getType()) {
    case 'custom_page':
      $processedResult = $entity->get('field_text_main')->view('custom_display');
      // $processedResult is now a render array. How do I render this to HTML?
      $entity->set('field_text_main_display', $processedResult);

Reference: This post on how to render Drupal 8 fields

1 Answer 1


In hooks which are not executed in a render context use renderPlain(), see Cron error: LogicException : Render context is empty

$html = \Drupal::service('renderer')->renderPlain($processedResult);

Caveat: Text filters can bubble up metadata which you ignore by storing only the HTML. For a custom text filter this might be OK when you know it doesn't depend on cache metadata and attachments, but don't use this as a general approach. This can have security implications, like revealing data to non-authorized users.

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.