5

I created a custom block that contains a form field.

This is my blockSubmit() method.

public function blockSubmit($form, FormStateInterface $form_state) {
    // Save our custom settings when the form is submitted.
    $this->setConfigurationValue('my_text_field', $form_state->getValue('my_text_field'));
} 

Now I want to access the my_text_field value from outside the custom block class.

10

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]);
}
  • Getting Fatal error: Call to a member function get() on a non-object – Nikhil Banait Jan 2 '17 at 13:48
  • Wrong block_id? Try for example Block::load('bartik_branding'). Better we check if the block exists. I add this to the code. – 4k4 Jan 2 '17 at 14:00
  • Correct answer technically but IMHO, this smells like an anti-pattern.. if your configuration is global, then make it global configuration. Block configuration is per-block on purpose, so you could have multiple blocks with different settings or even have blocks in page_manager or so. – Berdir Jan 2 '17 at 18:36
  • Good point, I add this to the answer. – 4k4 Jan 2 '17 at 21:55
  • @4k4 block_id is correct, still facing the same issue. – Nikhil Banait Jan 3 '17 at 7:28
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.