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"
/**
* Implements hook_form_alter().
*
* @param $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
* @param $form_id
*/
function drowl_customer_webform_submission_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if (strpos($form_id, 'eventregistration') >= 0) {
$node = \Drupal::routeMatch()->getParameter('node');
if (!empty($node) && $node instanceof \Drupal\node\NodeInterface) {
if ($node->bundle() == 'event') {
$nid = $node->id();
// Prepopulate with parent node ID and disable the selection:
$form['elements']['event_ref']['#default_value'] = $nid;
$form['elements']['event_ref']['#attributes']['disabled'] = 'disabled';
}
}
}
}
?>