You are here

public function WebformSubmitResource::post in Webform REST 8

Same name and namespace in other branches
  1. 8.3 src/Plugin/rest/resource/WebformSubmitResource.php \Drupal\webform_rest\Plugin\rest\resource\WebformSubmitResource::post()
  2. 8.2 src/Plugin/rest/resource/WebformSubmitResource.php \Drupal\webform_rest\Plugin\rest\resource\WebformSubmitResource::post()
  3. 4.x src/Plugin/rest/resource/WebformSubmitResource.php \Drupal\webform_rest\Plugin\rest\resource\WebformSubmitResource::post()

Responds to entity POST requests and saves the new entity.

Parameters

array $webform_data: Webform field data and webform ID.

Return value

\Drupal\rest\ResourceResponse The HTTP response object.

Throws

\Symfony\Component\HttpKernel\Exception\HttpException Throws HttpException in case of error.

File

src/Plugin/rest/resource/WebformSubmitResource.php, line 38

Class

WebformSubmitResource
Creates a resource for submitting a webform.

Namespace

Drupal\webform_rest\Plugin\rest\resource

Code

public function post(array $webform_data) {

  // Basic check for webform ID.
  if (empty($webform_data['webform_id'])) {
    $errors = [
      'error' => [
        'code' => '500',
      ],
    ];
    return new JsonResponse($errors, 500);
  }

  // Convert to webform values format.
  $values = [
    'webform_id' => $webform_data['webform_id'],
    'entity_type' => NULL,
    'entity_id' => NULL,
    'in_draft' => FALSE,
    'uri' => '/webform/' . $webform_data['webform_id'] . '/api',
  ];

  // Don't submit webform ID.
  unset($webform_data['webform_id']);
  $values['data'] = $webform_data;

  // Check for a valid webform.
  $webform = Webform::load($values['webform_id']);
  if (!$webform) {
    $errors = [
      'error' => [
        'message' => 'Invalid webform_id value.',
      ],
    ];
    return new ModifiedResourceResponse($errors);
  }

  // Check webform is open.
  $is_open = WebformSubmissionForm::isOpen($webform);
  if ($is_open === TRUE) {

    // Validate submission.
    $errors = WebformSubmissionForm::validateValues($values);

    // Check there are no validation errors.
    if (!empty($errors)) {
      $errors = [
        'error' => $errors,
      ];
      return new ResourceResponse($errors);
    }
    else {

      // Return submission ID.
      $webform_submission = WebformSubmissionForm::submitValues($values);
      return new ModifiedResourceResponse([
        'sid' => $webform_submission
          ->id(),
      ]);
    }
  }
}