0

Retrieve a node based on condition:

$query = \Drupal::entityQuery('node')
->condition('type', 'my_content_type')
->condition('title', 'my node title');
$nid = $query->execute();

The result of $nid is the correct node ID but the format is a string, (es: "123")

When I want to load the node by its ID, I write:

$node_id = Node::load($nid);

Doing this, the result I get is NULL because the variable $nid is holding a string (not integer). If I write the code like this:

$node_id = Node::load(123);

I get the node loaded.

How can I convert the variable string ($nid) as an integer ? I tried:

$nid_int = (int) $nid;
$node_id = Node::load($nid_int);

also I tried:

$nid_int = intval($nid);
$node_id = Node::load($nid_int);

But I alwas get result NULL

Thanks for your help

2
  • 6
    The result of your entity query is not a node id but an array of ids. That's why your load doesn't work. There's no problem with using a string node ID in a load. Oct 1, 2020 at 14:28
  • (not 100% sure) but could there be a possibility your query contains more than just one result? So, you might be trying to load multiple nodes in as a parameter. I could be wrong, just a thought. Oct 1, 2020 at 14:28

1 Answer 1

2

the $query->execute(); return an array of key/value like [KEY => nid1]:
if you are sure you have only one node with that tittle you should get the first element of the array it's your nid try with:

 $query = \Drupal::entityQuery('node')
  ->condition('type', 'my_content_type')
  ->condition('title', 'my node title');
$nids = $query->execute();
// Get the nid in the array.
$nid = reset($nids);
$node = Node::load($nid);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.