5

Could anyone tell me how to programmatically access the field content of a custom block?

Thus far I've managed:

use Drupal\block\Entity\Block;
$block = Block::load($block_name);

if ($block) {
  $render = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
}

However this doesn't give me access to the fields and their data.

1

2 Answers 2

14

Your code loads a configured block, not the content of a custom block.

This will load the field data of block content:

$custom_block = \Drupal::entityTypeManager()->getStorage('block_content')->load('1');
$fieldcontent = $custom_block->field_myfield->value;
1
  • Worked for me!!!
    – Pupil
    Commented Jun 10, 2022 at 7:37
4

I just wanted to explain the example code given in the other answer with more detail, which will save time to many users.

$custom_block = \Drupal::entityTypeManager()->getStorage('block_content')->load('1');
$fieldcontent = $custom_block->field_myfield->value;
  1. block_content is a database table in your Drupal project
  2. 1 in load('1') is the ID value from that table
  3. field_myfield is a table field from the block_content__body table, for example block_content__body.body_value

If you want to change data from block_content__body.body_value field in your block, simply use this code.

$custom_block->body->value = 'TEST';

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.