I created a custom block plugin that returns
if($ i >5) { $ this->configuration['label'] = 'i is greater than 5'; } return [ '#title' => $ this->configuration['label'], 'container' => [ '#type' => 'container', '#attributes' => [ 'class' => 'test-class', ], 'content' => [ '#markup' => 'test markup', ], ], ];
I want the displayed label or title (not sure the proper term) to be overwritten based on the value of another variable calculated inside the block plugin. However no matter what the title of the block plugin does not change. Even if I manually change it like so.
return [ '#title' => 'attempting to change title of block', 'container' => [ '#type' => 'container', '#attributes' => [ 'class' => 'test-class', ], 'content' => [ '#markup' => 'test markup', ], ], ];
Even when doing this the block is using the title in the original block configuration instead of the specified one. How would I programmatically change the title of a block from within its build function?
UPDATE: I just realized it might not be working because of something I’m doing in my .theme file.
function mytheme_preprocess_block(&$ vars){ $ token = Drupal::token(); $ vars['label'] = html_entity_decode($ token->replace($ vars['elements']['#configuration']['label'],['node' => $ node])); }
I’m storing the label in my own var that I’m using in my block.html.twig template, and maybe preprocess_block happens before the build function in my block plugin? Either way there’s not a postprocess block hook (that I know of) so I’m not sure of a simple solution.
If this is why it isn’t working I suppose then the build function happens after the preprocess_block hook. Just a guess
UPDATE 2: I tried correcting it
$ vars['elements']['#configuration']['label'] = html_entity_decode($ token->replace($ vars['elements']['#configuration']['label'],['node' => $ node]));
instead of
$ vars['label'] = html_entity_decode($ token->replace($ vars['elements']['#configuration']['label'],['node' => $ node]));
Which kind of worked but then the token replacement stopped working.