Correctly show error message next to the field when the same form is rendered multiple times

Every form block now has unique ID (even the same block in two different form has different ID) used for rendering error messages. Before this, when the same form was rendered on a page multiple times, error messages of custom fields were always shown on the last rendered form, even if the first one was submitted.

[MAILPOET-6182]
This commit is contained in:
 Ján Mikláš
2024-08-07 10:52:35 +02:00
committed by Aschepikov
parent ccc1786614
commit 4a54033d1e
9 changed files with 39 additions and 15 deletions

View File

@@ -27,7 +27,9 @@ class BlockRendererHelper {
}
public function getInputValidation(array $block, array $extraRules = [], ?int $formId = null): string {
$rules = [];
$rules = [
'errors-container' => '.' . $this->getErrorsContainerClass($block, $formId),
];
$blockId = $this->wp->escAttr($block['id']);
if ($blockId === 'email') {
@@ -52,13 +54,11 @@ class BlockRendererHelper {
$rules['required'] = true;
$rules['mincheck'] = 1;
$rules['group'] = $blockId;
$rules['errors-container'] = '.mailpoet_error_' . $blockId . '_' . $formId;
$rules['required-message'] = __('Please select a list.', 'mailpoet');
}
if (!empty($block['params']['required'])) {
$rules['required'] = true;
$rules['errors-container'] = '.mailpoet_error_' . $blockId . '_' . $formId;
$rules['required-message'] = __('This field is required.', 'mailpoet');
}
@@ -74,13 +74,11 @@ class BlockRendererHelper {
if (in_array($block['type'], ['radio', 'checkbox'])) {
$rules['group'] = 'custom_field_' . $blockId;
$rules['errors-container'] = '.mailpoet_error_' . $blockId . ($formId ? '_' . $formId : '');
$rules['required-message'] = __('This field is required.', 'mailpoet');
}
if ($block['type'] === 'date') {
$rules['group'] = 'custom_field_' . $blockId;
$rules['errors-container'] = '.mailpoet_error_' . $blockId . ($formId ? '_' . $formId : '');
}
$validation = [];
@@ -267,6 +265,22 @@ class BlockRendererHelper {
}, $value);
}
public function renderErrorsContainer(array $block = [], ?int $formId = null): string {
$errorContainerClass = $this->getErrorsContainerClass($block, $formId);
return '<span class="' . $errorContainerClass . '"></span>';
}
private function getErrorsContainerClass(array $block = [], ?int $formId = null): string {
$validationId = $block['validation_id'] ?? null;
if (!$validationId) {
$validationId = $this->wp->escAttr($block['id']);
if ($formId) {
$validationId .= '_' . $formId;
}
}
return 'mailpoet_error_' . $validationId;
}
private function translateValidationErrorMessage(string $validate): string {
switch ($validate) {
case 'email':