14

I want to be able to get the nid but the only information I have is http://example.com/this-is-the-alias.

Is there a drupal function to get either the internal path of /node/* for that alias if I am not on the page? Or is there a way to just get the nid from that alias right away?

20

I'm not sure if there's a direct function, but one route is to use the path alias manager service to lookup the internal path then regex it for a valid node id to perform an object load on:

$path = \Drupal::service('path.alias_manager')->getPathByAlias('/this-is-the-alias');
if(preg_match('/node\/(\d+)/', $path, $matches)) {
  $node = \Drupal\node\Entity\Node::load($matches[1]);
}
  • I found another way, see my answer – Adrian Cid Almaguer Nov 21 '16 at 22:49
  • 3
    For some reason, $path is sometimes equal to /this-is-the-alias. Once was when the root path (node/{id}) was another alias #migrationstruggles, but it was also present with other aliases. – Chris Happy Feb 23 '18 at 2:28
6

You can use the following code to get and load an entity and have access to his values:

  use \Drupal\Core\Url;

  $alias = \Drupal::service('path.alias_manager')->getPathByAlias('/etapes-de-la-vie');

  $params = Url::fromUri("internal:" . $alias)->getRouteParameters();
  $entity_type = key($params);
  $node = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);
  //to use dpm you need the devel module
  dpm($node->nid->value);

Reference:

Drupal 8: get entity object given system path?

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.