You are here

public function MenuParentFormSelector::parentSelectElement in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Menu/MenuParentFormSelector.php \Drupal\Core\Menu\MenuParentFormSelector::parentSelectElement()

Gets a form element to choose a menu and parent.

The specific type of form element will vary depending on the implementation, but callers will normally need to set the #title for the element.

Parameters

string $menu_parent: A menu name and parent ID concatenated with a ':' character to use as the default value.

string $id: (optional) ID of a link plugin. This will exclude the link and its children from being selected.

array $menus: (optional) Array of menu names as keys and titles as values to limit the values that may be selected. If NULL, all menus will be included.

Return value

array A form element to choose a parent, or an empty array if no possible parents exist for the given parameters. The resulting form value will be a single string containing the chosen menu name and parent ID separated by a ':' character.

Overrides MenuParentFormSelectorInterface::parentSelectElement

File

core/lib/Drupal/Core/Menu/MenuParentFormSelector.php, line 79

Class

MenuParentFormSelector
Default implementation of the menu parent form selector service.

Namespace

Drupal\Core\Menu

Code

public function parentSelectElement($menu_parent, $id = '', array $menus = NULL) {
  $options_cacheability = new CacheableMetadata();
  $options = $this
    ->getParentSelectOptions($id, $menus, $options_cacheability);

  // If no options were found, there is nothing to select.
  if ($options) {
    $element = [
      '#type' => 'select',
      '#options' => $options,
    ];
    if (!isset($options[$menu_parent])) {

      // The requested menu parent cannot be found in the menu anymore. Try
      // setting it to the top level in the current menu.
      list($menu_name, $parent) = explode(':', $menu_parent, 2);
      $menu_parent = $menu_name . ':';
    }
    if (isset($options[$menu_parent])) {

      // Only provide the default value if it is valid among the options.
      $element += [
        '#default_value' => $menu_parent,
      ];
    }
    $options_cacheability
      ->applyTo($element);
    return $element;
  }
  return [];
}