Reputation: 220
How do you create a Yii2 Active Form custom message using Html tags?
I change this message via jQuery.activeForm
.
Current message:
Desired message
Here is the javascript code I am trying:
myform.js
- which included to AppAssets.php
.
The order of operations:
ajax/is-email-busy
action. I do it via Ajax queryOn browser: When user clicks the link in message, will appear popup form to login
$("#form-ad").on("afterValidateAttribute", function(event, attribute, messages) {
var hasError = messages.length !== 0;
var field = $(attribute.container);
var input = field.find(attribute.input);
if(attribute.name == 'email' && !hasError) {
var form_data = new FormData();
form_data.append('email', input.val());
$.ajax({
url: 'ajax/is-email-busy',
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
console.log(data);
jQuery('#form-ad')
.yiiActiveForm(
'updateAttribute',
'adform-email',
['This email is busy. If it\'s your email <a href="#">click here</a>']);
}
});
}
});
In a view file:
echo $form->field($model, 'email')->input('email');
Upvotes: 2
Views: 2566
Reputation: 133360
You can customize the error message of a rule by specifying the message property when declaring the rule, like the following,
in your active form model
public function rules()
{
return [
['email', 'required',
'message' => 'This email is busy. If it\'s your email
<a href="#">click here</a>'
],
['email', 'email'],
];
}
otherwise you don't want add a custom validation rule in Yii and you want use jquery you should refer to the proper field id
normally the field id is modelname-fieldname (all lowercase) separated by -
In your case should by id='myform-email' and with this reference set the proper attribute (look ad the renderd code for find the correct attribute)
Looking at the code rendered by Yii2 the error message are managed by adding a div containing the text related to the message and hidden/display in function offer the result of validation. I suggest you the same behavior. When you validation fails add a sibling to the input with your message and the display. Or you can prepare this div in you form and then display in your jquery validation code.
I hope this is useful
Upvotes: 2