You are here

class BlockFormAlter in Block Style Plugins 8.2

Base class for Block style plugins.

Hierarchy

Expanded class hierarchy of BlockFormAlter

2 files declare their use of BlockFormAlter
BlockFormAlterTest.php in tests/src/Unit/BlockFormAlterTest.php
block_style_plugins.module in ./block_style_plugins.module
Contains block_style_plugins.module.

File

src/BlockFormAlter.php, line 18

Namespace

Drupal\block_style_plugins
View source
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());
        }
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BlockFormAlter::$blockStyleManager protected property Instance of the Block Style Manager service.
BlockFormAlter::alterForm public function Alter a form and set block configuration.
BlockFormAlter::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create
BlockFormAlter::layoutBuilderEmbedAlter public function Alter the component settings form in Layout Builder settings tray.
BlockFormAlter::submitForm public function Submit the form and save configuration.
BlockFormAlter::validateForm public function Validate the form.
BlockFormAlter::__construct public function Construct method for BlockFormAlter.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormEntityHelperTrait::$entityRepository protected property Instance of the Entity Repository service.
FormEntityHelperTrait::getBlockConfigEntityFromFormState protected function Get the Block config entity from the form state.
FormEntityHelperTrait::getBlockContent protected function Get the Block Content entity.
FormEntityHelperTrait::getBlockContentBundle public function Get the block content bundle type.
FormEntityHelperTrait::getEntityFromFormState protected function Get the config entity of the entity being styled from the form state.
FormEntityHelperTrait::getEntityRepository protected function Gets the Entity Repository service.
FormEntityHelperTrait::getSectionFromFormState protected function Get the Section config entity from the form state.
IncludeExcludeStyleTrait::allowStyles public function Determine whether a style should be allowed.
IncludeExcludeStyleTrait::exclude public function Exclude styles from appearing on blocks.
IncludeExcludeStyleTrait::includeOnly public function Only show styles on specific blocks.
IncludeExcludeStyleTrait::matchPattern protected function Match a plugin ID against a list of possible plugin IDs.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.