You are here

public function CshsMenuParentFormSelector::parentSelectElement in Menu Link Weight 8

Same name and namespace in other branches
  1. 8.2 src/MenuParentFormSelector/CshsMenuParentFormSelector.php \Drupal\menu_link_weight\MenuParentFormSelector\CshsMenuParentFormSelector::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 MenuParentFormSelector::parentSelectElement

File

src/MenuParentFormSelector/CshsMenuParentFormSelector.php, line 50

Class

CshsMenuParentFormSelector
Implements Client-side hierarchical select (CSHS) as the menu parent form selector.

Namespace

Drupal\menu_link_weight\MenuParentFormSelector

Code

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

  // If no options were found, there is nothing to select.
  if ($options) {
    $element = [
      '#type' => 'cshs',
      '#options' => $options,
      '#attached' => [
        'library' => [
          'menu_link_weight/menu_parent_selector.cshs',
        ],
      ],
    ];
    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 [];
}