创建验证器的最佳方法是检查模型值是否唯一,但它不返回false - 它只显示消息"值已经存在" (我仍然可以保存模型)?
答案 0 :(得分:1)
Validators usually don't return boolean values, they add errors for given model attribute(s).
One of the ways (with minimal completions) will be using built-in UniqueValidator and saving without running validation.
At first call $model->validate()
to fill model with errors.
You can use $model->validate('fieldName')
to validate only needed field.
Then call $model->save(false)
or $model->save('fieldName')
(for just one field).
This will prevent validation before saving and model values will be saved "as is".
Another way for just saving one attribute without triggering events, etc. will be using updateAttributes
after calling validate()
:
$model->updateAttributes(['fieldName' => 'fieldValue']);