Drupal - How to get a field value of custom block?
Fields of custom blocks are in block content. So you have to load the block content first, before you can get the field value:
$block = \Drupal\block\Entity\Block::load($block_id);
$uuid = $block->getPlugin()->getDerivativeId();
$block_content = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', $uuid);
if ($block_content) {
$field_value = $block_content->field_block_alt_title->value;
}
I was trying to do the same today and this is the only one that worked for me on the latest Drupal version (8.6.12).
use \Drupal\block_content\BlockContentInterface;
function HOOK_preprocess_block(&$variables)
{
$content = $variables['elements']['content'];
if (isset($content['#block_content']) && $content['#block_content'] instanceof BlockContentInterface) {
$blockType = $content['#block_content']->bundle();
if ($blockType === 'CUSTOM_BLOCK_TYPE') {
$variables['FIELD_VALUE_ACCESSIBLE_VIA_TEMPLATE'] = $content['#block_content']->get('FIELD_NAME')->value;
}
}
}
Then in your template file.
{{ FIELD_VALUE_ACCESSIBLE_VIA_TEMPLATE }}
You can load the field like:
$alt_title = Drupal\block\Entity\Block::load($block_id)->get('field_block_alt_title')->value;
or
$alt_title = Drupal\block\Entity\Block::load($block_id)->field_block_alt_title->value;