You are here

class MenuItemExtrasViewModesSettingsForm in Menu Item Extras 8.2

Base form for menu view modes settings edit forms.

Hierarchy

Expanded class hierarchy of MenuItemExtrasViewModesSettingsForm

File

src/MenuItemExtrasViewModesSettingsForm.php, line 23

Namespace

Drupal\menu_item_extras
View source
class MenuItemExtrasViewModesSettingsForm extends EntityForm {

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

  /**
   * The menu tree service.
   *
   * @var \Drupal\Core\Menu\MenuLinkTreeInterface
   */
  protected $menuTree;

  /**
   * The link generator.
   *
   * @var \Drupal\Core\Utility\LinkGeneratorInterface
   */
  protected $linkGenerator;

  /**
   * The custom menu link tree service.
   *
   * @var \Drupal\menu_item_extras\Service\MenuLinkTreeHandlerInterface
   */
  protected $menuLinkTreeHandler;

  /**
   * The entity display repository.
   *
   * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
   */
  private $entityDisplayRepository;

  /**
   * The overview tree form.
   *
   * @var array
   */
  protected $overviewTreeForm = [
    '#tree' => TRUE,
  ];

  /**
   * Constructs a MenuForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Menu\MenuLinkTreeInterface $menu_tree
   *   The menu tree service.
   * @param \Drupal\Core\Utility\LinkGeneratorInterface $link_generator
   *   The link generator.
   * @param \Drupal\menu_item_extras\Service\MenuLinkTreeHandlerInterface $menu_link_tree_handler
   *   The custom menu link tree service.
   * @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entityDisplayRepository
   *   The entity display repository.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, MenuLinkTreeInterface $menu_tree, LinkGeneratorInterface $link_generator, MenuLinkTreeHandlerInterface $menu_link_tree_handler, EntityDisplayRepositoryInterface $entityDisplayRepository) {
    $this->entityTypeManager = $entity_type_manager;
    $this->menuTree = $menu_tree;
    $this->linkGenerator = $link_generator;
    $this->menuLinkTreeHandler = $menu_link_tree_handler;
    $this->entityDisplayRepository = $entityDisplayRepository;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('menu.link_tree'), $container
      ->get('link_generator'), $container
      ->get('menu_item_extras.menu_link_tree_handler'), $container
      ->get('entity_display.repository'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);

    // Hides delete action as we don't need it.
    if (!empty($form['actions']['delete'])) {
      $form['actions']['delete']['#access'] = FALSE;
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form_state
      ->set('menu_overview_form_parents', [
      'links',
    ]);
    $form['links'] = $this
      ->buildOverviewForm($form, $form_state);
    return parent::form($form, $form_state);
  }

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

    /** @var \Drupal\system\MenuInterface $menu */
    $menu = $this->entity;
    $status = $menu
      ->save();
    if ($status == SAVED_UPDATED) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('Menu %label has been updated.', [
        '%label' => $menu
          ->label(),
      ]));
      $this
        ->logger('menu')
        ->notice('Menu %label has been updated.', [
        '%label' => $menu
          ->label(),
      ]);
    }
    $form_state
      ->setRedirectUrl($this->entity
      ->toUrl('view-modes-settings'));
  }

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

  /**
   * Form constructor to edit an entire menu tree at once.
   *
   * Shows for one menu the menu links accessible to the current user and
   * relevant operations.
   *
   * This form constructor can be integrated as a section into another form. It
   * relies on the following keys in $form_state:
   * - menu: A menu entity.
   * - menu_overview_form_parents: An array containing the parent keys to this
   *   form.
   * Forms integrating this section should call menu_overview_form_submit() from
   * their form submit handler.
   */
  protected function buildOverviewForm(array &$form, FormStateInterface $form_state) {
    if (!$form_state
      ->has('menu_overview_form_parents')) {
      $form_state
        ->set('menu_overview_form_parents', []);
    }
    $tree = $this->menuTree
      ->load($this->entity
      ->id(), new MenuTreeParameters());
    $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);
    $count = function (array $tree) {
      $sum = function ($carry, MenuLinkTreeElement $item) {
        return $carry + $item
          ->count();
      };
      return array_reduce($tree, $sum);
    };
    $delta = max($count($tree), 50);
    $form['links'] = [
      '#type' => 'table',
      '#theme' => 'table__menu_overview',
      '#header' => [
        $this
          ->t('Menu link'),
        [
          'data' => $this
            ->t('View Mode'),
          'colspan' => 3,
        ],
      ],
      '#attributes' => [
        'entity_id' => 'menu-overview',
      ],
    ];
    $links = $this
      ->buildOverviewTreeForm($tree, $delta);
    foreach (Element::children($links) as $entity_id) {
      if (isset($links[$entity_id]['#item'])) {
        $element = $links[$entity_id];
        $form['links'][$entity_id]['#item'] = $element['#item'];
        $element['parent']['#attributes']['class'][] = 'menu-parent';
        $element['entity_id']['#attributes']['class'][] = 'menu-id';
        $form['links'][$entity_id]['title'] = [
          [
            '#theme' => 'indentation',
            '#size' => $element['#item']->depth - 1,
          ],
          $element['title'],
        ];
        $form['links'][$entity_id]['view_mode'] = $element['view_mode'];
        $form['links'][$entity_id]['entity_id'] = $element['entity_id'];
        $form['links'][$entity_id]['parent'] = $element['parent'];
      }
    }
    return $form;
  }

  /**
   * Recursive helper function for buildOverviewForm().
   *
   * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
   *   The tree retrieved by \Drupal\Core\Menu\MenuLinkTreeInterface::load().
   * @param int $delta
   *   The default number of menu items used in the menu weight selector is 50.
   *
   * @return array
   *   The overview tree form.
   */
  protected function buildOverviewTreeForm(array $tree, $delta) {
    $form =& $this->overviewTreeForm;
    $tree_access_cacheability = new CacheableMetadata();
    foreach ($tree as $element) {
      $tree_access_cacheability = $tree_access_cacheability
        ->merge(CacheableMetadata::createFromObject($element->access));

      // Only render accessible links.
      if (!$element->access
        ->isAllowed()) {
        continue;
      }

      /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
      $link = $element->link;
      $metadata = $link
        ->getMetaData();
      if ($link && !empty($metadata['entity_id'])) {
        $entity_id = $metadata['entity_id'];
        $form[$entity_id]['#item'] = $element;
        $form[$entity_id]['#attributes'] = $link
          ->isEnabled() ? [
          'class' => [
            'menu-enabled',
          ],
        ] : [
          'class' => [
            'menu-disabled',
          ],
        ];
        $form[$entity_id]['title'] = Link::fromTextAndUrl($link
          ->getTitle(), $link
          ->getUrlObject())
          ->toRenderable();
        $form[$entity_id]['entity_id'] = [
          '#type' => 'hidden',
          '#value' => $entity_id,
        ];
        $form[$entity_id]['parent'] = [
          '#type' => 'hidden',
          '#default_value' => $link
            ->getParent(),
        ];
        $options = $this->entityDisplayRepository
          ->getViewModeOptionsByBundle('menu_link_content', $this->entity
          ->id());
        if (empty($options)) {
          $options['default'] = $this
            ->t('Default');
        }
        $form[$entity_id]['view_mode'] = [
          '#type' => 'select',
          '#options' => $options,
          '#default_value' => $this->menuLinkTreeHandler
            ->getMenuLinkItemViewMode($link),
        ];
      }
      if ($element->subtree) {
        $this
          ->buildOverviewTreeForm($element->subtree, $delta);
      }
    }
    $tree_access_cacheability
      ->merge(CacheableMetadata::createFromRenderArray($form))
      ->applyTo($form);
    return $form;
  }

  /**
   * Submit handler for the menu edit view modes form.
   */
  protected function submitOverviewForm(array $complete_form, FormStateInterface $form_state) {
    $parents = $form_state
      ->get('menu_overview_form_parents');
    $input = NestedArray::getValue($form_state
      ->getUserInput(), $parents);
    $form =& NestedArray::getValue($complete_form, $parents);
    $order = is_array($input) ? array_flip(array_keys($input)) : [];
    $form = array_intersect_key(array_merge($order, $form), $form);
    $fields = [
      'view_mode',
    ];
    $form_links = $form['links'];

    // Handles saving of updated values.
    foreach (Element::children($form_links) as $entity_id) {
      if (isset($form_links[$entity_id]['#item'])) {
        $element = $form_links[$entity_id];
        foreach ($fields as $field) {
          if ($element[$field]['#value'] != $element[$field]['#default_value']) {
            $menu_item = $this->entityTypeManager
              ->getStorage('menu_link_content')
              ->load($entity_id);
            $menu_item
              ->set('view_mode', $element[$field]['#value'])
              ->save();
          }
        }
      }
    }
  }

}

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::$entity protected property The entity being used by this form. 7
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::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.
MenuItemExtrasViewModesSettingsForm::$entityDisplayRepository private property The entity display repository.
MenuItemExtrasViewModesSettingsForm::$entityTypeManager protected property The entity type manager. Overrides EntityForm::$entityTypeManager
MenuItemExtrasViewModesSettingsForm::$linkGenerator protected property The link generator. Overrides LinkGeneratorTrait::$linkGenerator
MenuItemExtrasViewModesSettingsForm::$menuLinkTreeHandler protected property The custom menu link tree service.
MenuItemExtrasViewModesSettingsForm::$menuTree protected property The menu tree service.
MenuItemExtrasViewModesSettingsForm::$overviewTreeForm protected property The overview tree form.
MenuItemExtrasViewModesSettingsForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
MenuItemExtrasViewModesSettingsForm::buildOverviewForm protected function Form constructor to edit an entire menu tree at once.
MenuItemExtrasViewModesSettingsForm::buildOverviewTreeForm protected function Recursive helper function for buildOverviewForm().
MenuItemExtrasViewModesSettingsForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
MenuItemExtrasViewModesSettingsForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
MenuItemExtrasViewModesSettingsForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
MenuItemExtrasViewModesSettingsForm::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
MenuItemExtrasViewModesSettingsForm::submitOverviewForm protected function Submit handler for the menu edit view modes form.
MenuItemExtrasViewModesSettingsForm::__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.