You are here

abstract class DashboardBlockFormBase in Draggable dashboard 8.2

Class DashboardBlockFormBase

@package Drupal\draggable_dashboard\Form

Hierarchy

Expanded class hierarchy of DashboardBlockFormBase

File

src/Form/DashboardBlockFormBase.php, line 19

Namespace

Drupal\draggable_dashboard\Form
View source
abstract class DashboardBlockFormBase extends FormBase {

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

  /**
   * The context repository.
   *
   * @var \Drupal\Core\Plugin\Context\LazyContextRepository
   */
  protected $contextRepository;

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

  /**
   * Current Dashboard.
   *
   * @var \Drupal\draggable_dashboard\Entity\DashboardEntityInterface
   */
  protected $dashboard;

  /**
   * Block settings.
   *
   * @var array
   */
  protected $block;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->blockManager = $container
      ->get('plugin.manager.block');
    $instance->contextRepository = $container
      ->get('context.repository');
    $instance->pluginFormFactory = $container
      ->get('plugin_form.factory');
    return $instance;
  }

  /**
   * Initialize the form state and the entity before the first form build.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state object.
   * @param \Drupal\draggable_dashboard\Entity\DashboardEntityInterface $dashboard_entity
   *   Dashboard object.
   */
  protected function init(FormStateInterface $form_state, DashboardEntityInterface $dashboard_entity) {

    // Flag that this form has been initialized.
    $form_state
      ->set('form_initialized', TRUE);
    $this->dashboard = $dashboard_entity;
  }

  /**
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return array
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    /** @var \Drupal\Core\Block\BlockPluginInterface $block_instance */
    $block_instance = $this->blockManager
      ->createInstance($this->block['settings']['id'], $this->block['settings']);
    $form_state
      ->setTemporaryValue('gathered_contexts', $this->contextRepository
      ->getAvailableContexts());
    $form['settings'] = [
      '#tree' => TRUE,
    ];
    $subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
    $form['settings'] = $this
      ->getPluginForm($block_instance)
      ->buildConfigurationForm($form['settings'], $subform_state);
    if (empty($this->block['settings']['provider'])) {

      // If creating a new block, calculate a safe default machine name.
      $form['id'] = [
        '#type' => 'machine_name',
        '#maxlength' => 64,
        '#description' => $this
          ->t('A unique name for this block instance. Must be alpha-numeric and underscore separated.'),
        '#machine_name' => [
          'exists' => [
            $this,
            'blockIdExists',
          ],
          'replace_pattern' => '[^a-z0-9_]+',
          'source' => [
            'settings',
            'label',
          ],
        ],
        '#required' => TRUE,
        '#weight' => -10,
      ];
      if (empty($form['settings']['label']) || !empty($form['settings']['label']['#access']) && !$form['settings']['label']['#access'] && !empty($form['settings']['views_label'])) {
        $form['id']['#machine_name']['source'] = [
          'settings',
          'views_label',
        ];
      }
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
    ];
    $form['actions']['cancel'] = [
      '#type' => 'link',
      '#title' => $this
        ->t('Cancel'),
      '#attributes' => [
        'class' => [
          'button',
        ],
      ],
      '#url' => $this->dashboard
        ->toUrl('edit-form'),
    ];
    return $form;
  }

  /**
   * Retrieves the plugin form for a given block and operation.
   *
   * @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;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);

    // The Block Entity form puts all block plugin form elements in the
    // settings form element, so just pass that to the block for validation.

    /** @var BlockPluginInterface $block_instance */
    $block_instance = $this->blockManager
      ->createInstance($this->block['settings']['id']);
    $this
      ->getPluginForm($block_instance)
      ->validateConfigurationForm($form['settings'], SubformState::createForSubform($form['settings'], $form, $form_state));
  }

  /**
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Save block entity.
    $block = $this->blockManager
      ->createInstance($this->block['settings']['id']);
    $subform_state = SubformState::createForSubform($form['settings'], $form_state
      ->getCompleteForm(), $form_state);
    $block
      ->submitConfigurationForm($form['settings'], $subform_state);

    // If this block is context-aware, set the context mapping.
    if ($block instanceof ContextAwarePluginInterface && $block
      ->getContextDefinitions()) {
      $context_mapping = $subform_state
        ->getValue('context_mapping', []);
      $block
        ->setContextMapping($context_mapping);
    }
    $settings = $block
      ->getConfiguration();
    $form_state
      ->setValue('settings', $settings);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DashboardBlockFormBase::$block protected property Block settings.
DashboardBlockFormBase::$blockManager protected property The block manager.
DashboardBlockFormBase::$contextRepository protected property The context repository.
DashboardBlockFormBase::$dashboard protected property Current Dashboard.
DashboardBlockFormBase::$pluginFormFactory protected property The plugin form manager.
DashboardBlockFormBase::buildForm public function Overrides FormInterface::buildForm 2
DashboardBlockFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create
DashboardBlockFormBase::getPluginForm protected function Retrieves the plugin form for a given block and operation.
DashboardBlockFormBase::init protected function Initialize the form state and the entity before the first form build. 2
DashboardBlockFormBase::submitForm public function Overrides FormInterface::submitForm 2
DashboardBlockFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm
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.
FormInterface::getFormId public function Returns a unique string identifying the form. 236
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.