By Anonymous (not verified) on
I know that the new thing to do in Drupal 8 is to do everything by route name rather than path but is there a way to create a route object by a path? The example I have is to set a form redirect to a specific page, created via the CMS. Using Drupal::url() requires a path name which would require me to hard code the node ID of the page I wish to use to go along with entity.node.canonical, which seems rather backwards.
Conversely I could programatically create the page in order to give it a specific route, but then that would defeat the purpose of using a CMS.
What would be the best way to generate a url for a redirect to a specific node without needing to rely on a hardcode id?
Thanks!
Comments
I'm also interested in the
I'm also interested in the answer to this question exactly.
Anyone out there know the answer?
Short Answer:: Given a form
Short Answer:: Given a form which has a field of 'givenpath' and you wish to use that path to get the route:
almost
you`d want to get also the parameters for the route name, especially if you`re doing a redirect or smth (of course, it depends on the case, but I thought it might be useful for someone):
You can use any of these
You can get this info from
You can get this info from the Symfony router:
Now
$resultwill contain an array with all the information you need. It contains the route name, the route object, the controller and title callback, even the entity the route belongs to.Almost ;)
Thanks for that, though there's maybe a small typo in there (method matchRequests() doesn't exist, maybe you meant matchRequest()). You may also consider exception handling here.
Following code works (for me) in 8.2.x:
---
The code can be simplified, as Drupal routers implement the
match()method. (SeeRouter::match().)By querying the router table
You can also obtain the route name from
routertable.Your query will look like this:
Just replace "my-path" with your path. You will get the route name, and then you can use it to generate urls like this
\Drupal\Core\Url::fromRoute(route.name');Regards,
Subhojit Paul
As simple as that.
As simple as that.
Use RouteProvider:
Use RouteProvider::getRoutesByPattern(). Eg:
Works for me
Thank you!
Using RouteProvider::getRoutesByPattern() worked for me, I think that is the best way to find the route_name.
Best,
One liner
$route_name = Url::fromUserInput($internal_path)->getRouteName();See https://drupal.stackexchange.com/a/223465/2089 for details.
That doesn't work with an
That doesn't work with an internal path such as 'node/%/edit'.
I have used it for a path
I have used it for a path like 'user/%/path' and it works great.
$current_path = \Drupal::service('path.current')->getPath();