Skip to content

Instantly share code, notes, and snippets.

@jacecotton
Last active March 27, 2024 16:37
Show Gist options
  • Save jacecotton/1f5460a292a6a7f8da48be320a140840 to your computer and use it in GitHub Desktop.
Save jacecotton/1f5460a292a6a7f8da48be320a140840 to your computer and use it in GitHub Desktop.
Methods to derive node object
<?php
/**
* Once we have access to a node object we can e.g. `dump($node)` to
* discover properties, like `$node->get("field_example")->getValue()`
* or `$node->nid->getValue()[0]["value"]`.
*
* @todo - If we just need the node object of the current page, we
* probably don't need to derive it. But what exactly is the reference
* to the current node?
*/
// Do we already know the NID?
function nodeFromNid(String $nid) {
return \Drupal\node\Entity\Node::load($nid);
}
// Do we have access to a desired path?
function nodeFromPath(String $path) {
// Ensure path, convert from alias if necessary.
$path = \Drupal::services("path_alias.manager")->getPathByAlias($path);
if(preg_match("/node\/(\d+)/", $path, $matches)) {
return \Drupal\node\Entity\Node::load($matches[1]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment