Як створити власні вкладки користувачів?


9

Я намагаюся створити нову власну вкладку, яка з’явиться на всіх маршрутах, які є нащадками сутності. {Entit_type} .canonical. Я спробував розширити клас DeriverBase, конкретно перекривши метод getDerivativeDefinitions. Я створив саму вкладку, розширивши LocalTaskDefault і замінивши метод getRouteParameters. Вкладка з’являється, коли ви відвідуєте стандартний шлях користувача Drupal, такий як www.mysite.com/user/1/ або www.mysite.com/user/1/edit. Однак, коли ми додаємо наші нові користувацькі маршрути, такі як www.mysite.com/user/1/subscribe, вкладки не з’являються. Чи існує спеціальний спосіб визначення завдань місцевого меню на користувальницьких маршрутах? Зразок коду:

 $this->derivatives['recurly.subscription_tab'] = [
  'title' => $this->t('Subscription'),
  'weight' => 5,
  'route_name' => 'recurly.subscription_list',
  'base_route' => "entity.$entity_type.canonical",
];

foreach ($this->derivatives as &$entry) {
  $entry += $base_plugin_definition;
}

Заздалегідь дякую за будь-яку допомогу.


Звучить дуже близько до того, що Devel робить з маршрутом / devel route / local task, я пропоную вам поглянути на те, як це реалізувати.
Бердір

@Berdir, що було відправною точкою, але я все ще, здається, чогось не вистачає.
tflanagan

Ви намагалися додати файл "yourmodule.links.task.yml" із налаштуваннями для власної вкладки?
Андрій

Відповіді:


7

Як запропонував Бердір, ви можете подивитися на модуль Devel та на те, як це реалізувати. Наступний код був "вилучений" з Devel

1) Створіть маршрути

Створіть файл mymodule.routing.yml всередині та визначте зворотний виклик маршруту (який використовується для створення динамічних маршрутів)

route_callbacks:
  - '\Drupal\mymodule\Routing\MyModuleRoutes::routes'

Створіть клас MyModuleRoutes для генерації ваших динамічних маршрутів у src / Routing

<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class MyModuleRoutes implements ContainerInjectionInterface {

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  public function routes() {
    $collection = new RouteCollection();

    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
      if ($entity_type->hasLinkTemplate('canonical')) {
        $route = new Route("/mymodule/$entity_type_id/{{$entity_type_id}}");
        $route
          ->addDefaults([
            '_controller' => '\Drupal\mymodule\Controller\MyModuleController::doStuff',
            '_title' => 'My module route title',
          ])
          ->addRequirements([
            '_permission' => 'access mymodule permission',
          ])
          ->setOption('_mymodule_entity_type_id', $entity_type_id)
          ->setOption('parameters', [
            $entity_type_id => ['type' => 'entity:' . $entity_type_id],
          ]);

        $collection->add("entity.$entity_type_id.mymodule", $route);
      }
    }

    return $collection;
  }

}

2) Створіть динамічні локальні завдання

Створіть файл mymodule.links.task.yml і всередині визначте дериватор

mymodule.tasks:
  class: \Drupal\Core\Menu\LocalTaskDefault
  deriver: \Drupal\mymodule\Plugin\Derivative\MyModuleLocalTasks

Створіть клас MyModuleLocalTasks для створення ваших динамічних маршрутів у src / Plugin / Derivative

<?php

namespace Drupal\mymodule\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyModuleLocalTasks extends DeriverBase implements ContainerDeriverInterface {

  protected $entityTypeManager;

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public static function create(ContainerInterface $container, $base_plugin_id) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives = array();

    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
      if ($entity_type->hasLinkTemplate('canonical')) {
        $this->derivatives["$entity_type_id.mymodule_tab"] = [
          'route_name' => "entity.$entity_type_id.mymodule",
          'title' => t('Mymodule title'),
          'base_route' => "entity.$entity_type_id.canonical",
          'weight' => 100,
        ] + $base_plugin_definition;
      }
    }

    return $this->derivatives;
  }

}

3) Створіть контролер

Створіть клас MyModuleController в src / Controller

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;

class MyModuleController extends ControllerBase {

  public function doStuff(RouteMatchInterface $route_match) {
    $output = [];

    $parameter_name = $route_match->getRouteObject()->getOption('_mymodule_entity_type_id');
    $entity = $route_match->getParameter($parameter_name);

    if ($entity && $entity instanceof EntityInterface) {
      $output = ['#markup' => $entity->label()];
    }

    return $output;
  }

}

3
Це було дуже схоже на те, що я закінчив реалізувати. Проходження в RouteMatchInterface $ route_match було вирішенням моєї проблеми. Звідти мій об'єкт був доступний моєму контролеру.
tflanagan
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.