You are here

class PanelsIPELayoutForm in Panels 8.4

Same name and namespace in other branches
  1. 8.3 panels_ipe/src/Form/PanelsIPELayoutForm.php \Drupal\panels_ipe\Form\PanelsIPELayoutForm

Provides a form for configuring a layout for use with the IPE.

Hierarchy

Expanded class hierarchy of PanelsIPELayoutForm

File

panels_ipe/src/Form/PanelsIPELayoutForm.php, line 20

Namespace

Drupal\panels_ipe\Form
View source
class PanelsIPELayoutForm extends FormBase {

  /**
   * @var \Drupal\Core\Render\RendererInterface $renderer
   */
  protected $renderer;

  /**
   * @var \Drupal\Core\TempStore\SharedTempStoreFactory
   */
  protected $tempStore;

  /**
   * @var \Drupal\Core\Layout\LayoutPluginManagerInterface
   */
  protected $layoutManager;

  /**
   * The Panels storage manager.
   *
   * @var \Drupal\panels\Plugin\DisplayVariant\PanelsDisplayVariant
   */
  protected $panelsDisplay;

  /**
   * The current layout.
   *
   * @var \Drupal\Core\Layout\LayoutInterface
   */
  protected $layout;

  /**
   * Constructs a new PanelsIPEBlockPluginForm.
   *
   * @param \Drupal\Core\Layout\LayoutPluginManagerInterface $layout_manager
   * @param \Drupal\Core\Render\RendererInterface $renderer
   * @param \Drupal\Core\TempStore\SharedTempStoreFactory $temp_store_factory
   */
  public function __construct(LayoutPluginManagerInterface $layout_manager, RendererInterface $renderer, SharedTempStoreFactory $temp_store_factory) {
    $this->layoutManager = $layout_manager;
    $this->renderer = $renderer;
    $this->tempStore = $temp_store_factory
      ->get('panels_ipe');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.core.layout'), $container
      ->get('renderer'), $container
      ->get('tempstore.shared'));
  }

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

  /**
   * Builds a form that configure an existing or new layout for the IPE.
   *
   * @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 string $layout_id
   *   The requested Layout ID.
   * @param \Drupal\panels\Plugin\DisplayVariant\PanelsDisplayVariant $panels_display
   *   The current PageVariant ID.
   *
   * @return array
   *   The form structure.
   */
  public function buildForm(array $form, FormStateInterface $form_state, $layout_id = NULL, PanelsDisplayVariant $panels_display = NULL) {

    // We require these default arguments.
    if (!$layout_id || !$panels_display) {
      return FALSE;
    }

    // Save the panels display for later.
    $this->panelsDisplay = $panels_display;

    // Check if this is the current layout, and if not create an instance.
    $layout = $this->panelsDisplay
      ->getLayout();
    $current = $layout
      ->getPluginId() == $layout_id;
    if (!$current) {

      // Create a new layout instance.
      $layout = $this->layoutManager
        ->createInstance($layout_id, []);
    }

    // Save the layout for future use.
    $this->layout = $layout;
    if ($layout instanceof PluginFormInterface) {
      $form['settings'] = $layout
        ->buildConfigurationForm([], $form_state);
    }
    $form['settings']['#tree'] = TRUE;

    // If the form is empty, inform the user or auto-submit if they are changing
    // layouts.
    if (empty(Element::getVisibleChildren($form['settings']))) {
      if ($current) {
        $form['settings'][] = [
          '#markup' => $this
            ->t('<h5>This layout does not provide any configuration.</h5>'),
        ];
      }
      else {
        $this
          ->submitForm($form, $form_state);
      }
    }

    // Add an add button, which is only used by our App.
    $form['submit'] = [
      '#type' => 'button',
      '#value' => $current ? $this
        ->t('Update') : $this
        ->t('Change Layout'),
      '#ajax' => [
        'callback' => '::submitForm',
        'wrapper' => 'panels-ipe-layout-form-wrapper',
        'method' => 'replace',
        'progress' => [
          'type' => 'throbber',
          'message' => '',
        ],
      ],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if ($this->layout instanceof PluginFormInterface) {
      $layout_form_state = (new FormState())
        ->setValues($form_state
        ->getValue('settings', []));
      $this->layout
        ->validateConfigurationForm($form, $layout_form_state);

      // Update the original form values.
      $form_state
        ->setValue('settings', $layout_form_state
        ->getValues());
    }
  }

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

    // Return early if there are any errors.
    if ($form_state
      ->hasAnyErrors()) {
      return $form;
    }
    $panels_display = $this->panelsDisplay;

    // Submit the layout form.
    if ($this->layout instanceof PluginFormInterface) {
      $layout_form_state = (new FormState())
        ->setValues($form_state
        ->getValue('settings', []));
      $this->layout
        ->submitConfigurationForm($form, $layout_form_state);
    }
    $layout_config = $this->layout
      ->getConfiguration();

    // Shift our blocks to the first available region. The IPE can control
    // re-assigning blocks in a smarter way.
    $first_region = $this->layout
      ->getPluginDefinition()
      ->getDefaultRegion();

    // For each block, set the region to match the new layout.
    foreach ($panels_display
      ->getRegionAssignments() as $region => $region_assignment) {

      /** @var \Drupal\Core\Block\BlockPluginInterface $block */
      foreach ($region_assignment as $block_id => $block) {
        $block_config = $block
          ->getConfiguration();

        // If the new layout does not have a region with the same name, use the
        // first available region.
        if (!isset($region_definitions[$block_config['region']])) {
          $block_config['region'] = $first_region;
          $panels_display
            ->updateBlock($block_id, $block_config);
        }
      }
    }

    // Have our panels display use the new layout.
    $this->panelsDisplay
      ->setLayout($this->layout, $layout_config);

    // Update tempstore.
    $this->tempStore
      ->set($panels_display
      ->getTempStoreId(), $panels_display
      ->getConfiguration());
    $region_data = [];
    $region_content = [];

    // Compile region content and metadata.
    $regions = $panels_display
      ->getRegionAssignments();
    foreach ($regions as $id => $label) {

      // Wrap the region with a class/data attribute that our app can use.
      $region_name = Html::getClass("block-region-{$id}");
      $region_content[$id] = [
        '#prefix' => '<div class="' . $region_name . '" data-region-name="' . $id . '">',
        '#suffix' => '</div>',
      ];

      // Format region metadata.
      $region_data[] = [
        'name' => $id,
        'label' => $label,
      ];
    }
    $build = $panels_display
      ->getLayout()
      ->build($region_content);
    $form['build'] = $build;
    $data = [
      'id' => $this->layout
        ->getPluginId(),
      'label' => $this->layout
        ->getPluginDefinition()
        ->getLabel(),
      'current' => TRUE,
      'html' => $this->renderer
        ->render($build),
      'regions' => $region_data,
    ];

    // Add Block metadata and HTML as a drupalSetting.
    $form['#attached']['drupalSettings']['panels_ipe']['updated_layout'] = $data;
    return $form;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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.
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.
PanelsIPELayoutForm::$layout protected property The current layout.
PanelsIPELayoutForm::$layoutManager protected property
PanelsIPELayoutForm::$panelsDisplay protected property The Panels storage manager.
PanelsIPELayoutForm::$renderer protected property
PanelsIPELayoutForm::$tempStore protected property
PanelsIPELayoutForm::buildForm public function Builds a form that configure an existing or new layout for the IPE. Overrides FormInterface::buildForm
PanelsIPELayoutForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
PanelsIPELayoutForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
PanelsIPELayoutForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
PanelsIPELayoutForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
PanelsIPELayoutForm::__construct public function Constructs a new PanelsIPEBlockPluginForm.
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.