You are here

DashboardBlockFormBase.php in Draggable dashboard 8.2

File

src/Form/DashboardBlockFormBase.php
View source
<?php

namespace Drupal\draggable_dashboard\Form;

use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\SubformState;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Plugin\PluginWithFormsInterface;
use Drupal\draggable_dashboard\Entity\DashboardEntityInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class DashboardBlockFormBase
 *
 * @package Drupal\draggable_dashboard\Form
 */
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);
  }

}

Classes

Namesort descending Description
DashboardBlockFormBase Class DashboardBlockFormBase