3

Is it possible to add a default controller to the '<front>' route? There's no default controller defined in system.routing.yml.

I'm trying to get a handle on it by using the following code:

<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Get front page and set controller.
    if ($route = $collection->get('<front>')) {
      $route->setDefault('_controller', '\Drupal\mymodule\Controller\MyModuleController::MyModuleMethod');
    }
  }

}

But it doesn't seem to do anything. However this code works when replacing '<front>' with another route like help.main. Why is that? Do I have to add the controller instead of setting it? (D8)

1 Answer 1

1

<front> is not really a route that can be resolved for an incoming request, it's just a helper for building a URL.

It works in the opposite way, you create a controller at whatever path you want, and then you set the frontpage to that path on the system information page aka in the system.site configuration object.

2
  • Thanks for the explanation. I need to intercept requests to <front> and apply some logic from a module before the page is rendered. Any suggestions?
    – AdamB
    Commented Mar 10, 2018 at 18:14
  • There are no requests to <front>, it is a setting and is at runtime updated to /some/path, which can be anything, e.g. a node or a custom controller. Either define your own route that you use as front, which can then do what the current front does, you could alter the route that is already uses as front (doesn't really make sense for something generic like a node as that doesn't have a unique route) or you could implement a request event subscriber, and check for being on the frontpage. Might be easier to answer in a new question where you describe the specific problem you're trying to solve
    – Berdir
    Commented Mar 11, 2018 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.