Is it possible to modify the form’s own error message so that some parameters are added?
<form>
<label for="name">Name</label>
<input name="name" id="name" type="text" required>
<div class="error-message">Fill the name</div>
</form>
I want it to be
<form>
<label for="name">Name</label>
<input name="name" id="name" type="text" aria-required="true" aria-invalid="true" aria-describedby="hint-name" required>
<div class="error-message" id="hint-name">Fill the name</div>
</form>
It is important to put the ID in the error-message
, for aria.
FormHelper contain template:
'error' => '<div class="error-message">{{content}}</div>',
Thank you for help
You should look at Form - 4.x
See cakephp/FormHelper.php at master · cakephp/cakephp · GitHub for all the templates/keys which can be overwritten.
The problem you are running into is the fact, that the default error
template doesn’t have any other “variables” which can be used inside the template.
$errorText[] = $this->formatTemplate('errorItem', ['text' => $err]);
}
$error = $this->formatTemplate('errorList', [
'content' => implode('', $errorText),
]);
} else {
$error = array_pop($error);
}
}
return $this->formatTemplate('error', ['content' => $error]);
}
/**
* Returns a formatted LABEL element for HTML forms.
*
* Will automatically generate a `for` attribute if one is not provided.
*
* ### Options
*
* - `for` - Set the for attribute, if its not defined the for attribute
This line only sets the content
variable which then will be output at the position of {{content}}
in this template.
'templates' => [
// Used for button elements in button().
'button' => '<button{{attrs}}>{{text}}</button>',
// Used for checkboxes in checkbox() and multiCheckbox().
'checkbox' => '<input type="checkbox" name="{{name}}" value="{{value}}"{{attrs}}>',
// Input group wrapper for checkboxes created via control().
'checkboxFormGroup' => '{{label}}',
// Wrapper container for checkboxes.
'checkboxWrapper' => '<div class="checkbox">{{label}}</div>',
// Error message wrapper elements.
'error' => '<div class="error-message">{{content}}</div>',
// Container for error items.
'errorList' => '<ul>{{content}}</ul>',
// Error item wrapper.
'errorItem' => '<li>{{text}}</li>',
// File input used by file().
'file' => '<input type="file" name="{{name}}"{{attrs}}>',
// Fieldset element used by allControls().
'fieldset' => '<fieldset{{attrs}}>{{content}}</fieldset>',
// Open tag used by create().
'formStart' => '<form{{attrs}}>',
So in your example you would have to extend the FormHelper with a custom class, overwrite the error function and add that functionality in there.
I haven’t thought it completely through but those are the code parts you need to start looking at to get to know how this whole system works.
1 Like
Thank you, and how can you overwrite the error function, can you please give an example?