Yii2: unique validator does not show custom message

Created on 13 Aug 2016  路  7Comments  路  Source: yiisoft/yii2

What steps will reproduce the problem?

when i define unique rule for multiple fields like:
[['type_id', 'title'], 'unique', 'targetAttribute' => ['type_id', 'title'], 'message' => Yii::t('app', 'Duplicated Data Entries.')],

What is the expected result?

i expecte to show Yii::t('app', 'Duplicated Data Entries.')

What do you get instead?

but default message is shown.

Additional info

when i remove "'targetAttribute' => ['type_id', 'title']," part my message has been shown but it is not the rule i want.

| Yii version 2.0.9
| PHP version 5.5.34
| Operating system windows 10

BC breaking bug

Most helpful comment

You should use comboNotUnique for error message in this case: https://github.com/yiisoft/yii2/blob/master/framework/validators/UniqueValidator.php#L70

All 7 comments

You should use comboNotUnique for error message in this case: https://github.com/yiisoft/yii2/blob/master/framework/validators/UniqueValidator.php#L70

thanks a lot it works.

@rob006 thanks for noting the BC break, not sure if we should introduce a fallback in the code to avoid the break or just add a note to the UPGRADE docs. @yiisoft/core-developers opinions?

@cebe I think that both messages should be configured by message property and comboNotUnique should be deprecated. Another property for message is just confusing and does not give any benefit. So :+1: for fallback, but for comboNotUnique uses.

I suggest the following fallback:

    public function init()
    {
        parent::init();
        if ($this->message === null) {
            if (is_array($this->targetAttribute)) {
                $this->message = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
            } else {
                $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
            }
        }
    }

And use the appropriate placeholders with the $message depending on what is targetAttribute

@SilverFire If comboNotUnique is set you should use it as default value for message.

@rob006 yepp, you're right :)

Was this page helpful?
0 / 5 - 0 ratings