You are here

class ParameterEditForm in Page Manager 8

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

Provides a form for editing a parameter.

Hierarchy

Expanded class hierarchy of ParameterEditForm

1 string reference to 'ParameterEditForm'
page_manager_ui.routing.yml in page_manager_ui/page_manager_ui.routing.yml
page_manager_ui/page_manager_ui.routing.yml

File

page_manager_ui/src/Form/ParameterEditForm.php, line 22
Contains \Drupal\page_manager_ui\Form\ParameterEditForm.

Namespace

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

  /**
   * The form key for unsetting a parameter context.
   *
   * @var string
   */
  const NO_CONTEXT_KEY = '__no_context';

  /**
   * The page entity this static context belongs to.
   *
   * @var \Drupal\page_manager\PageInterface
   */
  protected $page;

  /**
   * The entity type repository.
   *
   * @var \Drupal\Core\Entity\EntityTypeRepositoryInterface
   */
  protected $entityTypeRepository;

  /**
   * The typed data manager.
   *
   * @var \Drupal\Core\TypedData\TypedDataManagerInterface
   */
  protected $typedDataManager;

  /**
   * @var \Drupal\user\SharedTempStoreFactory
   */
  protected $tempstore;

  /**
   * @var string
   */
  protected $tempstore_id;

  /**
   * The machine name of the page being edited in tempstore.
   *
   * @var string
   */
  protected $machine_name;

  /**
   * Constructs a new ParameterEditForm.
   *
   * @param \Drupal\Core\Entity\EntityTypeRepositoryInterface $entity_type_repository
   *   The entity type repository.
   * @param \Drupal\Core\TypedData\TypedDataManagerInterface $typed_data_manager
   *   The typed data manager.
   * @param \Drupal\user\SharedTempStoreFactory $tempstore
   *   The temporary store.
   */
  public function __construct(EntityTypeRepositoryInterface $entity_type_repository, TypedDataManagerInterface $typed_data_manager, SharedTempStoreFactory $tempstore) {
    $this->entityTypeRepository = $entity_type_repository;
    $this->typedDataManager = $typed_data_manager;
    $this->tempstore = $tempstore;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.repository'), $container
      ->get('typed_data_manager'), $container
      ->get('user.shared_tempstore'));
  }
  protected function getTempstore() {
    return $this->tempstore
      ->get($this->tempstore_id)
      ->get($this->machine_name);
  }
  protected function setTempstore($cached_values) {
    $this->tempstore
      ->get($this->tempstore_id)
      ->set($this->machine_name, $cached_values);
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $name = '', $tempstore_id = NULL, $machine_name = NULL) {
    $this->tempstore_id = $tempstore_id;
    $this->machine_name = $machine_name;
    $cached_values = $this
      ->getTempstore();
    $page = $cached_values['page'];
    $parameter = $page
      ->getParameter($name);
    $form['machine_name'] = [
      '#type' => 'value',
      '#value' => $name,
    ];
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Label'),
      '#default_value' => $parameter['label'] ?: ucfirst($parameter['machine_name']),
      '#states' => [
        'invisible' => [
          ':input[name="type"]' => [
            'value' => static::NO_CONTEXT_KEY,
          ],
        ],
      ],
    ];
    $form['type'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Type'),
      '#required' => TRUE,
      '#options' => $this
        ->buildParameterTypeOptions(),
      '#default_value' => $parameter['type'],
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Update parameter'),
      '#button_type' => 'primary',
    ];
    return $form;
  }

  /**
   * Builds an array of options for the parameter type.
   *
   * @return array[]
   *   A multidimensional array. The top level is keyed by group ('Content',
   *   'Configuration', 'Typed Data'). Those values are an array of type labels,
   *   keyed by the machine name.
   */
  protected function buildParameterTypeOptions() {
    $options = [
      static::NO_CONTEXT_KEY => $this
        ->t('No context selected'),
    ];

    // Make a grouped, sorted list of entity type options. Key the inner array
    // to use the typed data format of 'entity:$entity_type_id'.
    foreach ($this->entityTypeRepository
      ->getEntityTypeLabels(TRUE) as $group_label => $grouped_options) {
      foreach ($grouped_options as $key => $label) {
        $options[$group_label]['entity:' . $key] = $label;
      }
    }
    $primitives_label = (string) $this
      ->t('Primitives');
    foreach ($this->typedDataManager
      ->getDefinitions() as $key => $definition) {
      if (is_subclass_of($definition['class'], PrimitiveInterface::class)) {
        $options[$primitives_label][$key] = $definition['label'];
      }
    }
    asort($options[$primitives_label], SORT_NATURAL);
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $cache_values = $this
      ->getTempstore();

    /** @var \Drupal\page_manager\PageInterface $page */
    $page = $cache_values['page'];
    $name = $form_state
      ->getValue('machine_name');
    $type = $form_state
      ->getValue('type');
    if ($type === static::NO_CONTEXT_KEY) {
      $page
        ->removeParameter($name);
      $label = NULL;
    }
    else {
      $label = $form_state
        ->getValue('label');
      $page
        ->setParameter($name, $type, $label);
    }
    $this
      ->setTempstore($cache_values);
    drupal_set_message($this
      ->t('The %label parameter has been updated.', [
      '%label' => $label ?: $name,
    ]));
    list($route_name, $route_parameters) = $this
      ->getParentRouteInfo($cache_values);
    $form_state
      ->setRedirect($route_name, $route_parameters);
  }

  /**
   * Returns the parent route to redirect after form submission.
   *
   * @return array
   *   Array containing the route name and its parameters.
   */
  protected function getParentRouteInfo($cached_values) {

    /** @var $page \Drupal\page_manager\PageInterface */
    $page = $cached_values['page'];
    if ($page
      ->isNew()) {
      return [
        'entity.page.add_step_form',
        [
          'machine_name' => $this->machine_name,
          'step' => 'parameters',
        ],
      ];
    }
    else {
      return [
        'entity.page.edit_form',
        [
          'machine_name' => $this->machine_name,
          'step' => 'parameters',
        ],
      ];
    }
  }

}

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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
ParameterEditForm::$entityTypeRepository protected property The entity type repository.
ParameterEditForm::$machine_name protected property The machine name of the page being edited in tempstore.
ParameterEditForm::$page protected property The page entity this static context belongs to.
ParameterEditForm::$tempstore protected property
ParameterEditForm::$tempstore_id protected property
ParameterEditForm::$typedDataManager protected property The typed data manager.
ParameterEditForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ParameterEditForm::buildParameterTypeOptions protected function Builds an array of options for the parameter type.
ParameterEditForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ParameterEditForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ParameterEditForm::getParentRouteInfo protected function Returns the parent route to redirect after form submission.
ParameterEditForm::getTempstore protected function
ParameterEditForm::NO_CONTEXT_KEY constant The form key for unsetting a parameter context.
ParameterEditForm::setTempstore protected function
ParameterEditForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ParameterEditForm::__construct public function Constructs a new ParameterEditForm.
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.