0

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.

2
  • 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
    Mar 6 '18 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.
    – 4k4
    Mar 6 '18 at 17:01
0

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());
  }
}
2
  • slight correction: $form['elements']['FIELDNAME']['#default_value'] = 'f<insertfieldvalue>';
    – icicleking
    Mar 6 '18 at 17:56
  • It was just an example to give a hint and glad it works for you. Mar 7 '18 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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