You are here

abstract class PathFormBase in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/path/src/Form/PathFormBase.php \Drupal\path\Form\PathFormBase

Provides a base class for path add/edit forms.

Hierarchy

Expanded class hierarchy of PathFormBase

File

core/modules/path/src/Form/PathFormBase.php, line 22
Contains \Drupal\path\Form\PathFormBase.

Namespace

Drupal\path\Form
View source
abstract class PathFormBase extends FormBase {

  /**
   * An array containing the path ID, source, alias, and language code.
   *
   * @var array
   */
  protected $path;

  /**
   * The path alias storage.
   *
   * @var \Drupal\Core\Path\AliasStorageInterface
   */
  protected $aliasStorage;

  /**
   * The path alias manager.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * The path validator.
   *
   * @var \Drupal\Core\Path\PathValidatorInterface
   */
  protected $pathValidator;

  /**
   * The request context.
   *
   * @var \Drupal\Core\Routing\RequestContext
   */
  protected $requestContext;

  /**
   * Constructs a new PathController.
   *
   * @param \Drupal\Core\Path\AliasStorageInterface $alias_storage
   *   The path alias storage.
   * @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
   *   The path alias manager.
   * @param \Drupal\Core\Path\PathValidatorInterface $path_validator
   *   The path validator.
   * @param \Drupal\Core\Routing\RequestContext $request_context
   *   The request context.
   */
  public function __construct(AliasStorageInterface $alias_storage, AliasManagerInterface $alias_manager, PathValidatorInterface $path_validator, RequestContext $request_context) {
    $this->aliasStorage = $alias_storage;
    $this->aliasManager = $alias_manager;
    $this->pathValidator = $path_validator;
    $this->requestContext = $request_context;
  }

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

  /**
   * Builds the path used by the form.
   *
   * @param int|null $pid
   *   Either the unique path ID, or NULL if a new one is being created.
   */
  protected abstract function buildPath($pid);

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $pid = NULL) {
    $this->path = $this
      ->buildPath($pid);
    $form['source'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Existing system path'),
      '#default_value' => $this->path['source'],
      '#maxlength' => 255,
      '#size' => 45,
      '#description' => $this
        ->t('Specify the existing path you wish to alias. For example: /node/28, /forum/1, /taxonomy/term/1.'),
      '#field_prefix' => $this->requestContext
        ->getCompleteBaseUrl(),
      '#required' => TRUE,
    );
    $form['alias'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Path alias'),
      '#default_value' => $this->path['alias'],
      '#maxlength' => 255,
      '#size' => 45,
      '#description' => $this
        ->t('Specify an alternative path by which this data can be accessed. For example, type "/about" when writing an about page. Use a relative path with a slash in front..'),
      '#field_prefix' => $this->requestContext
        ->getCompleteBaseUrl(),
      '#required' => TRUE,
    );

    // A hidden value unless language.module is enabled.
    if (\Drupal::moduleHandler()
      ->moduleExists('language')) {
      $languages = \Drupal::languageManager()
        ->getLanguages();
      $language_options = array();
      foreach ($languages as $langcode => $language) {
        $language_options[$langcode] = $language
          ->getName();
      }
      $form['langcode'] = array(
        '#type' => 'select',
        '#title' => $this
          ->t('Language'),
        '#options' => $language_options,
        '#empty_value' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
        '#empty_option' => $this
          ->t('- None -'),
        '#default_value' => $this->path['langcode'],
        '#weight' => -10,
        '#description' => $this
          ->t('A path alias set for a specific language will always be used when displaying this page in that language, and takes precedence over path aliases set as <em>- None -</em>.'),
      );
    }
    else {
      $form['langcode'] = array(
        '#type' => 'value',
        '#value' => $this->path['langcode'],
      );
    }
    $form['actions'] = array(
      '#type' => 'actions',
    );
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $source =& $form_state
      ->getValue('source');
    $source = $this->aliasManager
      ->getPathByAlias($source);
    $alias =& $form_state
      ->getValue('alias');

    // Trim the submitted value of whitespace and slashes. Ensure to not trim
    // the slash on the left side.
    $alias = rtrim(trim(trim($alias), ''), "\\/");
    if ($source[0] !== '/') {
      $form_state
        ->setErrorByName('source', 'The source path has to start with a slash.');
    }
    if ($alias[0] !== '/') {
      $form_state
        ->setErrorByName('alias', 'The alias path has to start with a slash.');
    }

    // Language is only set if language.module is enabled, otherwise save for all
    // languages.
    $langcode = $form_state
      ->getValue('langcode', LanguageInterface::LANGCODE_NOT_SPECIFIED);
    if ($this->aliasStorage
      ->aliasExists($alias, $langcode, $this->path['source'])) {
      $stored_alias = $this->aliasStorage
        ->load([
        'alias' => $alias,
        'langcode' => $langcode,
      ]);
      if ($stored_alias['alias'] !== $alias) {

        // The alias already exists with different capitalization as the default
        // implementation of AliasStorageInterface::aliasExists is
        // case-insensitive.
        $form_state
          ->setErrorByName('alias', t('The alias %alias could not be added because it is already in use in this language with different capitalization: %stored_alias.', [
          '%alias' => $alias,
          '%stored_alias' => $stored_alias['alias'],
        ]));
      }
      else {
        $form_state
          ->setErrorByName('alias', t('The alias %alias is already in use in this language.', [
          '%alias' => $alias,
        ]));
      }
    }
    if (!$this->pathValidator
      ->isValid(trim($source, '/'))) {
      $form_state
        ->setErrorByName('source', t("The path '@link_path' is either invalid or you do not have access to it.", array(
        '@link_path' => $source,
      )));
    }
  }

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

    // Remove unnecessary values.
    $form_state
      ->cleanValues();
    $pid = $form_state
      ->getValue('pid', 0);
    $source = $form_state
      ->getValue('source');
    $alias = $form_state
      ->getValue('alias');

    // Language is only set if language.module is enabled, otherwise save for all
    // languages.
    $langcode = $form_state
      ->getValue('langcode', LanguageInterface::LANGCODE_NOT_SPECIFIED);
    $this->aliasStorage
      ->save($source, $alias, $langcode, $pid);
    drupal_set_message($this
      ->t('The alias has been saved.'));
    $form_state
      ->setRedirect('path.admin_overview');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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. 3
FormBase::$loggerFactory protected property The logger factory.
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. 3
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::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.
FormInterface::getFormId public function Returns a unique string identifying the form. 212
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator protected function Returns the link generator.
LinkGeneratorTrait::l protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator public function Sets the link generator service.
PathFormBase::$aliasManager protected property The path alias manager.
PathFormBase::$aliasStorage protected property The path alias storage.
PathFormBase::$path protected property An array containing the path ID, source, alias, and language code.
PathFormBase::$pathValidator protected property The path validator.
PathFormBase::$requestContext protected property The request context.
PathFormBase::buildForm public function Form constructor. Overrides FormInterface::buildForm 1
PathFormBase::buildPath abstract protected function Builds the path used by the form. 2
PathFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create
PathFormBase::submitForm public function Form submission handler. Overrides FormInterface::submitForm
PathFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm
PathFormBase::__construct public function Constructs a new PathController.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service.
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.
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 protected function Returns the URL generator service.
UrlGeneratorTrait::redirect protected function Returns a redirect response object for the specified route.
UrlGeneratorTrait::setUrlGenerator public function Sets the URL generator service.
UrlGeneratorTrait::url protected function Generates a URL or path for a specific route based on the given parameters.