12

I created a module that receives the node ID from the form. On form validation, it needs to verify a node with that node ID exists.

How can I verify it?

2 Answers 2

10

You can pass the nid to \Drupal\node\Entity\Node::load(). It will return an object if it exists, NULL if it doesn't.

17

If you don't want to load the entire node then you can use entity query:

$values = \Drupal::entityQuery('node')->condition('nid', $id)->execute();
$node_exists = !empty($values);

This will be much more efficient because it only asks for the ids and not all the node fields.

6
  • 1
    It will not even invoke too much hooks, so it is definitively faster, and it still doesn't require to hard-code the database table name (which would happen when directly query the database).
    – apaderno
    Commented Dec 26, 2016 at 4:30
  • 3
    This might not even be that obviously faster, depends on various factors. If the ID doesn't exist, then the query that load does is probably faster and it's more efficient than doing an entity query (which involves two layers of query builders. And if the node exists, then it might already be cached in static/persistent cache or might need to to be used somehow if it exists.. in all those cases, load() might actually make more sense.
    – Berdir
    Commented Dec 26, 2016 at 16:30
  • 1
    I agree that it depends on the situation.
    – Eyal
    Commented Dec 27, 2016 at 0:38
  • 2
    I was beginning to run into issues with my setup. I have about 8000 nodes. This code returns super duper fast. This should be the accepted answer. Commented Jul 25, 2018 at 22:54
  • 2
    Honestly, this is the best and most efficient answer.
    – JFC
    Commented Jan 5, 2019 at 7:31

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.