I need to programmatically change the content of a ui configured block. I've partially figured out how to do this, ie:

$ids = \Drupal::entityQuery('block_content')
  ->condition('type', 'custom_block_type')
  ->condition('info', 'Specific block title')

$my_block = BlockContent::load(array_values($ids)[0]);

This does change the content, but when I do this the block loses the Full HTML block format, and the new content in printed out verbatim as html encoded content (ie, the user literally sees '<h1>My altered value</h1>' on the screen). If I go through the ui and change the Text Format field manually to Full HTML, it renders correctly, but that doesn't really accomplish what I need to do.

How can I change the content programatically, without losing the html formatting?

  • try $my_block->body->format = 'full_html';
    – No Sssweat
    Oct 6 '16 at 0:30
  • Thanks for the insight! I didn't know I could access subfields that way. Oct 6 '16 at 14:12

The body field has at least two properties, value and format. To replace the complete field content, you have to use an array:

$my_block->set('body', [[
  'value' => '<h1>' . $my_processed_string . '</h1>',
  'format' => 'full_html',

Normally you don't need to do this. Set only the value property:

$my_block->body->value = '<h1>' . $my_processed_string . '</h1>';

So that you don't overwrite properties you don't want to change.


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.