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?


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

| improve this answer | |

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.

| improve this answer | |
  • 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). – kiamlaluno Dec 26 '16 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 Dec 26 '16 at 16:30
  • 1
    I agree that it depends on the situation. – Eyal Dec 27 '16 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. – Jorge Calderon Jul 25 '18 at 22:54
  • 2
    Honestly, this is the best and most efficient answer. – JFK Jan 5 '19 at 7:31

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.