1

is it possible to get and render the bid from a plugin block class build method ?

class HalPublicationBlock extends BlockBase implements BlockPluginInterface
{

  /**
   * {@inheritdoc}
   */
  public function build()
  {
        //do contain id but not bid 
        $config = $this->getConfiguration();
        //$bid=$this->get->?

EDIT : i'd like to pass the bid (or values that will be used by drupal as block css indentifier) to JS object and or twig templates , along with the same bloc instance configuration values

2

2 Answers 2

2

You receive the block id via a form value in the blockSubmit function, so if you save it as configuration, you can use it in the build() function. Seems a bit weird to save the block id as another config value, but otherwise you can't access it. Also note that it is possible to use a block plugin without an actual block entity, see https://drupal.stackexchange.com/a/181458/11500

/**
 * {@inheritdoc}
 */
public function blockSubmit($form, FormStateInterface $form_state) {
  $block_id = $form['id']['#default_value'];
  $this->configuration['block_class'] = $block_id;
}

You should probably add it to the BlockBase::defaultConfiguration() function as well. Because this changes the configuration, you will have to save the blocks manually once (to activate the change).

0

A reliable way to get the entity object (block in this case) attached to a plugin form is from the form_state object.

$formObject = $form_state->getFormObject()

This will return an instance of a FormInterface. From there you can get the entity object:

/** @var \Drupal\block\BlockInterface $block */
$block = $formObject->getEntity();

So if you have a Block Plugin with a block instance tied to it you can use the approach above to get the instance of the $block entity.

The good thing about this is you can use it in any of the functions that utilize the FormStateInterface object (functions like blockForm,blockSubmit, etc..)

So, to put it all together:

public function defaultConfiguration() {
     return ['block_id' => NULL] + parent::defaultConfiguration();
}

public function blockForm($form, FormStateInterface $form_state) {

    $block = $form_state->getFormObject()->getEntity();
    if (empty($config['block_id'])) {
        $this->setConfigurationValue('machine_name', $block->id());
    }
}

public function build(){
  $config = $this->getConfiguration();
  $bid = $config['block_id'];

  // Put code here to build your render array with the necessary information. 
}

Please use the necessary precautions to account for null values. Block plugins don't necessarily have a block instance attached to them.

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.