You are here

class MenuLinkConfigForm in Config menu link 8

Hierarchy

Expanded class hierarchy of MenuLinkConfigForm

1 string reference to 'MenuLinkConfigForm'
menu_link_config.links.menu.yml in ./menu_link_config.links.menu.yml
menu_link_config.links.menu.yml

File

src/Plugin/Menu/Form/MenuLinkConfigForm.php, line 28
Contains \Drupal\menu_link_config\Plugin\Menu\Form\MenuLinkConfigForm.

Namespace

Drupal\menu_link_config\Plugin\Menu\Form
View source
class MenuLinkConfigForm extends EntityForm implements MenuLinkFormInterface {

  /**
   * The edited menu link.
   *
   * @var \Drupal\menu_link_config\Entity\MenuLinkConfig
   */
  protected $entity;

  /**
   * The menu link manager.
   *
   * @var \Drupal\Core\Menu\MenuLinkManagerInterface
   */
  protected $menuLinkManager;

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityManager;

  /**
   * The menu parent form selector.
   *
   * @var \Drupal\Core\Menu\MenuParentFormSelectorInterface
   */
  protected $menuParentSelector;

  /**
   * Constructs a new MenuLinkConfigForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
   *   The entity manager.
   * @param \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager
   *   The menu link manager.
   * @param \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_form_selector
   *   The menu parent form selector.
   * @param \Drupal\Core\Access\AccessManagerInterface $access_manager
   * @param \Drupal\Core\Session\AccountInterface $account
   * @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   */
  public function __construct(EntityTypeManagerInterface $entity_manager, MenuLinkManagerInterface $menu_link_manager, MenuParentFormSelectorInterface $menu_parent_form_selector, AccessManagerInterface $access_manager, AccountInterface $account, AliasManagerInterface $alias_manager, ModuleHandlerInterface $module_handler, TranslationInterface $string_translation) {
    $this->entityManager = $entity_manager;
    $this->menuLinkManager = $menu_link_manager;
    $this->menuParentSelector = $menu_parent_form_selector;
    $this->accessManager = $access_manager;
    $this->account = $account;
    $this->pathAliasManager = $alias_manager;
    $this
      ->setModuleHandler($module_handler);
    $this
      ->setStringTranslation($string_translation);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('plugin.manager.menu.link'), $container
      ->get('menu.parent_form_selector'), $container
      ->get('access_manager'), $container
      ->get('current_user'), $container
      ->get('path.alias_manager'), $container
      ->get('module_handler'), $container
      ->get('string_translation'));
  }

  /**
   * {@inheritdoc}
   */
  public function setMenuLinkInstance(MenuLinkInterface $menu_link) {

    // Load the entity for the entity form. Loading by entity ID is much faster
    // than loading by UUID, so use that ID if we have it.
    $metadata = $menu_link
      ->getMetaData();
    if (!empty($metadata['entity_id'])) {
      $this->entity = $this->entityManager
        ->getStorage('menu_link_config')
        ->load($metadata['entity_id']);
    }
    else {

      // Fallback to the loading by UUID.
      $links = $this->entityManager
        ->getStorage('menu_link_config')
        ->loadByProperties([
        'uuid' => $menu_link
          ->getDerivativeId(),
      ]);
      $this->entity = reset($links);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $this
      ->setOperation('default');
    $this
      ->init($form_state);
    return $this
      ->form($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this
      ->doValidate($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    parent::form($form, $form_state);
    $form['#title'] = $this
      ->t('Edit menu link %title', [
      '%title' => $this->entity
        ->getTitle(),
    ]);

    // Put the title field first.
    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Title'),
      '#default_value' => $this->entity
        ->getTitle(),
      '#weight' => -10,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#maxlength' => 128,
      '#machine_name' => [
        'source' => [
          'title',
        ],
        'exists' => '\\Drupal\\menu_link_config\\Controller\\MenuController::getMenuLink',
      ],
      '#disabled' => !$this->entity
        ->isNew(),
      '#weight' => -9,
    ];
    $form['description'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Description'),
      '#description' => $this
        ->t('Shown when hovering over the menu link.'),
      '#default_value' => $this->entity
        ->getDescription(),
      '#weight' => -5,
    ];
    $link = [
      '#type' => 'link',
      '#title' => $this->entity
        ->getTitle(),
    ] + $this->entity
      ->getUrlObject()
      ->toRenderArray();
    $form['info'] = [
      'link' => $link,
      '#type' => 'item',
      '#title' => $this
        ->t('Link'),
    ];

    // We always show the internal path here.

    /** @var \Drupal\Core\Url $url */
    $url = $this->entity
      ->getUrlObject();
    if ($url
      ->isExternal()) {
      $default_value = $url
        ->toString();
    }
    elseif ($url
      ->getRouteName() == '<front>') {

      // The default route for new entities is <front>, but we just want an
      // empty form field.
      $default_value = $this->entity
        ->isNew() ? '' : '<front>';
    }
    else {

      // @todo Url::getInternalPath() calls UrlGenerator::getPathFromRoute()
      // which need a replacement since it is deprecated.
      // https://www.drupal.org/node/2307061
      try {
        $default_value = $url
          ->getInternalPath();
      } catch (\Exception $e) {
        $default_value = 'broken path';
      }

      // @todo Add a helper method to Url to render just the query string and
      // fragment. https://www.drupal.org/node/2305013
      $options = $url
        ->getOptions();
      if (isset($options['query'])) {
        $default_value .= $options['query'] ? '?' . UrlHelper::buildQuery($options['query']) : '';
      }
      if (isset($options['fragment']) && $options['fragment'] !== '') {
        $default_value .= '#' . $options['fragment'];
      }
    }
    $form['url'] = [
      '#title' => $this
        ->t('Link path'),
      '#type' => 'textfield',
      '#description' => $this
        ->t('The path for this menu link. This can be an internal Drupal path such as %add-node or an external URL such as %drupal. Enter %front to link to the front page.', [
        '%front' => '<front>',
        '%add-node' => '/node/add',
        '%drupal' => 'http://drupal.org',
      ]),
      '#default_value' => $default_value,
      '#required' => TRUE,
      '#weight' => -2,
    ];
    $form['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enable menu link'),
      '#description' => $this
        ->t('Menu links that are not enabled will not be listed in any menu.'),
      '#default_value' => $this->entity
        ->status(),
    ];
    $form['expanded'] = [
      '#type' => 'checkbox',
      '#title' => t('Show as expanded'),
      '#description' => $this
        ->t('If selected and this menu link has children, the menu will always appear expanded.'),
      '#default_value' => $this->entity
        ->isExpanded(),
    ];
    $menu_parent = $this->entity
      ->getMenuName() . ':' . $this->entity
      ->getParent();
    $form['menu_parent'] = $this->menuParentSelector
      ->parentSelectElement($menu_parent, $this->entity
      ->getPluginId());
    $form['menu_parent']['#title'] = $this
      ->t('Parent link');
    $form['menu_parent']['#description'] = $this
      ->t('The maximum depth for a link and all its children is fixed. Some menu links may not be available as parents if selecting them would exceed this limit.');
    $form['menu_parent']['#attributes']['class'][] = 'menu-title-select';
    $delta = max(abs($this->entity
      ->getWeight()), 50);
    $form['weight'] = [
      '#type' => 'number',
      '#min' => -$delta,
      '#max' => $delta,
      '#default_value' => $this->entity
        ->getWeight(),
      '#title' => $this
        ->t('Weight'),
      '#description' => $this
        ->t('Link weight among links in the same menu at the same depth. In the menu, the links with high weight will sink and links with a low weight will be positioned nearer the top.'),
    ];
    return $form;
  }

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

    /** @var \Drupal\menu_link_config\Entity\MenuLinkConfig $entity */
    $entity = parent::buildEntity($form, $form_state);
    $new_definition = $this
      ->extractFormValues($form, $form_state);
    $entity->id = $new_definition['metadata']['entity_id'];
    $entity->parent = $new_definition['parent'];
    $entity->menu_name = $new_definition['menu_name'];
    $entity
      ->setStatus(!$new_definition['hidden']);
    $entity->expanded = $new_definition['expanded'];
    $entity->weight = $new_definition['weight'];
    $entity->url = $new_definition['url'];
    $entity->route_name = $new_definition['route_name'];
    $entity->route_parameters = $new_definition['route_parameters'];
    $entity->options = $new_definition['options'];
    return $entity;
  }

  /**
   * {@inheritdoc}
   */
  public function validate(array $form, FormStateInterface $form_state) {
    $this
      ->doValidate($form, $form_state);
    parent::validate($form, $form_state);
  }

  /**
   * Validates the form, both on the menu link edit and content menu link form.
   *
   * $form is not currently used, but passed here to match the normal form
   * validation method signature.
   *
   * @param array $form
   *   A nested array form elements comprising the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  protected function doValidate(array $form, FormStateInterface $form_state) {
    $extracted = $this
      ->extractUrl($form_state
      ->getValue('url'));

    // If both URL and route_name are empty, the entered value is not valid.
    $valid = FALSE;
    if ($extracted['url']) {

      // This is an external link.
      $valid = TRUE;
    }
    elseif ($extracted['route_name'] == '<nolink>') {

      // This is a nolink.
      $valid = TRUE;
    }
    elseif ($extracted['route_name']) {

      // Users are not allowed to add a link to a page they cannot access.
      $valid = $this->accessManager
        ->checkNamedRoute($extracted['route_name'], $extracted['route_parameters'], $this->account);
    }
    if (!$valid) {
      $form_state
        ->setErrorByName('url', $this
        ->t("The path '@link_path' is either invalid or you do not have access to it.", [
        '@link_path' => $form_state
          ->getValue('url'),
      ]));
    }
    elseif ($extracted['route_name']) {

      // The user entered a Drupal path.
      $normal_path = $this->pathAliasManager
        ->getPathByAlias($extracted['path']);
      if ($extracted['path'] != $normal_path) {
        $this
          ->messenger()
          ->addStatus($this
          ->t('The menu system stores system paths only, but will use the URL alias for display. %link_path has been stored as %normal_path', [
          '%link_path' => $extracted['path'],
          '%normal_path' => $normal_path,
        ]));
      }
    }
  }

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

    // The entity is rebuilt in parent::submit().
    $menu_link = $this->entity;
    $saved = $menu_link
      ->save();
    if ($saved) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('The menu link has been saved.'));
      $form_state
        ->setRedirect('entity.menu.edit_form', array(
        'menu' => $menu_link
          ->getMenuName(),
      ));
    }
    else {
      $this
        ->messenger()
        ->addStatus($this
        ->t('There was an error saving the menu link.'), 'error');
      $form_state['rebuild'] = TRUE;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $new_definition = $this
      ->extractFormValues($form, $form_state);
    return $this->menuLinkManager
      ->updateDefinition($this->entity
      ->getPluginId(), $new_definition);
  }

  /**
   * Breaks up a user-entered URL or path into all the relevant parts.
   *
   * @param string $url
   *   The user-entered URL or path.
   *
   * @return array
   *   The extracted parts.
   */
  protected function extractUrl($url) {
    $extracted = UrlHelper::parse($url);
    $external = UrlHelper::isExternal($url);
    if ($external) {
      $extracted['url'] = $extracted['path'];
      $extracted['route_name'] = NULL;
      $extracted['route_parameters'] = [];
    }
    else {
      $extracted['url'] = '';

      // If the path doesn't match a Drupal path, the route should end up empty.
      $extracted['route_name'] = NULL;
      $extracted['route_parameters'] = [];
      try {

        // Find the route_name.
        $url_obj = \Drupal::pathValidator()
          ->getUrlIfValid($extracted['path']);
        if ($url_obj) {
          $extracted['route_name'] = $url_obj
            ->getRouteName();
          $extracted['route_parameters'] = $url_obj
            ->getRouteParameters();
        }
      } catch (MatchingRouteNotFoundException $e) {

        // The path doesn't match a Drupal path.
      } catch (ParamNotConvertedException $e) {

        // A path like node/99 matched a route, but the route parameter was
        // invalid (e.g. node with ID 99 does not exist).
      }
      if ($url == 'route:<nolink>') {
        $extracted['route_name'] = '<nolink>';
      }
    }
    return $extracted;
  }

  /**
   * {@inheritdoc}
   */
  public function extractFormValues(array &$form, FormStateInterface $form_state) {
    $new_definition = [];
    $new_definition['title'] = $form_state
      ->getValue('title');
    $extracted = $this
      ->extractUrl($form_state
      ->getValue('url'));
    $new_definition['url'] = $extracted['url'];
    $new_definition['route_name'] = $extracted['route_name'];
    $new_definition['route_parameters'] = $extracted['route_parameters'];
    $new_definition['options'] = [];
    if ($extracted['query']) {
      $new_definition['options']['query'] = $extracted['query'];
    }
    if ($extracted['fragment']) {
      $new_definition['options']['fragment'] = $extracted['fragment'];
    }
    $new_definition['description'] = $form_state
      ->getValue('description');
    $new_definition['hidden'] = !$form_state
      ->getValue('enabled');
    $new_definition['weight'] = (int) $form_state
      ->getValue('weight');
    $new_definition['expanded'] = (bool) $form_state
      ->getValue('expanded');
    list($menu_name, $parent) = explode(':', $form_state
      ->getValue('menu_parent'), 2);
    if (!empty($menu_name)) {
      $new_definition['menu_name'] = $menu_name;
    }
    if (isset($parent)) {
      $new_definition['parent'] = $parent;
    }
    $new_definition['metadata']['entity_id'] = $form_state
      ->getValue('id');
    return $new_definition;
  }

}

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
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::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.
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.
MenuLinkConfigForm::$entity protected property The edited menu link. Overrides EntityForm::$entity
MenuLinkConfigForm::$entityManager protected property The entity manager.
MenuLinkConfigForm::$menuLinkManager protected property The menu link manager.
MenuLinkConfigForm::$menuParentSelector protected property The menu parent form selector.
MenuLinkConfigForm::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
MenuLinkConfigForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityForm::buildEntity
MenuLinkConfigForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
MenuLinkConfigForm::doValidate protected function Validates the form, both on the menu link edit and content menu link form.
MenuLinkConfigForm::extractFormValues public function Extracts a plugin definition from form values. Overrides MenuLinkFormInterface::extractFormValues
MenuLinkConfigForm::extractUrl protected function Breaks up a user-entered URL or path into all the relevant parts.
MenuLinkConfigForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
MenuLinkConfigForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
MenuLinkConfigForm::setMenuLinkInstance public function Injects the menu link plugin instance. Overrides MenuLinkFormInterface::setMenuLinkInstance
MenuLinkConfigForm::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
MenuLinkConfigForm::validate public function
MenuLinkConfigForm::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
MenuLinkConfigForm::__construct public function Constructs a new MenuLinkConfigForm object.
MessengerTrait::$messenger protected property The messenger. 29
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.