You are here

public static function WebformSubmissionForm::submitWebformSubmission in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/WebformSubmissionForm.php \Drupal\webform\WebformSubmissionForm::submitWebformSubmission()

Programmatically validate and submit a webform submission.

Parameters

\Drupal\webform\WebformSubmissionInterface $webform_submission: WebformSubmission with values and data.

bool $validate_only: Flag to trigger only webform validation. Defaults to FALSE.

Return value

array|\Drupal\webform\WebformSubmissionInterface|null An array of error messages if validation fails or a webform submission (when $validate_only is FALSE) or NULL (when $validate_only is TRUE) if there are no validation errors.

2 calls to WebformSubmissionForm::submitWebformSubmission()
WebformSubmissionForm::submitFormValues in src/WebformSubmissionForm.php
Programmatically validate form values and submit a webform submission.
WebformSubmissionForm::validateWebformSubmission in src/WebformSubmissionForm.php
Programmatically validate and submit a webform submission.

File

src/WebformSubmissionForm.php, line 3231

Class

WebformSubmissionForm
Provides a webform to collect and edit submissions.

Namespace

Drupal\webform

Code

public static function submitWebformSubmission(WebformSubmissionInterface $webform_submission, $validate_only = FALSE) {

  /** @var \Drupal\webform\WebformSubmissionForm $form_object */
  $form_object = \Drupal::entityTypeManager()
    ->getFormObject('webform_submission', 'api');
  $form_object
    ->setEntity($webform_submission);

  // Create an empty form state which will be populated when the submission
  // form is submitted.
  $form_state = new FormState();

  // Set the triggering element to an empty element to prevent
  // errors from managed files.
  // @see \Drupal\file\Element\ManagedFile::validateManagedFile
  $form_state
    ->setTriggeringElement([
    '#parents' => [],
  ]);

  // Get existing error messages.
  $error_messages = \Drupal::messenger()
    ->messagesByType(MessengerInterface::TYPE_ERROR);

  // Submit the form.
  \Drupal::formBuilder()
    ->submitForm($form_object, $form_state);

  // Get the errors but skip drafts.
  $errors = $webform_submission
    ->isDraft() && !$validate_only ? [] : $form_state
    ->getErrors();

  // Delete all form related error messages.
  \Drupal::messenger()
    ->deleteByType(MessengerInterface::TYPE_ERROR);

  // Restore existing error message.
  foreach ($error_messages as $error_message) {
    \Drupal::messenger()
      ->addError($error_message);
  }
  if ($errors) {
    return $errors;
  }
  elseif ($validate_only) {
    return NULL;
  }
  else {
    $webform_submission
      ->save();
    return $webform_submission;
  }
}