I have a content type, applicant with a name, and birthday field. I also have a entity reference to a webform, which has a name and birthday fields, as well as others. I want to allow users to create the applicant content type, then click the link to webform, and autofill the appropriate fields on the webform.

I've been trying to use the FormStateInterface::setValue method. Here' where I am so far:

function mymodule_webform_element_alter(array &$element, \Drupal\Core\Form\FormStateInterface $form_state, array $context) {
  kint($element); // this outputs '#webform_key' => string(4) "name"

  $form_state->setValue('name', 'bob'); // Here I'm just trying to statically set the field.

This method doesn't actually autofill, and it also doesn't actually set the value. This is a demo-project, so we don't have specs yet, so I'm actually fine with either auto-filling, or setting the value, probably both.

The main thing I'm trying to do here is to link one node entity to a webform submission.

  • I wouldn't necessarily assume #webform_key and the key of the element in the form array are related (maybe you know better from debugging?). hook_form_alter might be a better place to approach this either way
    – Clive
    Commented Mar 6, 2018 at 14:35
  • You shouldn't need to do such low level stuff. You can set default values when you render a webform or if the webform is embedded in a node you can use node tokens.
    – 4uk4
    Commented Mar 6, 2018 at 17:01

1 Answer 1


Using hook_form_alter() or hook_form_FORM_ID_alter(), you can set the default value by php code

For Example

function HOOK_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  if($form_id == 'YOUR_FROM_ID'){
    $form['submitted']['FIELDNAME']['#default_value'] = date("Y-m-d h:i a", time());
  • slight correction: $form['elements']['FIELDNAME']['#default_value'] = 'f<insertfieldvalue>';
    – icicleking
    Commented Mar 6, 2018 at 17:56
  • It was just an example to give a hint and glad it works for you. Commented Mar 7, 2018 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.