You are here

public function BlockFieldItem::getBlock in Block field 8

Get block instance.

Return value

null|\Drupal\Core\Block\BlockPluginInterface Return the block instance or NULL if the block does not exist.

Overrides BlockFieldItemInterface::getBlock

File

src/Plugin/Field/FieldType/BlockFieldItem.php, line 166

Class

BlockFieldItem
Plugin implementation of the 'block_field' field type.

Namespace

Drupal\block_field\Plugin\Field\FieldType

Code

public function getBlock() {
  if (empty($this->plugin_id)) {
    return NULL;
  }

  /** @var \Drupal\Core\Block\BlockManagerInterface $block_manager */
  $block_manager = \Drupal::service('plugin.manager.block');

  /** @var \Drupal\Core\Block\BlockPluginInterface $block_instance */
  $block_instance = $block_manager
    ->createInstance($this->plugin_id, $this->settings);
  $plugin_definition = $block_instance
    ->getPluginDefinition();

  // Don't return broken block plugin instances.
  if ($plugin_definition['id'] == 'broken') {
    return NULL;
  }

  // Don't return broken block content instances.
  if ($plugin_definition['id'] == 'block_content') {
    $uuid = $block_instance
      ->getDerivativeId();
    if (!\Drupal::service('entity.repository')
      ->loadEntityByUuid('block_content', $uuid)) {
      return NULL;
    }
  }
  return $block_instance;
}