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
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.
}
}
-
-
It seems that the $form_state->get('webform_submission') value is currently null, which could mean that no webform submission has been made yet Mar 3 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() ) {
return;
} else {
//pre-populate fields...
}
}