I made a custom handler for one of my webform to call a service when the form is submitted. Here is my code. It is working when the service return a response with status code = 200 but I cannot find a way to notify the view when an error is raised by the webservice. I would like to show a modal with an error message but cannot find how to do this.
class CRMWebformHandler extends WebformHandlerBase {
public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
try {
$data = array(
'firstName' => $webform_submission->getData()['lastname'],
'lastName' => $webform_submission->getData()['firstname'],
'civility' => $webform_submission->getData()['civility'],
'email' => $webform_submission->getData()['email'],
);
$payload = json_encode($data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
curl_setopt($curl, CURLOPT_URL, "https://my-url.com");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
$json = json_decode($result, TRUE);
$succeed = is_bool($json) ? $json : FALSE;
if (!$succeed && curl_getinfo($curl, CURLINFO_HTTP_CODE) !== 200) {
throw new \Exception('No valid response from server.');
}
}
catch (\Exception $exception) {
\Drupal::messenger()->addError('No valid response from server.');
return;
}
}
}