1

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')
  ->execute();

$my_block = BlockContent::load(array_values($ids)[0]);
$my_block->set('body','<h1>'.$my_processed_string.'</h1>');
$my_block->save();

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?

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

1 Answer 1

3

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.

0

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.