我通过所有条目的校验和(md5()来验证一个新条目,看看该条目是否已经存在,并且工作正常,但是对于规则消息,我想显示条目"name"而不是唯一属性,如下所示:
public function rules() {
return array_merge(parent::rules(), array(
array('checksum', 'unique', 'message' => 'Store ' . $this->name . 'already exists on the database.'),
));
}
rules函数总是将$this->name设为空。什么好主意吗?
CUniqueValidator
在错误消息中支持自定义{value}
占位符,但不幸的是,它映射到正在验证的属性值(校验和),因此您不能使用它来显示名称。
另外,当rules()
被框架调用时,当前实例仍然是空的,所以上面写的$this->name
将始终具有name
属性的默认值——通常是null
。
得到你想要的唯一方法是扩展CUniqueValidator
,也许像这样:
class ExtendedUniqueValidator extends CUniqueValidator
{
public $additionalPlaceholders;
protected function addError($object,$attribute,$message,$params=array())
{
$params['{attribute}']=$object->getAttributeLabel($attribute);
$additional = array_filter(
array_map('trim', explode(',', $this->additionalPlaceholders)));
foreach ($additional as $attributeName) {
$params['{'.$attributeName.'}'] = $object->$attributeName;
}
$object->addError($attribute,strtr($message,$params));
}
}
然后可以用
定义验证规则'additionalPlaceholders' => 'name', // comma-separated list
'message' => 'Store {name} already exists on the database.',
被验证的对象在rules函数中是不可访问的,取而代之的是Yii中的验证器使用占位符机制。
我认为获得您想要的行为的正确方法是扩展uniqueValidator,以在新的或现有的占位符中包含对象名称