没有不值得去解决的问题,也没有不值得去学习的技术!

Custom Error Messages for Composite Field Uniqueness With unique in Yii 2

POST http://api.pcs-api.localhost/v1/config-columns?login_id=e56db1b43546a110431ac38409ed8e9e&login_tid=ccffd87b68171e8cb6c19f4bb8ccd775 , 422 response

1. The model class files in the /common/models directory are only generated by the Gii tool and serve as the common model data layer. \common\models\ConfigColumn.php contains the model’s validation rules.

PHP

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['group_id', 'code', 'name'], 'required'],
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['group_id', 'code', 'name'], 'string', 'max' => 32],
            [['group_id', 'code'], 'unique', 'targetAttribute' => ['group_id', 'code']],
            [['group_id', 'name'], 'unique', 'targetAttribute' => ['group_id', 'name']],
        ];
    }

2. The model class files in the /common/logics directory handle business logic. They inherit from the /common/models data layer and serve as the common model logic layer. \logics\ConfigColumn.php contains the model’s validation rules.

PHP

    /**
     * @inheritdoc
     */
    public function rules()
    {
        $rules = [
        ];
        $parentRules = parent::rules();

        return ArrayHelper::merge($rules, $parentRules);
    }

3. POST http://api.pcs-api.localhost/v1/config-columns?login_id=e56db1b43546a110431ac38409ed8e9e&login_tid=ccffd87b68171e8cb6c19f4bb8ccd775 , 422 response

JSON

{
    "code": 20004,
    "message": "Data validation failed: The combination \"015ce30b116ce86058fa6ab4fea4ac63\"-\"wxcq\" of Group ID and Code has already been taken."
}

JSON

{
    "code": 20004,
    "message": "数据验证失败:The combination \"015ce30b116ce86058fa6ab4fea4ac63\"-\"wxcq\" of 租户ID and 栏目代码 has already been taken."
}

4. Analyze the source code: \vendor\yiisoft\yii2\validators\UniqueValidator.php

PHP

        if (is_array($this->targetAttribute) && count($this->targetAttribute) > 1) {
            // fallback for deprecated `comboNotUnique` property - use it as message if is set
            if ($this->comboNotUnique === null) {
                $this->message = Yii::t('yii', 'The combination {values} of {attributes} has already been taken.');
            } else {
                $this->message = $this->comboNotUnique;
            }
        } else {
            $this->message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
        }

5. ‘The combination {values} of {attributes} has already been taken.’ does not exist in the framework’s built-in Simplified Chinese language pack, as shown in Figure 1.

'The combination {values} of {attributes} has already been taken.' does not exist in the framework's built-in Simplified Chinese language pack
Figure 1

6. ‘The combination {values} of {attributes} has already been taken.’ exists in the framework’s built-in English language pack, but the source language is not translated, as shown in Figure 2.

'The combination {values} of {attributes} has already been taken.' exists in the framework's built-in English language pack, but the source language is not translated
Figure 2

7. Since the model class files in the /common/models directory are only generated by the Gii tool and cannot be edited again, custom error messages can only be implemented in \logics\ConfigColumn.php. Note: If the rules() in \common\models\ConfigColumn.php change, \logics\ConfigColumn.php must be adjusted accordingly.

PHP

    /**
     * @inheritdoc
     */
    public function rules()
    {
        $rules = [
            [['group_id', 'code'], 'unique', 'targetAttribute' => ['group_id', 'code'], 'message' => Yii::t('app', 'The combination {values} of {attributes} has already been taken.')],
            [['group_id', 'name'], 'unique', 'targetAttribute' => ['group_id', 'name'], 'message' => Yii::t('app', 'The combination {values} of {attributes} has already been taken.')],
        ];
        $parentRules = parent::rules();

        unset($parentRules[3], $parentRules[4]);

        return ArrayHelper::merge($rules, $parentRules);
    }

8. Edit \common\messages\zh-CN\app.php

PHP
<?php
return [
    'The combination {values} of {attributes} has already been taken.' => '组合{attributes}的值"{values}"已经被占用了。',
];

9. Edit \api\messages\zh-CN\app.php

PHP
<?php
return [
    'The combination {values} of {attributes} has already been taken.' => '组合{attributes}的值"{values}"已经被占用了。',
];

10. POST http://api.pcs-api.localhost/v1/config-columns?login_id=e56db1b43546a110431ac38409ed8e9e&login_tid=ccffd87b68171e8cb6c19f4bb8ccd775 , 422 response, as shown in Figure 3.

POST http://api.pcs-api.localhost/v1/config-columns?login_id=e56db1b43546a110431ac38409ed8e9e&login_tid=ccffd87b68171e8cb6c19f4bb8ccd775 , 422 response
Figure 3
JSON

{
    "code": 20004,
    "message": "Data validation failed: The combination \"015ce30b116ce86058fa6ab4fea4ac63\"-\"wxcq\" of Group ID and Code has already been taken."
}

JSON

{
    "code": 20004,
    "message": "数据验证失败:组合租户ID and 栏目代码的值\"\"015ce30b116ce86058fa6ab4fea4ac63\"-\"wxcq\"\"已经被占用了。"
}

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系