I'm using hook_webform_submission_form_alter() to prepopulate some form values. When a user saves a draft of their webform submission and comes back to it later, the code in hook_webform_submission_form_alter() is wiping out their saved values. How do I first check if there's an existing draft submission? Using Webform 6.1.

2 Answers 2

function MYMODULE_webform_submission_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // Check if there's an existing draft submission.
  $webform_submission = $form_state->get('webform_submission');
  if ($webform_submission && !$webform_submission->isCompleted()) {
    // Get the saved values from the existing draft submission.
    $values = $webform_submission->getData();
    // Prepopulate the form fields with the saved values.
    $form['elements']['my_field']['#default_value'] = $values['my_field'];
    // Add any additional prepopulation code here.
  • Thanks but $form_state->get('webform_submission') is null.
    – codesmith
    Commented Mar 3, 2023 at 7:56
  • It seems that the $form_state->get('webform_submission') value is currently null, which could mean that no webform submission has been made yet
    – Vikram8888
    Commented Mar 3, 2023 at 8:02

Ah found it...

function MYMODULE_webform_submission_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form_object = $form_state->getFormObject();
  $webform_submission = $form_object->getEntity();

  if ( $webform_submission->isDraft() ) {
  } else {

    //pre-populate fields...

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.