Drupal 8 Webform: Prepopulate entity reference (select, radio, ...) with current entitiy / node ID via tokens

Several times in the last months we had the requirement to prepopulate a Drupal 8 webform with a parent entity ID from the URL. For example we had forms to register for events which we embedded on the node page as paragraphs or blocks and wanted to set an entity reference field to the node ID programmatically.

It wasn't easy to find the right token due to missing or misleading documentation in the token browser.
Finally I found it:

This token has to be pasted into the "advanced" section of the form element configuration into "default value":

PS: We also had a different approach using a hook in a custom module. If you need something more complicated, here's our snippet:

  • The node type is "event"
  • The webform has "event_registration" in its ID
  • The event reference field in the entity form is: "event_ref"

  1. /**
  2.  * Implements hook_form_alter().
  3.  *
  4.  * @param $form
  5.  * @param \Drupal\Core\Form\FormStateInterface $form_state
  6.  * @param $form_id
  7.  */
  8. function drowl_customer_webform_submission_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  9.   if (strpos($form_id, 'eventregistration') >= 0) {
  10.     $node = \Drupal::routeMatch()->getParameter('node');
  11.     if (!empty($node) && $node instanceof \Drupal\node\NodeInterface) {
  12.       if ($node->bundle() == 'event') {
  13.         $nid = $node->id();
  14.         // Prepopulate with parent node ID and disable the selection:
  15.         $form['elements']['event_ref']['#default_value'] = $nid;
  16.         $form['elements']['event_ref']['#attributes']['disabled'] = 'disabled';
  17.       }
  18.     }
  19.   }
  20. }

webform_drupal_8_prepopulate_with_node_id.png63.46 KB


Kommentar hinzufügen

Der Inhalt dieses Feldes wird nicht öffentlich zugänglich angezeigt.

Weitere Informationen über Formatierungsoptionen