1

In Drupal\rsvplist\Form\RSVPForm->buildForm(), I wrote this to get the current nid:

$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->nid->value;

I get this error:

Notice: Trying to get property 'nid' of non-object in Drupal\rsvplist\Form\RSVPForm->buildForm() (line 30 of modules\custom\rsvplist\src\Form\RSVPForm.php).

I am a new module developer. How to get the current nid in drupal 8?

4
  • What URL are you doing this? Is this form a separate standalone page? The get parameter node will work only on node view pages. Is your form going to be shown in a block under the node? in the node pages?
    – anoopjohn
    Nov 11 '19 at 0:30
  • 2
    Use the id() method instead. You also have to check if $node is an instance of NodeInterface because you could be on a route where that won't work (like a user, view, taxonomy, or media route).
    – Kevin
    Nov 11 '19 at 1:04
  • ->getRawParameter() will return just the NID as well Nov 11 '19 at 1:14
  • 1
    But that could be any ID, couldn't it?
    – Kevin
    Nov 11 '19 at 3:37
5

You will need to check if the $node variable is actually an instance of node object.

if ($node instanceof \Drupal\node\NodeInterface) {
  // You can get nid and anything else you need from the node object.
  $nid = $node->id();
}

See

How do I get the current node ID?

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.