1

I'm trying create/update Webform Submission programmatically. I already know how the create new submission by following the Drupal 8 API. Now I'm trying to build a update method, I refer to the Webform module source-code and API documents but couldn't find a solution. I guess they remove webform_get_submission webform_submission_update functions in Drupal 8.3 as-well.

$values = [
  'webform_id' => 'attendees_info',
  'in_draft' => FALSE,
  'uid' => $uid,
  'langcode' => 'en',
  'token' => 'at_'.$token,
  'uri' => '/webform/attendees/api',
  'remote_addr' => '',
  'data' => [
    'name' => $name,
    'email' => $email,
    'gallery_url' => 'gallery/'.$token,
  ],
];

$webform = Webform::load($values['webform_id']);
$is_open = WebformSubmissionForm::isOpen($webform);

if ($is_open === TRUE) {
    // Validate submission.
    $errors = WebformSubmissionForm::validateValues($values);

    // Check there are no validation errors.
    if (!empty($errors)) {
       return $errors;
    }
    else {
      // Submit values and get submission ID.
      $webform_submission = WebformSubmissionForm::submitValues($values);
      return $webform_submission->id();
    }
}

Above is my Submission creation code, I don't know how to do the update method. Is anyone face this issue before? Hope someone will help me on this, thanks.

7

Try using \Drupal\webform\WebformSubmissionInterface::getData(); and \Drupal\webform\WebformSubmissionInterface::setData($data);

// Load submission using sid.
/** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */
$webform_submission = \Drupal\webform\Entity\WebformSubmission::load($sid);

// Get submission data.
$data = $webform_submission->getData();

// Change submission data.
$data['element_key'] = 'custom_element_value';

// Set submission data.
$webform_submission->setData($data);

// Save submission.
$webform_submission->save();

Update: Use a capital "E" in "Entity" for the class name. (Recently got updated).

0

jrockowitz's above code is the correct and clean approach. Below also works, just wanted to share.

$query = \Drupal::database()->merge('webform_submission_data');
$query->key([
    'sid' => $sid,
    'name' => 'your_custom_key',
])->fields([
    'value' => 'your_value',
]);
$query->execute();
  • This works too, as $ws->setData() doesn't do any validation, however it may change in the future. Plus, by skipping $ws->save() change_date doesn't get updated which may cause inconsistency later. It's always a good practice to avoid touching row data. – Alexar Jun 20 '18 at 9:00

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.