How can I retrieve the current node ID on a custom route? I have a new route and the yml file looks like this:

rsvplist.form:
  path: '/rsvplist'
  defaults:
    _form: '\Drupal\rsvplist\Form\RSVPForm'
    _title: 'RSVP to this Event'
  requirements:
    _permission: 'access content'


From the module root directory, I have src/Form/RSVPForm.php, and inside is where I have the build form function that looks like the following:

public function buildForm(array $form, FormStateInterface $form_state) {
    $node = \Drupal::routeMatch()-&gt;getParameter('node');
    $nid = $node-&gt;nid-&gt;value;

    $form['email'] = [
        '#title' =&gt; t('Email Address'),
        '#type' =&gt; 'textfield',
        '#size' =&gt; 25,
        '#description' =&gt; t('We will send updates to the email you provide.'),
        '#required' =&gt; TRUE,
    ];

    $form['submit'] = [
        '#type' =&gt; 'submit',
        '#value' =&gt; t('RSVP'),
    ];

    return $form;
}


When I clear the site cache and refresh the page: mylocal.com/rsvplist, I see the following error:

Notice: Trying to get property 'nid' of non-object


I initially used the following code to get the node

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


If I change the last piece of code to this:

$nid = $node-&gt;id();


I see the following error:

Error: Call to a member function id() on null


How can I get the node id when am on the new route?

Reference here
Your route doesn't have a parameter called node, so therefore $node is null.

In order to make node available as a parameter you have to be on a route that has node as a parameter.

So to add the node parameter to your route, you can do like this:

rsvplist.form:
  path: '/rsvplist/{node}'
  defaults:
    _form: '\Drupal\rsvplist\Form\RSVPForm'
    _title: 'RSVP to this Event'
  requirements:
    _permission: 'access content'
    _entity_access: 'node.view'
    node: \d+


And then you can add the $node parameter to your buildForm method, like this:

public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
  // Your form.
}


Since I added node: \d+ to your form, $node is now the loaded entity in the buildForm method.