0

I'm finding I can't alter block content with hook_preprocess_block() in Drupal 8. Should I expect to be able to alter content, such as a block body, using hook_preprocess_block()?

For example, this has no effect on my block output:

function mysite_preprocess_block(&$variables) {
  $variables['elements']['content']['body'][0]['#text'] = 'alter all block bodies everywhere';
}
6
  • first check blocks are of which type,view block or custom block ,if its view block then above preprocess function will not work
    – Vikram8888
    Feb 18, 2020 at 8:19
  • You need to look at which variables the template uses to determine which ones you need to alter. In the default template it comes from "content", not elements. Feb 18, 2020 at 13:19
  • 1
    @AlfredArmstrong -- Thanks. Yes, it's as simple as dropping that 'elements' key. This works: $variables['content']['body'][0]['#text']. Somehow I couldn't find the right combination the other day.
    – arnoldbird
    Feb 19, 2020 at 13:38
  • @Vikram8888 -- Thanks. That is a very good thing to keep in mind as well.
    – arnoldbird
    Feb 19, 2020 at 13:39
  • May be worth noting that setting a value in hook_preprocess_block() for $variables['content']['body'][0]['#text'] only works -- at least in my case -- if there is a value saved in the body field. One of the reasons I struggled with this initially is that I had nothing saved in the body field in the database, but was still trying to set a value for the field in hook_preprocess_block(). Solved by saving some dummy characters to the body field.
    – arnoldbird
    Feb 20, 2020 at 14:42

1 Answer 1

1

There were two issues, in my case. For one thing, I was using the wrong key. I needed to use...

$variables['content']['body'][0]['#text'] 

...instead of...

$variables['elements']['content']['body'][0]['#text']

The other issue was that I had nothing saved in the body field, and in some cases setting a value for the body field in hook_preprocess_block() has no effect on output unless there is a value saved in the body field. You must at least save some garbage characters to the field or else setting a value in hook_preprocess_block() will have no effect on the output.

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.