问题
how to place yii2 form error in title of anchor tag
This is my code
$form = ActiveForm::begin([
'id' => 'login-form',
'options' => ['class' => 'form-horizontal'],
'fieldConfig' => [
'template' => '
{label}
<div class="error-block">
<a href="#" title="{error}">error</a>
</div>
{input}
',
'errorOptions' => ['tag' => null]
],
]);
I want to add error in title of anchor tag in YII2
<a href="#" title="{error}">error</a>
回答1:
You need to display the error text inside the anchor tags title
attribute, and using the template
option wont help you achieve it automatically.
A few things in your approach.
You are specifying the
"tag"=>null
under theerrorOptions
which wont create the default html<p class="help-block help-block-error"></p>
.Even if you specify the tag as
div
orspan
even then it will break the HTML as the attribute title has double quotes<a href="#" title="{error}">error</a>
and the tag created will also have double quotes<div class="help-block help-block-error"></div>
.Then if you change the
<a href="#" title="{error}">error</a>
to<a href="#" title=\'{error}\'>error</a>
to fix the brokenHTML
the javascript wont be able to detect the element.
So then the event afterValidateAttribute
will come to your rescue which is triggered after validating the whole form and each attribute.
The signature of the event handler should be:
function (event, attribute, messages)
where
event
: an Event object.
attribute
: the attribute being validated. Please refer toattributeDefaults
for the structure of this parameter.
messages
: an array to which you can add additional validation error messages for the specified attribute.
Now change the template
under the fieldConfig
to the following and remove the {error}
from the template and the errorOptions
, as it is not needed and just keep you custom error element inside the template.
'fieldConfig' => [
'template' => '
{label}
<div class="error-block">
<a href="#" title="">error</a>
</div>
{input}
',
],
Now add the below javascript at the top of your view where you are rendering the form.
$js = <<< JS
$("#login-form").on(
'afterValidateAttribute',
function (event,attribute,messages) {
let input=attribute.input;
$(input).siblings('.error-block').find('a').attr('title',messages.join(','));
}
);
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
Now if you focus
out of the fields or hit the submit button you will see the error messages being populated in the title
attribute of the a
tag.
来源:https://stackoverflow.com/questions/53607230/how-to-place-yii2-form-error-in-title-of-anchor-tag