Score:1

How to alter routes defined in route_callbacks?

in flag

Usually I alter static routes in routes subscriber:

  protected function alterRoutes(RouteCollection $collection) {
    $route = $collection->get('gutenberg.media.load_media');
    if ($route) {
      $route->setDefault('_controller', '\Drupal\gutenberg_adv\Controller\MediaController::loadMedia');
    }
  }

However I this does not work for routes defined in routes_callback, so this does not work for search route for example:

$route = $collection->get('search.view_node_search');
if ($route) {
  $route->setDefault('_controller',
      '\Drupal\wi_misc\Controller\SearchController::view');
}

So how to alter search route controller?

MacSim avatar
um flag
Did you set the `search` module as a dependency of your own module ?
Score:-1
jp flag

Try to change the weight of the execution of the alterRoutes function. You can override the getSubscribedEvents function:

public static function getSubscribedEvents(): array
{
    return [
        RoutingEvents::ALTER => [
            'onAlterRoutes', 1
        ],
    ];
}

Notice that i call onAlterRoutes instead of alterRoutes. This is because in the parent class this is a wrapper for the called function:

public static function getSubscribedEvents() {
    $events[RoutingEvents::ALTER] = 'onAlterRoutes';
    return $events;
}

The higher your number (= weight) is, the earlier it gets executed (or the other way around). I would try with some high and some low numbers and check the result.

I have never tried it with this specific eventbut i used this method to solve other problems with events in some RouteSubscriber.

If you use drush to clear your cache (which you should after changing code in a RouteSubscriber) then you can also use var_dump($route); to ensure your route does exist and is loaded correctly. The dump will get displayed in the cmd.

Sergey Kravchenko avatar
in flag
unfortunately this does not affect at all the route definitely exists, I checked it but Drupal still uses default controller
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.