Hi,
How do I use the UniqueValidator as a standalone object.
I want to validate an attribute in a model to make sure it is unique but I do not want to do it in the model.
How do I use this class to do it in the controller outside of the model?
James.
Bizley
(Bizley)
April 24, 2015, 7:44am
2
Not sure but have you tried
$validator = new \yii\validators\UniqueValidator();
if ($validator->validateAttribute($model, $attribute) { // set model instance and attribute to check
// ok
} else {
// error
}
Bizley:
Not sure but have you tried
$validator = new \yii\validators\UniqueValidator();
if ($validator->validateAttribute($model, $attribute) { // set model instance and attribute to check
// ok
} else {
// error
}
validateAttribute returns void not boolean, so cannot be used.
Bizley
(Bizley)
April 25, 2015, 7:28am
4
Sorry, you are right.
But this should work:
$validator = new \yii\validators\UniqueValidator();
$validator->validateAttribute($model, $attribute);
if (empty($model->getErrors($attribute))) {
// ok
} else {
echo $model->getErrors($attribute);
}
Yes you are right, thanks.
I wonder why Yii just does not provide a solution for it though.