3

I want to get a node path/URL via entity query. So far I've managed to fetch the title of the node.

$facultyPostings = $query->get('node')
  ->condition('status', 1, '=')
  ->condition('type', 'careers')
  ->condition('field_career_directory', 'Faculty Postings', '=')
  ->sort('created')
  ->execute();

foreach ($facultyPostings as $key => $careers) {
  $careersNode = _nodeLoad($careers);
  $variables['faculty_postings'][$key]['title'] = $careersNode->get('title')->value;
  $variables['faculty_postings'][$key]['path'] = $careersNode->get('path')->value;
}
0

2 Answers 2

7

It depends on what you want to generate. To get the \Drupal\Core\Url object for the node:

$node->toUrl();

To get a URL string:

$node->toUrl()->toString();

To get a \Drupal\Core\Link object:

$node->toLink();

To get an HTML string for the link:

$node->toLink()->toString();

toLink() can optionally take an argument providing a different node link. For example, the following can be used to get a link to the node edit page;

$node->toLink('edit-form');

Or to the delete page:

$node->toLink('delete-form');

The values that can be passed to toLink() can be determined by looking at keys of the links section of the annotation for the entity type. The node class lists these as:

*  links = {
*    "canonical" = "/node/{node}",
*    "delete-form" = "/node/{node}/delete",
*    "delete-multiple-form" = "/admin/content/node/delete",
*    "edit-form" = "/node/{node}/edit",
*    "version-history" = "/node/{node}/revisions",
*    "revision" = "/node/{node}/revisions/{node_revision}/view",
*    "create" = "/node",
*  }
?>
1

Once you get the node id you can retrive it via

$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.