I need to validate a set of attributes and display a common error (not related to particular attribute) as described here
I have created a class that extends yii\validators\Validator in which I need to validate a date composed from multilple attributes, in my validateAttribute($model, $attribute) function I created the date and validate in this way:
$date = "$year-$month-$day";
$dateValidator = new DateValidator();
$dateValidator->format = 'php:Y-m-d';
if(!$dateValidator->validate($date)){
$model->addError('*', "Date $date is not a valid date");
}
In my view I display the geral error in this way (I am using twig view template engine):
However when my date is validated the server raise an exception
name: Exception
message: Attribute name must contain word characters only.
code: 0
type: yii\base\InvalidArgumentException
file: /var/www/apache/plurima.snake.lappi.virt/vendor/yiisoft/yii2/helpers/BaseHtml.php
line: 2240
It seems like the * character in the addError function are not recognized as a general error and Yii2 complains because the attribute names cannot contain special characters… what am I doing wrong?
The first parameter of addError must be the name of an attribute, and * is not considered to be a valid attribute name. You have to select one of the attributes that make up the date, i.e., year, month or day. I think day would be a decent selection for it.
Otherwise you could define an additional virtual attribute of date that will receive the error message. In that case you would need to tweak your form a bit to include that virtual attribute.
So, your original code should work as expected. I don’t know what’s wrong with it.
The exception is thrown in BaseHtml::getAttributeValue($model, $attribute), and I wonder where this method is called from. Could you check the stack trace?
I see. The call of Html::getInputId can throw an exception when the model has a validation error whose $attribute is *.
I think you should report an issue.
In the meantime, you might try using some non-existing attribute name in place of *, something like `date_error’.
Thank you @softark I created another attribute and declared as hidden input in my view, inside the active form, and manage to solve in this way. Thanks also for the issue report suggestion, I think I will soon.