Change routing behaviour for non-existent entities For my custom entity type called item, I would like to set up routes such that the path:

/item/{item}



views the entity as normal, if it exists
if it doesn't exists, redirects to the create form


The default Entity controllers create a 404 response. How can I change that behaviour?

Currently, the routes are generated through the entity's annotation (via DefaultHtmlRouteProvider):

* links = {
*   "canonical" = "/item/{item}"
*   ...
* }
Yes, routing is one way to do this. Extend the entity view controller, where you call (1) the parent method to view the entity or (2) redirect to the create form. Change the route so that it points to the new controller and remove the options for type casting and converting the entity parameter. You have then to load the entity in the controller by hand, because the controller gets only the raw parameter (the entity id), but you need to check if the entity exists anyway to decide if you need to redirect. You can change the route by extending DefaultHtmlRouteProvider or in a RouteSubscriber. You might also need to move the access check from the route to the controller after the entity is loaded.

There are more ways to do this, you could redirect in a request subscriber where you check if the entity exists before routing or you could redirect in an exception subscriber after a 404 is raised.

The last option is possibly easier to implement, because then you don't need to think about routing and access checking and simply react on a 404 caused by your specific entity route.