You are here

BlockFormAlter.php in Block Style Plugins 8.2

File

src/BlockFormAlter.php
View source
<?php

namespace Drupal\block_style_plugins;

use Drupal\block_style_plugins\Plugin\BlockStyleManager;
use Drupal\Core\Form\SubformState;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\layout_builder\SectionComponent;

/**
 * Base class for Block style plugins.
 */
class BlockFormAlter implements ContainerInjectionInterface {
  use StringTranslationTrait;
  use IncludeExcludeStyleTrait;
  use FormEntityHelperTrait;
  use DependencySerializationTrait;

  /**
   * Instance of the Block Style Manager service.
   *
   * @var \Drupal\block_style_plugins\Plugin\BlockStyleManager
   */
  protected $blockStyleManager;

  /**
   * Construct method for BlockFormAlter.
   *
   * @param \Drupal\block_style_plugins\Plugin\BlockStyleManager $blockStyleManager
   *   A Block Style Manager instance.
   */
  public function __construct(BlockStyleManager $blockStyleManager) {
    $this->blockStyleManager = $blockStyleManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.block_style.processor'));
  }

  /**
   * Alter a form and set block configuration.
   *
   * This code will be run as part of a form alter so that the current blocks
   * configuration will be available to the form.
   *
   * @param array $form
   *   The form definition array for the block configuration form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param bool $layout_builder
   *   TRUE if the current form is the Layout Builder component settings.
   */
  public function alterForm(array &$form, FormStateInterface $form_state, $layout_builder = FALSE) {

    // Retrieve a list of style plugin definitions.
    $style_plugins = $this->blockStyleManager
      ->getBlockDefinitions();
    foreach ($style_plugins as $plugin_id => $plugin_definition) {
      if ($layout_builder && empty($plugin_definition['layout_builder_embed_form'])) {
        continue;
      }

      /** @var \Drupal\block_style_plugins\Plugin\BlockStyleInterface $style_plugin */
      $style_plugin = $this->blockStyleManager
        ->createInstance($plugin_id);

      // Get the current block config entity.
      $entity = $this
        ->getBlockConfigEntityFromFormState($form_state);

      // Set properties and configuration.
      $block_plugin = $entity
        ->getPlugin();
      $block_content_bundle_id = $this
        ->getBlockContentBundle($form_state);

      // Find the plugin ID or block content bundle id.
      $block_plugin_id = $block_plugin
        ->getPluginId();
      if ($block_content_bundle_id) {
        $block_plugin_id = $block_content_bundle_id;
      }

      // Check to see if this should only apply to includes or if it has been
      // excluded.
      if ($this
        ->allowStyles($block_plugin_id, $plugin_definition)) {

        // Create a fieldset to contain style fields.
        if (!isset($form['block_styles'])) {
          $form['block_styles'] = [
            '#type' => 'fieldset',
            '#title' => $this
              ->t('Block Styles'),
            '#collapsible' => FALSE,
            '#collapsed' => FALSE,
            '#weight' => 0,
          ];
        }
        $styles = $entity
          ->getThirdPartySetting('block_style_plugins', $plugin_id, []);
        $style_plugin
          ->setConfiguration($styles);

        // Create containers to place each plugin style settings into the styles
        // fieldset.
        $form['third_party_settings']['block_style_plugins'][$plugin_id] = [
          '#type' => 'container',
          '#group' => 'block_styles',
        ];

        // Allow plugins to add field elements to this form.
        if ($style_plugin instanceof PluginFormInterface) {
          $subform_state = SubformState::createForSubform($form['third_party_settings']['block_style_plugins'][$plugin_id], $form, $form_state);
          $form['third_party_settings']['block_style_plugins'][$plugin_id] += $style_plugin
            ->buildConfigurationForm($form['third_party_settings']['block_style_plugins'][$plugin_id], $subform_state);
        }
      }
    }
    $form['#validate'][] = [
      $this,
      'validateForm',
    ];
    $form['#submit'] = $form['#submit'] ?? [];
    array_unshift($form['#submit'], [
      $this,
      'submitForm',
    ]);
  }

  /**
   * Alter the component settings form in Layout Builder settings tray.
   *
   * @param array $form
   *   The form definition array for the block configuration form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param string $form_id
   *   Id of the current form.
   */
  public function layoutBuilderEmbedAlter(array &$form, FormStateInterface $form_state, $form_id) {
    if ($form_id == 'layout_builder_update_block' || $form_id == 'layout_builder_add_block') {
      $this
        ->alterForm($form, $form_state, TRUE);
    }
  }

  /**
   * Validate the form.
   *
   * @param array $form
   *   The form definition array for the block configuration form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function validateForm(array $form, FormStateInterface $form_state) {

    // Retrieve a list of possible style plugin definitions.
    $available_plugins = $this->blockStyleManager
      ->getBlockDefinitions();
    $style_settings = $form_state
      ->getValue([
      'third_party_settings',
      'block_style_plugins',
    ]);
    foreach ($style_settings as $plugin_id => $settings) {

      // Only instantiate plugins that are available.
      if (array_key_exists($plugin_id, $available_plugins)) {

        /** @var \Drupal\block_style_plugins\Plugin\BlockStyleInterface $style_plugin */
        $style_plugin = $this->blockStyleManager
          ->createInstance($plugin_id);
        if ($style_plugin instanceof PluginFormInterface) {
          $subform_state = SubformState::createForSubform($form['third_party_settings']['block_style_plugins'][$plugin_id], $form, $form_state);
          $style_plugin
            ->validateConfigurationForm($form['third_party_settings']['block_style_plugins'][$plugin_id], $subform_state);
        }
      }
    }
  }

  /**
   * Submit the form and save configuration.
   *
   * @param array $form
   *   The form definition array for the block configuration form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function submitForm(array $form, FormStateInterface $form_state) {

    // Retrieve a list of possible style plugin definitions.
    $available_plugins = $this->blockStyleManager
      ->getBlockDefinitions();
    $style_settings = $form_state
      ->getValue([
      'third_party_settings',
      'block_style_plugins',
    ]);
    $component = $this
      ->getBlockConfigEntityFromFormState($form_state);
    foreach ($style_settings as $plugin_id => $styles) {

      // Only instantiate plugins that are available.
      if (array_key_exists($plugin_id, $available_plugins)) {

        /** @var \Drupal\block_style_plugins\Plugin\BlockStyleInterface $style_plugin */
        $style_plugin = $this->blockStyleManager
          ->createInstance($plugin_id);
        $style_plugin
          ->setConfiguration($styles);
        if ($style_plugin instanceof PluginFormInterface) {
          $subform_state = SubformState::createForSubform($form['third_party_settings']['block_style_plugins'][$plugin_id], $form, $form_state);
          $style_plugin
            ->submitConfigurationForm($form['third_party_settings']['block_style_plugins'][$plugin_id], $subform_state);
        }

        // Embedded form on Layout Builder settings tray needs styles saved to
        // the component.
        if ($component instanceof SectionComponent) {
          $component
            ->setThirdPartySetting('block_style_plugins', $plugin_id, $style_plugin
            ->getConfiguration());
        }
      }
    }
  }

}

Classes

Namesort descending Description
BlockFormAlter Base class for Block style plugins.