Php 在模型规则错误消息上显示另一个属性值

Php 在模型规则错误消息上显示另一个属性值,php,yii,Php,Yii,我通过一个校验和来验证一个新条目,该校验和是所有条目的md5(),以查看该条目是否已经存在并且工作正常,但是对于规则消息,我希望显示条目“name”,而不是unique属性,如下所示: public function rules() { return array_merge(parent::rules(), array( array('checksum', 'unique', 'message' => 'Store ' . $this->name . 'alr

我通过一个校验和来验证一个新条目,该校验和是所有条目的md5(),以查看该条目是否已经存在并且工作正常,但是对于规则消息,我希望显示条目“name”,而不是unique属性,如下所示:

public function rules() {
    return array_merge(parent::rules(), array(
        array('checksum', 'unique', 'message' => 'Store ' . $this->name . 'already exists on the database.'),
    ));
}

规则函数的$this->name始终为null。有什么想法吗?

规则函数中无法访问正在验证的对象,而Yii中的验证程序使用占位符机制


我认为获得所需行为的正确方法是扩展uniqueValidator,将对象名称包含在新的或现有的占位符中。

规则函数中无法访问正在验证的对象,而Yii中的验证程序使用占位符机制


我认为获得所需行为的正确方法是扩展uniqueValidator,将对象名称包含在新的或现有的占位符中。

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.',

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.',