I am attempting to override a node field value in Drupal 8 (on output) using template_preprocess_node. Specifically, I am attempting to override the text of a long text field. I am currently using this:

function THEMENAME_preprocess_node(&$variables) {
  $variables['content']['field_content'] = array(
    '#type' => 'markup',
    '#markup' => '<p>Testing 123</p>',

And that works, but it totally overrides the field, removing the classes I added to the field wrapper, etc.

Does anyone know how to just set the value only, without replacing the entire field theming, etc? I do not want to manually add the field wrapper classes to #markup.

  • get rid off markup and try '#type' => 'processed_text', '#text' => 'Testing 123', – No Sssweat Aug 3 '17 at 4:54
  • Hey thanks for that. Unfortunately that does the same thing (removing field wrappers). Is there a list of these options somewhere? I've been looking for that. – Micah Aug 3 '17 at 5:02
  • You flushed the cache, right? – No Sssweat Aug 3 '17 at 5:04
  • Yup--that's how I got the change to show up. – Micah Aug 3 '17 at 5:06
  • How did you add the class to the field wrapper? – No Sssweat Aug 3 '17 at 5:07

After doing a quick test, turns out that hook_preprocess_node will always override hook_preprocess_field's attributes.

Therefore, instead of adding the class in hook_preprocess_field, and if you don't want to use '#markup', you could add it in hook_preprocess_node like this:

function THEMENAME_preprocess_node(&$variables) {
    $variables['content']['field_test'] = array(
    '#type' => 'processed_text', 
    '#text' => 'Test 123',
    '#prefix' => '<div class="your-class">',
    '#suffix' => '</div>',
  • 1
    Yup, thanks for looking into that--adding prefix/suffix works fine. I ended up switching back to using markup because I didn't want the extra <p> tags from processed_text. Thanks again! – Micah Aug 3 '17 at 7:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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