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()->getParameter('node');
$nid = $node->nid->value;
$form['email'] = [
'#title' => t('Email Address'),
'#type' => 'textfield',
'#size' => 25,
'#description' => t('We will send updates to the email you provide.'),
'#required' => TRUE,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => 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()->getParameter('node');
$nid = $node->nid->value;
If I change the last piece of code to this:
$nid = $node->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