
In Drupal 11, to get a field value from a custom block, we’ll typically be dealing with a block_content entity. Here’s how we can retrieve the field value programmatically.
1. Load the custom block by UUID or ID
use Drupal\block_content\Entity\BlockContent;
// Load by block ID (e.g., 1)
$block = BlockContent::load(1);
if ($block && $block->hasField('field_example_text')) {
$value = $block->get('field_example_text')->value;
\Drupal::messenger()->addMessage("Field value: " . $value);
}
2. Load by custom block UUID
use Drupal\block_content\Entity\BlockContent;
$uuid = 'your-block-uuid-here';
$blocks = \Drupal::entityTypeManager()
->getStorage('block_content')
->loadByProperties(['uuid' => $uuid]);
$block = reset($blocks);
if ($block && $block->hasField('field_example_text')) {
$value = $block->get('field_example_text')->value;
}
3. Using block plugin in preprocess
function MYTHEME_preprocess_block(array &$variables) {
$block = $variables['elements']['#block_content'] ?? NULL;
if ($block instanceof \Drupal\block_content\Entity\BlockContent && $block->hasField('field_example_text')) {
$variables['example_text'] = $block->get('field_example_text')->value;
}
}

0 Comments