You are here

class PageVariantAddForm in Page Manager 8.4

Same name and namespace in other branches
  1. 8 page_manager_ui/src/Form/PageVariantAddForm.php \Drupal\page_manager_ui\Form\PageVariantAddForm

Provides a form for adding a variant.

Hierarchy

Expanded class hierarchy of PageVariantAddForm

1 file declares its use of PageVariantAddForm
PageVariantAddWizard.php in page_manager_ui/src/Wizard/PageVariantAddWizard.php

File

page_manager_ui/src/Form/PageVariantAddForm.php, line 16

Namespace

Drupal\page_manager_ui\Form
View source
class PageVariantAddForm extends FormBase {

  /**
   * The variant manager.
   *
   * @var \Drupal\Core\Display\VariantManager
   */
  protected $variantManager;

  /**
   * Tempstore factory.
   *
   * @var \Drupal\Core\TempStore\SharedTempStoreFactory
   */
  protected $tempstore;

  /**
   * Constructs a new DisplayVariantAddForm.
   *
   * @param \Drupal\Core\Display\VariantManager $variant_manager
   *   The variant manager.
   * @param \Drupal\Core\TempStore\SharedTempStoreFactory $tempstore
   *   The shared temp store factory.
   */
  public function __construct(VariantManager $variant_manager, SharedTempStoreFactory $tempstore) {
    $this->variantManager = $variant_manager;
    $this->tempstore = $tempstore;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $machine_name = '') {
    $cached_values = $form_state
      ->getTemporaryValue('wizard');

    // The name label for variants is not required and can be changed later.
    $form['name']['label']['#required'] = FALSE;
    $form['name']['label']['#disabled'] = FALSE;
    $variant_plugin_options = [];
    foreach ($this->variantManager
      ->getDefinitions() as $plugin_id => $definition) {

      // The following two variants are provided by Drupal Core. They are not
      // configurable and therefore not compatible with Page Manager but have
      // similar and confusing labels. Skip them so that they are not shown in
      // the UI.
      if (in_array($plugin_id, [
        'simple_page',
        'block_page',
      ])) {
        continue;
      }
      $variant_plugin_options[$plugin_id] = $definition['admin_label'];
    }
    $form['variant_plugin_id'] = [
      '#title' => $this
        ->t('Type'),
      '#type' => 'select',
      '#options' => $variant_plugin_options,
      '#default_value' => !empty($cached_values['variant_plugin_id']) ? $cached_values['variant_plugin_id'] : '',
    ];
    $form['wizard_options'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Optional features'),
      '#description' => $this
        ->t('Check any optional features you need to be presented with forms for configuring them. If you do not check them here you will still be able to utilize these features once the new variant is created.'),
      '#options' => [
        'selection' => $this
          ->t('Selection criteria'),
        'contexts' => $this
          ->t('Contexts'),
      ],
      '#default_value' => !empty($cached_values['wizard_options']) ? $cached_values['wizard_options'] : [],
    ];
    return $form;
  }

  /**
   * Check if a variant id is taken.
   *
   * @param \Drupal\page_manager\PageInterface $page
   *   The page entity.
   * @param string $variant_id
   *   The page variant id to check.
   *
   * @return bool
   *   TRUE if the ID is available; FALSE otherwise.
   */
  protected function variantExists(PageInterface $page, $variant_id) {
    return isset($page
      ->getVariants()[$variant_id]) || PageVariant::load($variant_id);
  }

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

    // If the label is not present or is an empty string.
    if (!$form_state
      ->hasValue('label') || !$form_state
      ->getValue('label')) {
      $cached_values = $form_state
        ->getTemporaryValue('wizard');

      /** @var $page_variant \Drupal\page_manager\Entity\PageVariant */
      $page_variant = $cached_values['page_variant'];
      $plugin = $page_variant
        ->getVariantPlugin();

      /** @var \Drupal\Core\StringTranslation\TranslatableMarkup $admin_label */
      $admin_label = $plugin
        ->getPluginDefinition()['admin_label'];
      $form_state
        ->setValue('label', (string) $admin_label);
    }

    // Currently the parent does nothing, but that could change.
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $cached_values = $form_state
      ->getTemporaryValue('wizard');

    /** @var $page \Drupal\page_manager\Entity\Page */
    $page = $cached_values['page'];
    $variant_plugin_id = $cached_values['variant_plugin_id'] = $form_state
      ->getValue('variant_plugin_id');

    /** @var $page_variant \Drupal\page_manager\Entity\PageVariant */
    $page_variant = $cached_values['page_variant'];
    $page_variant
      ->setVariantPluginId($variant_plugin_id);
    $page_variant
      ->set('label', $form_state
      ->getValue('label'));
    $page_variant
      ->set('page', $page
      ->id());

    // Loop over variant ids until one is available.
    $variant_id_base = "{$page->id()}-{$variant_plugin_id}";
    $key = 0;
    while ($this
      ->variantExists($page, "{$variant_id_base}-{$key}")) {
      $key++;
    }
    $cached_values['id'] = "{$variant_id_base}-{$key}";
    $page_variant
      ->set('id', $cached_values['id']);
    $cached_values['wizard_options'] = $form_state
      ->getValue('wizard_options');
    $form_state
      ->setTemporaryValue('wizard', $cached_values);
  }

}

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.
PageVariantAddForm::$tempstore protected property Tempstore factory.
PageVariantAddForm::$variantManager protected property The variant manager.
PageVariantAddForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
PageVariantAddForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
PageVariantAddForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
PageVariantAddForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
PageVariantAddForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
PageVariantAddForm::variantExists protected function Check if a variant id is taken.
PageVariantAddForm::__construct public function Constructs a new DisplayVariantAddForm.
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.