menu_item_fields-8.x-1.5/src/Hook/MenuNameFormMode.php

src/Hook/MenuNameFormMode.php
<?php

namespace Drupal\menu_item_fields\Hook;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\menu_link_content\MenuLinkContentInterface;
use Drupal\system\MenuInterface;

/**
 * Switch form mode based on the menu name.
 */
#[Hook('entity_form_mode_alter')]
class MenuNameFormMode {

  /**
   * Build a MenuNameFormMode handler.
   */
  public function __construct(
    protected RouteMatchInterface $routeMatch,
    protected ConfigFactoryInterface $config,
  ) {
  }

  /**
   * Implements hook_entity_form_mode_alter().
   *
   * When there is a form mode that matches the menu
   * use that one instead of default.
   *
   * @param string $form_mode
   *   The form_mode that is to be used to build the entity form.
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity for which the form is being built.
   */
  public function __invoke(&$form_mode, EntityInterface $entity): void {
    if (!$entity instanceof MenuLinkContentInterface) {
      return;
    }

    $menuId = NULL;
    if ($entity->isNew()) {
      $menu = $this->routeMatch->getParameter('menu');
      if (!$menu instanceof MenuInterface) {
        return;
      }
      /** @var \Drupal\system\MenuInterface $menu */
      $menuId = $menu->id();
    }
    else {
      $menuId = $entity->get('menu_name')->getString();
    }

    $underscoreId = str_replace(search: '-', replace: '_', subject: $menuId);
    // When the form mode is enabled swap the current form mode.
    if ($this->config->get('core.entity_form_display.menu_link_content.menu_link_content.' . $underscoreId)->get('status')) {
      $form_mode = $underscoreId;
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc