You are here

class ConfigPagesTypeForm in Config Pages 8.3

Same name and namespace in other branches
  1. 8 src/ConfigPagesTypeForm.php \Drupal\config_pages\ConfigPagesTypeForm
  2. 8.2 src/ConfigPagesTypeForm.php \Drupal\config_pages\ConfigPagesTypeForm

Base form for category edit forms.

Hierarchy

Expanded class hierarchy of ConfigPagesTypeForm

File

src/ConfigPagesTypeForm.php, line 16

Namespace

Drupal\config_pages
View source
class ConfigPagesTypeForm extends EntityForm {

  /**
   * Required routes rebuild.
   *
   * @var string
   */
  protected $routesRebuildRequired = FALSE;

  /**
   * @var PathValidatorInterface|\Drupal\Core\Path\PathValidatorInterface
   */
  protected $pathValidator;

  /**
   * @var RouteBuilderInterface|\Drupal\Core\Routing\RouteBuilderInterface
   */
  protected $routerBuilder;

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs a ConfigPagesForm object.
   *
   * @param \Drupal\Core\Path\PathValidatorInterface $path_validator
   *   The path validator class.
   * @param \Drupal\Core\Routing\RouteBuilderInterface
   *   The router interface.
   * @param MessengerInterface $messenger
   */
  public function __construct(PathValidatorInterface $path_validator, RouteBuilderInterface $router_builder, MessengerInterface $messenger) {
    $this->pathValidator = $path_validator;
    $this->routerBuilder = $router_builder;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('path.validator'), $container
      ->get('router.builder'), $container
      ->get('messenger'));
  }

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

    /* @var \Drupal\config_pages\ConfigPagesTypeInterface $config_pages_type */
    $config_pages_type = $this->entity;
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => t('Label'),
      '#maxlength' => 255,
      '#default_value' => $config_pages_type
        ->label(),
      '#description' => t("Provide a label for this config page type to help identify it in the administration pages."),
      '#required' => TRUE,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $config_pages_type
        ->id(),
      '#machine_name' => [
        'exists' => '\\Drupal\\config_pages\\Entity\\ConfigPagesType::load',
      ],
      '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
      '#disabled' => !$config_pages_type
        ->isNew(),
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => t('Save'),
    ];
    $options = [];
    $items = \Drupal::service('plugin.manager.config_pages_context')
      ->getDefinitions();
    foreach ($items as $plugin_id => $item) {
      $options[$plugin_id] = $item['label'];
    }

    // Menu.
    $form['menu'] = [
      '#type' => 'details',
      '#title' => t('Menu'),
      '#tree' => TRUE,
      '#open' => TRUE,
    ];
    $form['menu']['path'] = [
      '#type' => 'textfield',
      '#description' => t('Menu path which will be used for form display.'),
      '#default_value' => !empty($config_pages_type->menu['path']) ? $config_pages_type->menu['path'] : [],
      '#required' => FALSE,
    ];
    $weight = [];
    foreach (range(-50, 50) as $number) {
      $weight[$number] = $number;
    }
    $form['menu']['weight'] = [
      '#type' => 'select',
      '#description' => t('Weight of menu item.'),
      '#options' => $weight,
      '#default_value' => !empty($config_pages_type->menu['weight']) ? $config_pages_type->menu['weight'] : 0,
      '#required' => FALSE,
    ];
    $form['menu']['description'] = [
      '#type' => 'textfield',
      '#description' => t('Description will be displayed under link in Drupal BO.'),
      '#default_value' => !empty($config_pages_type->menu['description']) ? $config_pages_type->menu['description'] : '',
      '#required' => FALSE,
    ];

    // Context.
    $form['context'] = [
      '#type' => 'details',
      '#title' => t('Context'),
      '#tree' => TRUE,
      '#open' => FALSE,
    ];
    $form['context']['show_warning'] = [
      '#type' => 'checkbox',
      '#title' => t('Show context info message on ConfigPage edit form.'),
      '#default_value' => !empty($config_pages_type->context['show_warning']) ? $config_pages_type->context['show_warning'] : TRUE,
      '#required' => FALSE,
    ];
    $default_options = [];
    if (!empty($config_pages_type->context['group'])) {
      foreach ($config_pages_type->context['group'] as $key => $value) {
        if ($value) {
          $default_options[] = $key;
        }
      }
    }
    $form['context']['group'] = [
      '#type' => 'checkboxes',
      '#description' => t('Consider following context for this configuration'),
      '#options' => $options,
      '#default_value' => $default_options,
      '#required' => FALSE,
    ];
    $form['context']['fallback_text'] = [
      '#prefix' => '<h2>',
      '#suffix' => '</h2>',
      '#markup' => $this
        ->t('Fallback for contexts'),
    ];
    foreach ($options as $contextId => $contextLabel) {
      $form['context']['fallback'][$contextId] = [
        '#type' => 'textfield',
        '#title' => $contextLabel,
        '#description' => $this
          ->t('Value that the context is going to have when no config page is found for the current context'),
        '#default_value' => empty($config_pages_type->context['fallback'][$contextId]) ? '' : $config_pages_type->context['fallback'][$contextId],
        '#required' => FALSE,
      ];
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $new_menu_path = $form_state
      ->getValue('menu')['path'];
    if (!empty($new_menu_path) && !in_array($new_menu_path[0], [
      '/',
    ], TRUE)) {
      $form_state
        ->setErrorByName('menu', $this
        ->t('Manually entered paths should start with /'));
      return;
    }
    $old_menu_path = NULL;

    // Load unchanged entity.
    $config_pages_type = $this->entity;
    $config_pages_type_unchanged = $config_pages_type
      ->load($config_pages_type
      ->id());
    if (is_object($config_pages_type_unchanged)) {
      $old_menu_path = $config_pages_type_unchanged->menu['path'];
    }

    // If menu path was changed check if it's a valid Drupal path.
    if (!empty($new_menu_path) && $new_menu_path != $old_menu_path) {
      $path_exists = $this->pathValidator
        ->isValid($new_menu_path);
      if ($path_exists) {
        $form_state
          ->setErrorByName('menu', $this
          ->t('This menu path is already exists, please provide another one.'));
      }
      $this->routesRebuildRequired = TRUE;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $config_pages_type = $this->entity;
    $status = $config_pages_type
      ->save();
    $edit_link = $this->entity
      ->toLink($this
      ->t('Edit'), 'edit-form')
      ->toString();
    $logger = $this
      ->logger('config_pages');
    if ($status == SAVED_UPDATED) {
      $this->messenger
        ->addStatus(t('Custom config page type %label has been updated.', [
        '%label' => $config_pages_type
          ->label(),
      ]));
      $logger
        ->notice('Custom config page type %label has been updated.', [
        '%label' => $config_pages_type
          ->label(),
        'link' => $edit_link,
      ]);
    }
    else {
      $this->messenger
        ->addStatus(t('Custom config page type %label has been added.', [
        '%label' => $config_pages_type
          ->label(),
      ]));
      $logger
        ->notice('Custom config page type %label has been added.', [
        '%label' => $config_pages_type
          ->label(),
        'link' => $edit_link,
      ]);
    }

    // Check if we need to rebuild routes.
    if ($this->routesRebuildRequired) {
      $this->routerBuilder
        ->rebuild();
    }
    $form_state
      ->setRedirectUrl($this->entity
      ->toUrl('collection'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigPagesTypeForm::$messenger protected property The Messenger service. Overrides MessengerTrait::$messenger
ConfigPagesTypeForm::$pathValidator protected property
ConfigPagesTypeForm::$routerBuilder protected property
ConfigPagesTypeForm::$routesRebuildRequired protected property Required routes rebuild.
ConfigPagesTypeForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ConfigPagesTypeForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
ConfigPagesTypeForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
ConfigPagesTypeForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ConfigPagesTypeForm::__construct public function Constructs a ConfigPagesForm object.
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
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 17
EntityForm::__get public function
EntityForm::__set public function
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 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.