MenuLinkFormController.php 11 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\menu_link\MenuLinkFormController.
 */

namespace Drupal\menu_link;

10
use Drupal\Core\Entity\EntityControllerInterface;
11
use Drupal\Core\Entity\EntityFormController;
12
use Drupal\Core\Language\Language;
13
use Drupal\Core\Extension\ModuleHandlerInterface;
14
use Drupal\Core\Path\AliasManagerInterface;
15 16
use Drupal\Core\Routing\UrlGenerator;
use Drupal\menu_link\MenuLinkStorageControllerInterface;
17
use Symfony\Component\DependencyInjection\ContainerInterface;
18 19 20 21

/**
 * Form controller for the node edit forms.
 */
22 23
class MenuLinkFormController extends EntityFormController implements EntityControllerInterface {

24 25 26 27 28 29 30
  /**
   * The menu link storage controller.
   *
   * @var \Drupal\menu_link\MenuLinkStorageControllerInterface
   */
  protected $menuLinkStorageController;

31 32 33 34 35 36 37
  /**
   * The path alias manager.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected $pathAliasManager;

38 39 40 41 42 43 44
  /**
   * The URL generator.
   *
   * @var \Drupal\Core\Routing\UrlGenerator
   */
  protected $urlGenerator;

45 46 47
  /**
   * Constructs a new MenuLinkFormController object.
   *
48 49
   * @param \Drupal\Core\Extension\ModuleHandlerInterface
   *   The module handler service.
50 51 52
   * @param \Drupal\Core\Path\AliasManagerInterface $path_alias_manager
   *   The path alias manager.
   */
53 54
  public function __construct(ModuleHandlerInterface $module_handler, MenuLinkStorageControllerInterface $menu_link_storage_controller, AliasManagerInterface $path_alias_manager, UrlGenerator $url_generator) {
    parent::__construct($module_handler);
55
    $this->menuLinkStorageController = $menu_link_storage_controller;
56
    $this->pathAliasManager = $path_alias_manager;
57
    $this->urlGenerator = $url_generator;
58 59 60 61 62
  }

  /**
   * {@inheritdoc}
   */
63
  public static function createInstance(ContainerInterface $container, $entity_type, array $entity_info, $operation = NULL) {
64
    return new static(
65
      $container->get('module_handler'),
66 67
      $container->get('plugin.manager.entity')->getStorageController('menu_link'),
      $container->get('path.alias_manager.cached'),
68
      $container->get('url_generator')
69 70
    );
  }
71 72 73 74

  /**
   * Overrides EntityFormController::form().
   */
75 76
  public function form(array $form, array &$form_state) {
    $menu_link = $this->entity;
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    // Since menu_link_load() no longer returns a translated and access checked
    // item, do it here instead.
    _menu_link_translate($menu_link);

    if (!$menu_link->isNew()) {
      // Get the human-readable menu title from the given menu name.
      $titles = menu_get_menus();
      $current_title = $titles[$menu_link->menu_name];

      // Get the current breadcrumb and add a link to that menu's overview page.
      $breadcrumb = menu_get_active_breadcrumb();
      $breadcrumb[] = l($current_title, 'admin/structure/menu/manage/' . $menu_link->menu_name);
      drupal_set_breadcrumb($breadcrumb);
    }

    $form['link_title'] = array(
      '#type' => 'textfield',
      '#title' => t('Menu link title'),
      '#default_value' => $menu_link->link_title,
      '#description' => t('The text to be used for this link in the menu.'),
      '#required' => TRUE,
    );
    foreach (array('link_path', 'mlid', 'module', 'has_children', 'options') as $key) {
      $form[$key] = array('#type' => 'value', '#value' => $menu_link->{$key});
    }
    // Any item created or edited via this interface is considered "customized".
    $form['customized'] = array('#type' => 'value', '#value' => 1);

    // We are not using url() when constructing this path because it would add
    // $base_path.
    $path = $menu_link->link_path;
    if (isset($menu_link->options['query'])) {
109
      $path .= '?' . $this->urlGenerator->httpBuildQuery($menu_link->options['query']);
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    }
    if (isset($menu_link->options['fragment'])) {
      $path .= '#' . $menu_link->options['fragment'];
    }
    if ($menu_link->module == 'menu') {
      $form['link_path'] = array(
        '#type' => 'textfield',
        '#title' => t('Path'),
        '#maxlength' => 255,
        '#default_value' => $path,
        '#description' => 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.', array('%front' => '<front>', '%add-node' => 'node/add', '%drupal' => 'http://drupal.org')),
        '#required' => TRUE,
      );
    }
    else {
      $form['_path'] = array(
        '#type' => 'item',
        '#title' => t('Path'),
        '#description' => l($menu_link->link_title, $menu_link->href, $menu_link->options),
      );
    }

    $form['description'] = array(
      '#type' => 'textarea',
      '#title' => t('Description'),
      '#default_value' => isset($menu_link->options['attributes']['title']) ? $menu_link->options['attributes']['title'] : '',
      '#rows' => 1,
      '#description' => t('Shown when hovering over the menu link.'),
    );
    $form['enabled'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enabled'),
      '#default_value' => !$menu_link->hidden,
      '#description' => t('Menu links that are not enabled will not be listed in any menu.'),
    );
    $form['expanded'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show as expanded'),
      '#default_value' => $menu_link->expanded,
      '#description' => t('If selected and this menu link has children, the menu will always appear expanded.'),
    );

    // Generate a list of possible parents (not including this link or descendants).
    $options = menu_parent_options(menu_get_menus(), $menu_link);
    $default = $menu_link->menu_name . ':' . $menu_link->plid;
    if (!isset($options[$default])) {
      $default = 'tools:0';
    }
    $form['parent'] = array(
      '#type' => 'select',
      '#title' => t('Parent link'),
      '#default_value' => $default,
      '#options' => $options,
      '#description' => t('The maximum depth for a link and all its children is fixed at !maxdepth. Some menu links may not be available as parents if selecting them would exceed this limit.', array('!maxdepth' => MENU_MAX_DEPTH)),
      '#attributes' => array('class' => array('menu-title-select')),
    );

    // Get number of items in menu so the weight selector is sized appropriately.
168
    $delta = $this->menuLinkStorageController->countMenuLinks($menu_link->menu_name);
169 170 171 172 173 174 175 176 177
    $form['weight'] = array(
      '#type' => 'weight',
      '#title' => t('Weight'),
      // Old hardcoded value.
      '#delta' => max($delta, 50),
      '#default_value' => $menu_link->weight,
      '#description' => t('Optional. In the menu, the heavier links will sink and the lighter links will be positioned nearer the top.'),
    );

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    // Language module allows to configure the menu link language independently
    // of the menu language. It also allows to optionally show the language
    // selector on the menu link form so that the language of each menu link can
    // be configured individually.
    if ($this->moduleHandler->moduleExists('language')) {
      $language_configuration = language_get_default_configuration('menu_link', $menu_link->bundle());
      $default_langcode = ($menu_link->isNew() ? $language_configuration['langcode'] : $menu_link->langcode);
      $language_show = $language_configuration['language_show'];
    }
    // Without Language module menu links inherit the menu language and no
    // language selector is shown.
    else {
      $default_langcode = ($menu_link->isNew() ? entity_load('menu', $menu_link->menu_name)->langcode : $menu_link->langcode);
      $language_show = FALSE;
    }

194 195 196
    $form['langcode'] = array(
      '#type' => 'language_select',
      '#title' => t('Language'),
197
      '#languages' => Language::STATE_ALL,
198 199
      '#default_value' => $default_langcode,
      '#access' => $language_show,
200 201 202 203 204 205 206 207 208 209 210
    );

    return parent::form($form, $form_state, $menu_link);
  }

  /**
   * Overrides EntityFormController::actions().
   */
  protected function actions(array $form, array &$form_state) {
    $element = parent::actions($form, $form_state);
    $element['submit']['#button_type'] = 'primary';
211
    $element['delete']['#access'] = $this->entity->module == 'menu';
212 213 214 215 216 217 218 219 220 221

    return $element;
  }

  /**
   * Overrides EntityFormController::validate().
   */
  public function validate(array $form, array &$form_state) {
    $menu_link = $this->buildEntity($form, $form_state);

222
    $normal_path = $this->pathAliasManager->getSystemPath($menu_link->link_path);
223 224 225 226 227 228 229
    if ($menu_link->link_path != $normal_path) {
      drupal_set_message(t('The menu system stores system paths only, but will use the URL alias for display. %link_path has been stored as %normal_path', array('%link_path' => $menu_link->link_path, '%normal_path' => $normal_path)));
      $menu_link->link_path = $normal_path;
    }
    if (!url_is_external($menu_link->link_path)) {
      $parsed_link = parse_url($menu_link->link_path);
      if (isset($parsed_link['query'])) {
230 231
        $menu_link->options['query'] = array();
        parse_str($parsed_link['query'], $menu_link->options['query']);
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
      }
      else {
        // Use unset() rather than setting to empty string
        // to avoid redundant serialized data being stored.
        unset($menu_link->options['query']);
      }
      if (isset($parsed_link['fragment'])) {
        $menu_link->options['fragment'] = $parsed_link['fragment'];
      }
      else {
        unset($menu_link->options['fragment']);
      }
      if (isset($parsed_link['path']) && $menu_link->link_path != $parsed_link['path']) {
        $menu_link->link_path = $parsed_link['path'];
      }
    }
    if (!trim($menu_link->link_path) || !drupal_valid_path($menu_link->link_path, TRUE)) {
      form_set_error('link_path', t("The path '@link_path' is either invalid or you do not have access to it.", array('@link_path' => $menu_link->link_path)));
    }

    parent::validate($form, $form_state);
  }

  /**
   * Overrides EntityFormController::submit().
   */
  public function submit(array $form, array &$form_state) {
    // Build the menu link object from the submitted values.
    $menu_link = parent::submit($form, $form_state);

    // The value of "hidden" is the opposite of the value supplied by the
    // "enabled" checkbox.
    $menu_link->hidden = (int) !$menu_link->enabled;
    unset($menu_link->enabled);

    $menu_link->options['attributes']['title'] = $menu_link->description;
    list($menu_link->menu_name, $menu_link->plid) = explode(':', $menu_link->parent);

    return $menu_link;
  }

  /**
   * Overrides EntityFormController::save().
   */
  public function save(array $form, array &$form_state) {
277
    $menu_link = $this->entity;
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

    $saved = $menu_link->save();

    if ($saved) {
      drupal_set_message(t('The menu link has been saved.'));
      $form_state['redirect'] = 'admin/structure/menu/manage/' . $menu_link->menu_name;
    }
    else {
      drupal_set_message(t('There was an error saving the menu link.'), 'error');
      $form_state['rebuild'] = TRUE;
    }
  }

  /**
   * Overrides EntityFormController::delete().
   */
  public function delete(array $form, array &$form_state) {
295
    $menu_link = $this->entity;
296 297 298
    $form_state['redirect'] = 'admin/structure/menu/item/' . $menu_link->id() . '/delete';
  }
}