You are here

class BigMenuForm in Big Menu 8

Same name and namespace in other branches
  1. 2.x src/BigMenuForm.php \Drupal\bigmenu\BigMenuForm

Defines class for BigMenuForm.

Hierarchy

Expanded class hierarchy of BigMenuForm

1 file declares its use of BigMenuForm
bigmenu.module in ./bigmenu.module
Alternative to core menu management.

File

src/BigMenuForm.php, line 17

Namespace

Drupal\bigmenu
View source
class BigMenuForm extends MenuForm {

  /**
   * The menu tree.
   *
   * @var array
   */
  protected $tree = [];

  /**
   * The bigmenu configuration.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->config = $container
      ->get('config.factory')
      ->get('bigmenu.settings');
    return $instance;
  }

  /**
   * Overrides Drupal\menu_ui\MenuForm::buildOverviewForm() to limit the depth.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state object.
   *
   * @return array
   *   The form.
   */
  protected function buildOverviewForm(array &$form, FormStateInterface $form_state) {
    $menu_link = $this
      ->getRequest()->query
      ->get('menu_link');
    $form['#cache']['contexts'][] = 'url.query_args:menu_link';
    $max_depth = $this->config
      ->get('max_depth') ?: 1;
    return $this
      ->buildOverviewFormWithDepth($form, $form_state, $max_depth, $menu_link);
  }

  /**
   * Build a shallow version of the overview form.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state object.
   * @param int $depth
   *   The depth.
   * @param string $menu_link
   *   (Optional) The starting menu link id.
   *
   * @return array
   *   The form.
   */
  protected function buildOverviewFormWithDepth(array &$form, FormStateInterface $form_state, $depth = 1, $menu_link = NULL) {

    // Ensure that menu_overview_form_submit() knows the parents of this form
    // section.
    if (!$form_state
      ->has('menu_overview_form_parents')) {
      $form_state
        ->set('menu_overview_form_parents', []);
    }

    // Use Menu UI adminforms.
    $form['#attached']['library'][] = 'menu_ui/drupal.menu_ui.adminforms';

    // Add a link to go back to the full menu.
    if ($menu_link) {

      /** @var \Drupal\Core\Menu\MenuLinkInterface $parent */
      $breadcrumbs = [];
      $parent = $this->menuLinkManager
        ->createInstance($menu_link);
      while ($parent_id = $parent
        ->getParent()) {
        $parent = $this->menuLinkManager
          ->createInstance($parent_id);
        $breadcrumbs[] = new Link($parent
          ->getTitle(), $this->entity
          ->toUrl('edit-form')
          ->setOption('query', [
          'menu_link' => $parent_id,
        ]));
      }
      $breadcrumbs[] = $this->entity
        ->toLink($this
        ->t('Back to @label top level', [
        '@label' => $this->entity
          ->label(),
      ]), 'edit-form');
      $form['breadcrumb'] = [
        '#theme' => 'breadcrumb',
        '#links' => array_reverse($breadcrumbs),
      ];
    }
    $form['links'] = [
      '#type' => 'table',
      '#theme' => 'table__menu_overview',
      '#header' => [
        $this
          ->t('Menu link'),
        $this
          ->t('Edit children'),
        [
          'data' => $this
            ->t('Enabled'),
          'class' => [
            'checkbox',
          ],
        ],
        $this
          ->t('Weight'),
        [
          'data' => $this
            ->t('Operations'),
          'colspan' => 3,
        ],
      ],
      '#attributes' => [
        'id' => 'menu-overview',
      ],
      '#tabledrag' => [
        [
          'action' => 'match',
          'relationship' => 'parent',
          'group' => 'menu-parent',
          'subgroup' => 'menu-parent',
          'source' => 'menu-id',
          'hidden' => TRUE,
          'limit' => $this->menuTree
            ->maxDepth() - 1,
        ],
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'menu-weight',
        ],
      ],
    ];

    // No Links available (Empty menu)
    $form['links']['#empty'] = $this
      ->t('There are no menu links yet. <a href=":url">Add link</a>.', [
      ':url' => $this->entity
        ->toUrl('add-link-form', [
        'query' => [
          'destination' => $this->entity
            ->toUrl('edit-form')
            ->toString(),
        ],
      ])
        ->toString(),
    ]);

    // Get the menu tree if it's not in our property.
    if (empty($this->tree)) {
      $this->tree = $this
        ->getTree($depth, $menu_link);
    }

    // Determine the delta; the number of weights to be made available.
    $count = function (array $tree) {
      $sum = function ($carry, MenuLinkTreeElement $item) {
        return $carry + $item
          ->count();
      };
      return array_reduce($tree, $sum);
    };

    // Tree maximum or 50.
    $delta = max($count($this->tree), 50);
    $links = $this
      ->buildOverviewTreeForm($this->tree, $delta);
    $this
      ->processLinks($form, $links, $menu_link);
    return $form;
  }

  /**
   * Format the links appropriately so draggable views will work.
   *
   * @param array $form
   *   The form array.
   * @param array $links
   *   An array of links.
   * @param string $menu_link
   *   A menu link plugin id.
   */
  public function processLinks(array &$form, array &$links, $menu_link) {
    foreach (Element::children($links) as $id) {
      if (isset($links[$id]['#item'])) {
        $element = $links[$id];
        $form['links'][$id]['#item'] = $element['#item'];

        // TableDrag: Mark the table row as draggable.
        $form['links'][$id]['#attributes'] = $element['#attributes'];
        $form['links'][$id]['#attributes']['class'][] = 'draggable';

        // TableDrag: Sort the table row according to its existing/configured
        // weight.
        $form['links'][$id]['#weight'] = $element['#item']->link
          ->getWeight();

        // Add special classes to be used for tabledrag.js.
        $element['parent']['#attributes']['class'] = [
          'menu-parent',
        ];
        $element['weight']['#attributes']['class'] = [
          'menu-weight',
        ];
        $element['id']['#attributes']['class'] = [
          'menu-id',
        ];
        $form['links'][$id]['title'] = [
          [
            '#theme' => 'indentation',
            '#size' => $element['#item']->depth - 1,
          ],
          $element['title'],
        ];
        $form['links'][$id]['root'][] = [];

        // The hasChildren property only checks enabled children. The link
        // to edit children should be available when all children are not
        // enabled, so perform an additional check when necessary.
        // @see https://www.drupal.org/node/2302149
        if ($form['links'][$id]['#item']->hasChildren || $this
          ->hasAnyChildren($links[$id]['#item'])) {
          if (is_null($menu_link) || isset($menu_link) && $menu_link != $element['#item']->link
            ->getPluginId()) {
            $uri = $this->entity
              ->toUrl('edit-form', [
              'query' => [
                'menu_link' => $element['#item']->link
                  ->getPluginId(),
              ],
            ]);
            $form['links'][$id]['root'][] = [
              '#type' => 'link',
              '#title' => $this
                ->t('Edit child items'),
              '#url' => $uri,
            ];
          }
        }
        $form['links'][$id]['enabled'] = $element['enabled'];
        $form['links'][$id]['enabled']['#wrapper_attributes']['class'] = [
          'checkbox',
          'menu-enabled',
        ];
        $form['links'][$id]['weight'] = $element['weight'];

        // Operations (dropbutton) column.
        $form['links'][$id]['operations'] = $element['operations'];
        $form['links'][$id]['id'] = $element['id'];
        $form['links'][$id]['parent'] = $element['parent'];
      }
    }
  }

  /**
   * Gets the menu tree.
   *
   * @param int $depth
   *   The depth.
   * @param string $root
   *   An optional root menu link plugin id.
   *
   * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
   *   An array of menu link tree elements.
   */
  protected function getTree($depth, $root = NULL) {
    $tree_params = new MenuTreeParameters();
    $tree_params
      ->setMaxDepth($depth);
    if ($root) {
      $tree_params
        ->setRoot($root);
    }
    $tree = $this->menuTree
      ->load($this->entity
      ->id(), $tree_params);

    // We indicate that a menu administrator is running the menu access check.
    $this
      ->getRequest()->attributes
      ->set('_menu_admin', TRUE);
    $manipulators = [
      [
        'callable' => 'menu.default_tree_manipulators:checkAccess',
      ],
      [
        'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
      ],
    ];
    $tree = $this->menuTree
      ->transform($tree, $manipulators);
    $this
      ->getRequest()->attributes
      ->set('_menu_admin', FALSE);
    return $tree;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    parent::save($form, $form_state);
    $form_state
      ->setRedirectUrl(Url::fromUserInput($this
      ->getRedirectDestination()
      ->get()));
  }

  /**
   * Checks if a MenuLinkTreeElement has any children, enabled or disabled.
   *
   * @param \Drupal\Core\Menu\MenuLinkTreeElement $element
   *   The parent element.
   *
   * @return bool
   *   TRUE if a MenuLinkTreeElement has any children, otherwise FALSE.
   */
  protected function hasAnyChildren(MenuLinkTreeElement $element) {
    $depth = $element->depth + 1;
    $tree_params = new MenuTreeParameters();
    $tree_params
      ->setMinDepth($depth);
    $tree_params
      ->setMaxDepth($depth);
    $tree_params
      ->addExpandedParents([
      $element->link
        ->getPluginId(),
    ]);
    $tree = $this->menuTree
      ->load($this->entity
      ->id(), $tree_params);
    return !empty($tree);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BigMenuForm::$config protected property The bigmenu configuration.
BigMenuForm::$tree protected property The menu tree.
BigMenuForm::buildOverviewForm protected function Overrides Drupal\menu_ui\MenuForm::buildOverviewForm() to limit the depth. Overrides MenuForm::buildOverviewForm
BigMenuForm::buildOverviewFormWithDepth protected function Build a shallow version of the overview form.
BigMenuForm::create public static function Instantiates a new instance of this class. Overrides MenuForm::create
BigMenuForm::getTree protected function Gets the menu tree.
BigMenuForm::hasAnyChildren protected function Checks if a MenuLinkTreeElement has any children, enabled or disabled.
BigMenuForm::processLinks public function Format the links appropriately so draggable views will work.
BigMenuForm::save public function Form submission handler for the 'save' action. Overrides MenuForm::save
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::$entity protected property The entity being used by this form. 7
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::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
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::__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::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.
MenuForm::$linkGenerator protected property The link generator. Overrides LinkGeneratorTrait::$linkGenerator
MenuForm::$menuLinkContentStorage protected property The menu_link_content storage handler.
MenuForm::$menuLinkManager protected property The menu link manager.
MenuForm::$menuTree protected property The menu tree service.
MenuForm::$overviewTreeForm protected property The overview tree form.
MenuForm::buildOverviewTreeForm protected function Recursive helper function for buildOverviewForm().
MenuForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
MenuForm::menuNameExists public function Returns whether a menu name already exists.
MenuForm::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 EntityForm::submitForm
MenuForm::submitOverviewForm protected function Submit handler for the menu overview form.
MenuForm::__construct public function Constructs a MenuForm 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.