You are here

abstract class ConfigureBlockFormBase in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/layout_builder/src/Form/ConfigureBlockFormBase.php \Drupal\layout_builder\Form\ConfigureBlockFormBase
  2. 9 core/modules/layout_builder/src/Form/ConfigureBlockFormBase.php \Drupal\layout_builder\Form\ConfigureBlockFormBase

Provides a base form for configuring a block.

@internal Form classes are internal.

Hierarchy

Expanded class hierarchy of ConfigureBlockFormBase

File

core/modules/layout_builder/src/Form/ConfigureBlockFormBase.php, line 32

Namespace

Drupal\layout_builder\Form
View source
abstract class ConfigureBlockFormBase extends FormBase implements BaseFormIdInterface {
  use AjaxFormHelperTrait;
  use ContextAwarePluginAssignmentTrait;
  use LayoutBuilderContextTrait;
  use LayoutRebuildTrait;

  /**
   * The plugin being configured.
   *
   * @var \Drupal\Core\Block\BlockPluginInterface
   */
  protected $block;

  /**
   * The layout tempstore repository.
   *
   * @var \Drupal\layout_builder\LayoutTempstoreRepositoryInterface
   */
  protected $layoutTempstoreRepository;

  /**
   * The block manager.
   *
   * @var \Drupal\Core\Block\BlockManagerInterface
   */
  protected $blockManager;

  /**
   * The UUID generator.
   *
   * @var \Drupal\Component\Uuid\UuidInterface
   */
  protected $uuidGenerator;

  /**
   * The plugin form manager.
   *
   * @var \Drupal\Core\Plugin\PluginFormFactoryInterface
   */
  protected $pluginFormFactory;

  /**
   * The field delta.
   *
   * @var int
   */
  protected $delta;

  /**
   * The current region.
   *
   * @var string
   */
  protected $region;

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

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

  /**
   * Constructs a new block form.
   *
   * @param \Drupal\layout_builder\LayoutTempstoreRepositoryInterface $layout_tempstore_repository
   *   The layout tempstore repository.
   * @param \Drupal\Core\Plugin\Context\ContextRepositoryInterface $context_repository
   *   The context repository.
   * @param \Drupal\Core\Block\BlockManagerInterface $block_manager
   *   The block manager.
   * @param \Drupal\Component\Uuid\UuidInterface $uuid
   *   The UUID generator.
   * @param \Drupal\Core\Plugin\PluginFormFactoryInterface $plugin_form_manager
   *   The plugin form manager.
   */
  public function __construct(LayoutTempstoreRepositoryInterface $layout_tempstore_repository, ContextRepositoryInterface $context_repository, BlockManagerInterface $block_manager, UuidInterface $uuid, PluginFormFactoryInterface $plugin_form_manager) {
    $this->layoutTempstoreRepository = $layout_tempstore_repository;
    $this->contextRepository = $context_repository;
    $this->blockManager = $block_manager;
    $this->uuidGenerator = $uuid;
    $this->pluginFormFactory = $plugin_form_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('layout_builder.tempstore_repository'), $container
      ->get('context.repository'), $container
      ->get('plugin.manager.block'), $container
      ->get('uuid'), $container
      ->get('plugin_form.factory'));
  }

  /**
   * {@inheritdoc}
   */
  public function getBaseFormId() {
    return 'layout_builder_configure_block';
  }

  /**
   * Builds the form for the block.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param \Drupal\layout_builder\SectionStorageInterface $section_storage
   *   The section storage being configured.
   * @param int $delta
   *   The delta of the section.
   * @param \Drupal\layout_builder\SectionComponent $component
   *   The section component containing the block.
   *
   * @return array
   *   The form array.
   */
  public function doBuildForm(array $form, FormStateInterface $form_state, SectionStorageInterface $section_storage = NULL, $delta = NULL, SectionComponent $component = NULL) {
    $this->sectionStorage = $section_storage;
    $this->delta = $delta;
    $this->uuid = $component
      ->getUuid();
    $this->block = $component
      ->getPlugin();
    $form_state
      ->setTemporaryValue('gathered_contexts', $this
      ->getPopulatedContexts($section_storage));

    // @todo Remove once https://www.drupal.org/node/2268787 is resolved.
    $form_state
      ->set('block_theme', $this
      ->config('system.theme')
      ->get('default'));
    $form['#tree'] = TRUE;
    $form['settings'] = [];
    $subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
    $form['settings'] = $this
      ->getPluginForm($this->block)
      ->buildConfigurationForm($form['settings'], $subform_state);
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->submitLabel(),
      '#button_type' => 'primary',
    ];
    if ($this
      ->isAjax()) {
      $form['actions']['submit']['#ajax']['callback'] = '::ajaxSubmit';

      // @todo static::ajaxSubmit() requires data-drupal-selector to be the same
      //   between the various Ajax requests. A bug in
      //   \Drupal\Core\Form\FormBuilder prevents that from happening unless
      //   $form['#id'] is also the same. Normally, #id is set to a unique HTML
      //   ID via Html::getUniqueId(), but here we bypass that in order to work
      //   around the data-drupal-selector bug. This is okay so long as we
      //   assume that this form only ever occurs once on a page. Remove this
      //   workaround in https://www.drupal.org/node/2897377.
      $form['#id'] = Html::getId($form_state
        ->getBuildInfo()['form_id']);
    }

    // Mark this as an administrative page for JavaScript ("Back to site" link).
    $form['#attached']['drupalSettings']['path']['currentPathIsAdmin'] = TRUE;
    return $form;
  }

  /**
   * Returns the label for the submit button.
   *
   * @return string
   *   Submit label.
   */
  protected abstract function submitLabel();

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
    $this
      ->getPluginForm($this->block)
      ->validateConfigurationForm($form['settings'], $subform_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Call the plugin submit handler.
    $subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
    $this
      ->getPluginForm($this->block)
      ->submitConfigurationForm($form, $subform_state);

    // If this block is context-aware, set the context mapping.
    if ($this->block instanceof ContextAwarePluginInterface) {
      $this->block
        ->setContextMapping($subform_state
        ->getValue('context_mapping', []));
    }
    $configuration = $this->block
      ->getConfiguration();
    $section = $this->sectionStorage
      ->getSection($this->delta);
    $section
      ->getComponent($this->uuid)
      ->setConfiguration($configuration);
    $this->layoutTempstoreRepository
      ->set($this->sectionStorage);
    $form_state
      ->setRedirectUrl($this->sectionStorage
      ->getLayoutBuilderUrl());
  }

  /**
   * {@inheritdoc}
   */
  protected function successfulAjaxSubmit(array $form, FormStateInterface $form_state) {
    return $this
      ->rebuildAndClose($this->sectionStorage);
  }

  /**
   * Retrieves the plugin form for a given block.
   *
   * @param \Drupal\Core\Block\BlockPluginInterface $block
   *   The block plugin.
   *
   * @return \Drupal\Core\Plugin\PluginFormInterface
   *   The plugin form for the block.
   */
  protected function getPluginForm(BlockPluginInterface $block) {
    if ($block instanceof PluginWithFormsInterface) {
      return $this->pluginFormFactory
        ->createInstance($block, 'configure');
    }
    return $block;
  }

  /**
   * Retrieves the section storage object.
   *
   * @return \Drupal\layout_builder\SectionStorageInterface
   *   The section storage for the current form.
   */
  public function getSectionStorage() {
    return $this->sectionStorage;
  }

  /**
   * Retrieves the current layout section being edited by the form.
   *
   * @return \Drupal\layout_builder\Section
   *   The current layout section.
   */
  public function getCurrentSection() {
    return $this->sectionStorage
      ->getSection($this->delta);
  }

  /**
   * Retrieves the current component being edited by the form.
   *
   * @return \Drupal\layout_builder\SectionComponent
   *   The current section component.
   */
  public function getCurrentComponent() {
    return $this
      ->getCurrentSection()
      ->getComponent($this->uuid);
  }

}

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.
ConfigureBlockFormBase::$block protected property The plugin being configured.
ConfigureBlockFormBase::$blockManager protected property The block manager.
ConfigureBlockFormBase::$delta protected property The field delta.
ConfigureBlockFormBase::$layoutTempstoreRepository protected property The layout tempstore repository.
ConfigureBlockFormBase::$pluginFormFactory protected property The plugin form manager.
ConfigureBlockFormBase::$region protected property The current region.
ConfigureBlockFormBase::$sectionStorage protected property The section storage.
ConfigureBlockFormBase::$uuid protected property The UUID of the component.
ConfigureBlockFormBase::$uuidGenerator protected property The UUID generator.
ConfigureBlockFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ConfigureBlockFormBase::doBuildForm public function Builds the form for the block.
ConfigureBlockFormBase::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId
ConfigureBlockFormBase::getCurrentComponent public function Retrieves the current component being edited by the form.
ConfigureBlockFormBase::getCurrentSection public function Retrieves the current layout section being edited by the form.
ConfigureBlockFormBase::getPluginForm protected function Retrieves the plugin form for a given block.
ConfigureBlockFormBase::getSectionStorage public function Retrieves the section storage object.
ConfigureBlockFormBase::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ConfigureBlockFormBase::submitLabel abstract protected function Returns the label for the submit button. 2
ConfigureBlockFormBase::successfulAjaxSubmit protected function Allows the form to respond to a successful AJAX submission. Overrides AjaxFormHelperTrait::successfulAjaxSubmit
ConfigureBlockFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm
ConfigureBlockFormBase::__construct public function Constructs a new block form.
ContextAwarePluginAssignmentTrait::addContextAssignmentElement protected function Builds a form element for assigning a context to a given slot.
ContextAwarePluginAssignmentTrait::contextHandler protected function Wraps the context handler.
ContextAwarePluginAssignmentTrait::t abstract protected function Ensures the t() method is available.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack.
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. 3
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.
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.
FormInterface::buildForm public function Form constructor. 170
FormInterface::getFormId public function Returns a unique string identifying the form. 239
LayoutBuilderContextTrait::$contextRepository protected property The context repository.
LayoutBuilderContextTrait::contextRepository protected function Gets the context repository service.
LayoutBuilderContextTrait::getPopulatedContexts protected function Returns all populated contexts, both global and section-storage-specific.
LayoutRebuildTrait::rebuildAndClose protected function Rebuilds the layout.
LayoutRebuildTrait::rebuildLayout protected function Rebuilds the layout.
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. 18
MessengerTrait::messenger public function Gets the messenger. 18
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. 3
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. 1