I have a form that adds a product to the cart.
The form uses AJAX to open a modal when the form is submitted.
I want to show form errors (if any) before the modal opens and avoid opening it if there are errors.
Here's my form submit element:
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Submit'),
'#ajax' => [
'callback' => '::submitAjaxForm'
],
'#attached' => [
'library' => ['core/drupal.dialog.ajax'],
],
];
My submitAjaxForm
:
public function submitAjaxForm(array $form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$response->addCommand(new OpenModalDialogCommand(
$this->t('Product added to cart!'),
[
'#theme' => 'some_theme',
]
));
return $response;
}
And my submitForm
:
public function submitForm(array &$form, FormStateInterface $form_state) {
// Add product to cart.
}
I have tried by adding this code to the AjaxSubmit but it only shows the error messages once the page has been reloaded.
if ($form_state::hasAnyErrors()) {
foreach ($form_state->getErrors() as $error) {
$this->messenger()->addError($error);
$message = [
'#theme' => 'status_messages',
'#message_list' => $this->messenger()->messagesByType(MessengerInterface::TYPE_ERROR),
];
$messages = $this->renderer->render($message);
$response = new AjaxResponse();
$response->addCommand(new HtmlCommand('#result-message', $messages));
$form_state->setRebuild(TRUE);
return $response;
}
}
How can I show the errors without having to reload the page?