11

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.

3 Answers 3

19

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]);
}
6
  • Getting Fatal error: Call to a member function get() on a non-object Commented Jan 2, 2017 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.
    – 4uk4
    Commented Jan 2, 2017 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
    Commented Jan 2, 2017 at 18:36
  • Good point, I add this to the answer.
    – 4uk4
    Commented Jan 2, 2017 at 21:55
  • @4k4 block_id is correct, still facing the same issue. Commented Jan 3, 2017 at 7:28
4

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

I understand that the code above sounds like it should work, Block::load($bid) and $bid is from the annotation of the Block class. But the start of my code is this:

/**
 * Provides a 'SearchFiltersBlock' block.
 *
 * @Block(
 *  id = "search_filters_block",
 *  admin_label = @Translation("Filters"),
 * )
 */
class SearchFiltersBlock extends BlockBase {

yet, ::load('search_filters_block') returns NULL.

I tried this: Block::loadMultiple() to see what blocks existed and i see one with the id "filters" and it has plugin value "search_filters_block".

No idea.

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.