For my custom entity type called item, I would like to set up routes such that the path:

  1. views the entity as normal, if it exists
  2. 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}"
*   ...
* }
  • Show us your routing.yml setting for /item/{item} – Beebee Apr 6 '18 at 14:53
  • voila. See above. The route does not come from a .yml file, but from a route provider. – Hendrik Apr 6 '18 at 15:11
  • Although I'd be happy to change that and declare the route statically. Do you think that would be a good solution? – Hendrik Apr 6 '18 at 15:19

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.

  • Sounds good. You mention options for type casting. Which options are those? I can see DefaultHtmlProvider adds _entity_view. – Hendrik Apr 6 '18 at 15:52
  • 1
    I was looking at the route table (if you alter the route), then you can remove all requirements and options other than the requirement for \d+, so that you get the raw entity id. If you change the route in the DefaultHtmlProvider then user _controller instead of _entity_view. – 4k4 Apr 6 '18 at 15:54

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.