You are here

public function LayoutBuilderAddBlockController::addBlock in Panopoly Magic 8.2

Adds the new block to layout builder and opens the configuration form.

Parameters

\Drupal\layout_builder\SectionStorageInterface $section_storage: The section storage.

int $delta: The delta of the section to add the block to.

string $region: The region for the section.

string $plugin_id: The plugin ID of the layout to add.

Return value

\Symfony\Component\HttpFoundation\Response|array The controller response.

File

src/Controller/LayoutBuilderAddBlockController.php, line 105

Class

LayoutBuilderAddBlockController
Controller for adding blocks in layout builder.

Namespace

Drupal\panopoly_magic\Controller

Code

public function addBlock(SectionStorageInterface $section_storage, $delta, $region, $plugin_id) {

  // Create a new component and add it to the section storage.
  $plugin_configuration = [
    'id' => $plugin_id,
  ];

  /** @var \Drupal\Core\Block\BlockPluginInterface $plugin */
  $plugin = $this->blockPluginManager
    ->createInstance($plugin_id, [
    'id' => $plugin_id,
  ]);
  $contexts = $this
    ->getAvailableContexts($section_storage);

  // Map contexts for plugins that need them.
  if ($contexts && $plugin instanceof ContextAwarePluginInterface) {
    $context_mapping = [];
    foreach ($plugin
      ->getContextDefinitions() as $context_slot => $definition) {

      // If the context is required, we have to give it something.
      if ($definition
        ->isRequired()) {
        $valid_contexts = $this->contextHandler
          ->getMatchingContexts($contexts, $definition);

        // Get the first context id, and assign that to the slot. The user can
        // change it later.
        reset($valid_contexts);
        $context_id = key($valid_contexts);
        $context_mapping[$context_slot] = $context_id;
      }
    }
    $plugin
      ->setContextMapping($context_mapping);
    $plugin_configuration = $plugin
      ->getConfiguration();
  }
  $component = new SectionComponent($this->uuid
    ->generate(), $region, $plugin_configuration);
  $section_storage
    ->getSection($delta)
    ->appendComponent($component);

  // Rebuild the layout.
  $response = $this
    ->rebuildLayout($section_storage);

  // Build the panopoly magic update block form and open it in the off canvas.
  $form = $this->formBuilder
    ->getForm(LayoutBuilderUpdateBlockForm::class, $section_storage, $delta, $region, $component
    ->getUuid());
  $response
    ->addCommand(new HtmlCommand('#drupal-off-canvas', $form));
  return $response;
}