You are here

class BlockStyleForm in Block Style Plugins 8.2

Provides a form for applying styles to a block.

@internal

Hierarchy

Expanded class hierarchy of BlockStyleForm

1 string reference to 'BlockStyleForm'
block_style_plugins.routing.yml in ./block_style_plugins.routing.yml
block_style_plugins.routing.yml

File

src/Form/BlockStyleForm.php, line 24

Namespace

Drupal\block_style_plugins\Form
View source
class BlockStyleForm extends FormBase {
  use AjaxFormHelperTrait;
  use IncludeExcludeStyleTrait;

  /**
   * The Block Styles Manager.
   *
   * @var \Drupal\block_style_plugins\Plugin\BlockStyleManager
   */
  protected $blockStyleManager;

  /**
   * The form builder.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * Instance of the Entity Repository service.
   *
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;

  /**
   * The section storage.
   *
   * @var \Drupal\layout_builder\SectionStorageInterface
   */
  protected $sectionStorage;

  /**
   * The layout section delta.
   *
   * @var int
   */
  protected $delta;

  /**
   * The uuid of the block component.
   *
   * @var string
   */
  protected $uuid;

  /**
   * Constructs a BlockStylesForm object.
   *
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
   *   The form builder.
   * @param \Drupal\block_style_plugins\Plugin\BlockStyleManager $blockStyleManager
   *   The Block Style Manager.
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entityRepository
   *   An Entity Repository instance.
   */
  public function __construct(FormBuilderInterface $form_builder, BlockStyleManager $blockStyleManager, EntityRepositoryInterface $entityRepository) {
    $this->formBuilder = $form_builder;
    $this->blockStyleManager = $blockStyleManager;
    $this->entityRepository = $entityRepository;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'block_style_plugins_layout_builder_styles';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, SectionStorageInterface $section_storage = NULL, $delta = NULL, $uuid = NULL) {
    $this->sectionStorage = $section_storage;
    $this->delta = $delta;
    $this->uuid = $uuid;
    $component = $section_storage
      ->getSection($delta)
      ->getComponent($uuid);
    $block_styles = $component
      ->getThirdPartySettings('block_style_plugins');

    // Get the component/block ID and then replace it with a block_content_type
    // if this is a reusable "block_content" block.
    $block_id = $component
      ->getPluginId();
    preg_match('/^block_content:(.+)/', $block_id, $matches);
    if ($matches) {
      $plugin = $this->entityRepository
        ->loadEntityByUuid('block_content', $matches[1]);
      if ($plugin) {
        $block_id = $plugin
          ->bundle();
      }
    }

    // Retrieve a list of style plugin definitions.
    $style_plugins = [];
    foreach ($this->blockStyleManager
      ->getBlockDefinitions() as $plugin_id => $definition) {

      // Check to see if this should only apply to includes or if it has been
      // excluded.
      if ($this
        ->allowStyles($block_id, $definition)) {
        $style_plugins[$plugin_id] = $definition['label'];
      }
    }

    // Create a list of applied styles with operation links.
    $items = [];
    foreach ($block_styles as $style_id => $configuration) {
      $options = [
        'attributes' => [
          'class' => [
            'use-ajax',
          ],
          'data-dialog-type' => 'dialog',
          'data-dialog-renderer' => 'off_canvas',
          'data-outside-in-edit' => TRUE,
        ],
      ];

      // Create links to edit and delete.
      $links = [
        'edit' => [
          '#title' => $this
            ->t('Edit'),
          '#type' => 'link',
          '#url' => Url::fromRoute('block_style_plugins.layout_builder.add_styles', $this
            ->getParameters($style_id), $options),
        ],
        'delete' => [
          '#title' => $this
            ->t('Delete'),
          '#type' => 'link',
          '#url' => Url::fromRoute('block_style_plugins.layout_builder.delete_styles', $this
            ->getParameters($style_id), $options),
        ],
        '#attributes' => [
          'class' => 'operations',
        ],
      ];

      // If there is no plugin for the set block style then we should only allow
      // deleting. This could be due to a plugin being removed.
      if (!isset($style_plugins[$style_id])) {
        unset($links['edit']);
      }
      $plugin_label = !empty($style_plugins[$style_id]) ? $style_plugins[$style_id] : $this
        ->t('Missing Style Plugin');
      $items[] = [
        [
          '#markup' => $plugin_label,
        ],
        $links,
      ];
    }
    if ($items) {
      $form['applied_styles_title'] = [
        '#markup' => '<h3>' . $this
          ->t('Applied Styles') . '</h3>',
      ];
      $form['applied_styles'] = [
        '#prefix' => '<div id="applied-styles">',
        '#suffix' => '</div>',
        '#theme' => 'item_list',
        '#items' => $items,
        '#empty' => $this
          ->t('No styles have been set.'),
        '#attached' => [
          'library' => [
            'block_style_plugins/off_canvas',
          ],
        ],
      ];
    }

    // Dropdown for adding styles.
    $form['block_styles'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Add a style'),
      '#options' => $style_plugins,
      '#empty_value' => '',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Add Styles'),
    ];
    if ($this
      ->isAjax()) {
      $form['actions']['submit']['#ajax']['callback'] = '::ajaxSubmit';
      $form['actions']['submit']['#ajax']['event'] = 'click';
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  protected function successfulAjaxSubmit(array $form, FormStateInterface $form_state) {
    $style_id = $form_state
      ->getValue('block_styles');
    $parameters = $this
      ->getParameters($style_id);
    $new_form = $this->formBuilder
      ->getForm('\\Drupal\\block_style_plugins\\Form\\ConfigureStyles', $this->sectionStorage, $parameters['delta'], $parameters['uuid'], $parameters['plugin_id']);
    $url = new Url('block_style_plugins.layout_builder.add_styles', $parameters, [
      'query' => [
        FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
        '_wrapper_format' => 'drupal_ajax',
      ],
    ]);
    $new_form['actions']['submit']['#attached']['drupalSettings']['ajax'][$new_form['actions']['submit']['#id']]['url'] = $url
      ->toString();
    $response = new AjaxResponse();
    $response
      ->addCommand(new OpenOffCanvasDialogCommand($this
      ->t('Configure Styles'), $new_form));
    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $parameters = $this
      ->getParameters($form_state
      ->getValue('block_styles'));
    $url = new Url('block_style_plugins.layout_builder.add_styles', $parameters);
    $form_state
      ->setRedirectUrl($url);
  }

  /**
   * Gets the parameters needed for the various Url() and form invocations.
   *
   * @param string $style_id
   *   The id of the style plugin.
   *
   * @return array
   *   List of Url parameters.
   */
  protected function getParameters($style_id) {
    return [
      'section_storage_type' => $this->sectionStorage
        ->getStorageType(),
      'section_storage' => $this->sectionStorage
        ->getStorageId(),
      'delta' => $this->delta,
      'uuid' => $this->uuid,
      'plugin_id' => $style_id,
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AjaxFormHelperTrait::ajaxSubmit public function Submit form dialog #ajax callback.
AjaxHelperTrait::getRequestWrapperFormat protected function Gets the wrapper format of the current request.
AjaxHelperTrait::isAjax protected function Determines if the current request is via AJAX.
BlockStyleForm::$blockStyleManager protected property The Block Styles Manager.
BlockStyleForm::$delta protected property The layout section delta.
BlockStyleForm::$entityRepository protected property Instance of the Entity Repository service.
BlockStyleForm::$formBuilder protected property The form builder.
BlockStyleForm::$sectionStorage protected property The section storage.
BlockStyleForm::$uuid protected property The uuid of the block component.
BlockStyleForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
BlockStyleForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
BlockStyleForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
BlockStyleForm::getParameters protected function Gets the parameters needed for the various Url() and form invocations.
BlockStyleForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
BlockStyleForm::successfulAjaxSubmit protected function Allows the form to respond to a successful AJAX submission. Overrides AjaxFormHelperTrait::successfulAjaxSubmit
BlockStyleForm::__construct public function Constructs a BlockStylesForm object.
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
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.