3

I am trying to render a link from a Url object and verify the user actually has access to that URL, like when viewing a node.

For some reason, this always returns FALSE, although the node is accessible when $language is the set language.

$_url = Url::fromRoute('<current>', [], ['language' => $language]); if ($_url->access()) { // The code inside here is never executed. } 

How do I verify a user may access the given path, without actually loading the entity behind that path?


edit: current state:

$currentPath = \Drupal::service('path.current')->getPath(); $urlObject = Url::fromUserInput($currentPath); $routeName = $urlObject->getRouteName(); $linkUrl = Url::fromRoute($routeName, [], ['language' => $dataLangId]); debug($languageData['languageName']); debug($linkUrl->toString()); if ($linkUrl->access()) { debug('access'); } else { debug('denied'); } 

results in:

Some mandatory parameters are missing ("node") to generate a URL for route "entity.node.canonical

1 Answer 1

6

I don't know why

 $_url = Url::fromRoute('', [], ['language' => $language]); 

Doesn't work with route name <current> but it works with other route names. For example with route with name some_module.some_route_name the following will work.

  $language = \Drupal::languageManager()->getCurrentLanguage()->getId(); $_url = Url::fromRoute('some_module.some_route_name', [], ['language' => $language]); $userCurrent = \Drupal::currentUser(); if ($_url->access($userCurrent)) { //- Do Stuff }  

In your case for the current route. Try this out.

 use Drupal\Core\Url; $request = \Drupal::request(); $_url = Url::createFromRequest($request); $userCurrent = \Drupal::currentUser(); if ($_url->access($userCurrent)) { //- Do Stuff } 
5
  • the problem is i dont have the route inside the request. its just an array of links i want to render (or dont render, depending on the access grant) Commented Aug 6, 2018 at 8:12
  • also, i try to get the url for the translation Commented Aug 6, 2018 at 10:54
  • You can loop through your array links, and for each element use the following to get the route name . $route_name = Url::fromUserInput('your_path')->getRouteName(); Commented Aug 6, 2018 at 11:41
  • thanks for your help so far. when i load the route from a node, i obviously get the following error: Some mandatory parameters are missing ("node") to generate a URL for route "entity.node.canonical so before loading the route i would need to check whether its a node, a view, etc to pass the needed params. which brings me back to my original question: isnt there a freaking built in function to check if a user has access to a url without having to do all that? :( Commented Aug 6, 2018 at 15:13
  • prefix it with / instead of 'node/nid' try '/node/nid'. Commented Aug 6, 2018 at 16:04

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.