Drupal - How do I get a block configuration value in a module?

You can load the block configuration entity, and get the settings.

$block = \Drupal\block\Entity\Block::load($block_id);
if ($block) {
  $settings = $block->get('settings');
  $my_text_field = $settings['my_text_field'];
}

$block_id is the machine name you see in the block layout when you save the block.

Edit: Store module configuration

If you want to store configuration for modules don't use a block form, but use a configuration form. Reference https://www.drupal.org/docs/8/api/configuration-api/working-with-configuration-forms (see comment from @Berdir)

Dump all blocks and their settings

$blocks = \Drupal\block\Entity\Block::loadMultiple();
foreach ($blocks as $key => $block) {
  $settings = $block->get('settings');
  var_dump([$key => $settings]);
}

Replace BLOCK_ID with your block's ID and dig the variables in it using get function

$config = \Drupal::config('block.block.BLOCK_ID');
$config->get('settings.my_text_field');

Tags:

8

Blocks