I am trying to add some values to a hidden field in my webform before submission. Is there any hooks to access webform submission in Drupal 8? I tried How do I modify a webform submission field right before it is saved? without luck.
2 Answers
The answer linked is mostly right, just a couple of updates to get it working. In a custom .module add:
use Drupal\Core\Form\FormStateInterface;
function MODULENAME_form_alter(&$form,$form_state, $form_id) {
if ($form_id == 'FORMID') {
$form['actions']['submit']['#validate'][] = 'MODULENAME_form_validate';
}
}
function MODULENAME_form_validate($form, FormStateInterface $form_state) {
$form_state->setValue('hidden_id', 'Value for Hidden field');
}
To alter webform values before submission -
In my code, I am changing the timestamp from "Y-m-d HH:MM:SS" to "Y-m-d" format and changing it before saving to DB. Also, i am creating a custom module name as "webform_presave"
/**
* Implements hook_ENTITY_TYPE_presave().
*/
function webform_presave_webform_submission_presave(\Drupal\webform\Entity\WebformSubmission $submission) {
$submissionCreated = $submission->getCreatedTime();
$submissionCreatedChnaged = format_date($submissionCreated, 'custom_date');
$a = strptime($submissionCreatedChnaged, '%Y-%m-%d');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);
$submission->setCreatedTime($timestamp);
}