For example, we have two routes, which points to the same path.

And each route has its own controller.

For example, I have defined a route with controller, which has a path "node/1", whereas a node with id=1 is already added to the site.

How can we determine, which controller will be started ?

And how can we select and assign forcibly controller to start, which we need ? For example, in my case for path "node/1" we don't want to start the NodeController, but we want to use the controller, defined in our module. Or Vice versa.


Drupal uses always the most specific route. If you define for the path /node/1


  path: '/node/1'
    _controller: '\Drupal\mymodule\Controller\MyController::content'
    _title: 'Override of node 1'
    _permission: 'access content'

then the custom controller \Drupal\mymodule\Controller\MyController::content is used instead of the node controller \Drupal\node\Controller\NodeViewController::view.

But I don't understand "Or Vice versa". For that you would have to remove the more specific route, so that the less specific node route for /node/{node} can take over again.

If you want a dynamic solution, you can route all nodes to your custom controller and then decide in this controller what to do, display the node or your own content.

For this you can extend the NodeViewController class and define a new view() function, in which you call parent::view() for the original node content. Then replace the class in a route subscriber:

$route->setDefault('_controller', '\Drupal\mymodule\Controller\MyController::view');

Reference: https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones

  • You have written > the custom controller \Drupal\mymodule\Controller\MyController::content is used instead of the node controller \Drupal\node\Controller\NodeViewController::view. Could you explain me, why priority of my controller is higher than priority of the default node controller ? Or, could you give me a link to the documentation, where I would read how priorities are being assigned ? – Yakimkin Roman Dec 19 '16 at 12:55
  • 1
    The priority is higher, because the path is more specific. Sorry, couldn't find a link, but I'm sure someone told me that or I read it somewhere. – 4k4 Dec 19 '16 at 14:15
  • I think that's what's called "fit" in the {router} table. See \Drupal\Core\Routing\RouteCompiler::getFit – Berdir Dec 19 '16 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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