0

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

2

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 
  }
  • 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) – Alex Aug 6 '18 at 8:12
  • also, i try to get the url for the translation – Alex Aug 6 '18 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(); – berramou Aug 6 '18 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? :( – Alex Aug 6 '18 at 15:13
  • prefix it with / instead of 'node/nid' try '/node/nid'. – berramou Aug 6 '18 at 16:04

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.