Yii2覆盖字段()以在验证错误的情况下重命名字段

时间:2016-12-19 10:35:18

标签: rest api validation yii2 field

参考:http://www.yiiframework.com/doc-2.0/guide-rest-resources.html#overriding-fields

我重写字段()以重命名用户模型中的字段。

GET - 响应数据字段按预期重命名

POST - 验证错误字段名称未重命名

1。用户表列

public function rules()
{
    return [
        [['User_Name', 'Password', 'Auth_Token', 'User_Type_Id', 'User_Status_Id'], 'required'],
    ]
}

2。覆盖字段()

public function fields()
{
    return [
        'user_id' => 'User_Id',
        'access_token' => 'Auth_Token',
        'user_name' => 'User_Name',
        'user_type' => 'userType.User_Type_Name',
        'name' => 'userProfile.Fname',
    ];
}

3。获取用户数据(按预期重命名的字段)

[
  {
    "user_id": "1",
    "access_token": "123",
    "user_name": "kiran",
    "user_type": "Customer",
    "name": "customer"
  }
]
  1. 验证模型(不重命名错误字段名称)
  2.  [
        {
          "field": "User_Name",
          "message": "User  Name cannot be blank."
        },
        {
          "field": "Password",
          "message": "Password cannot be blank."
        },
        {
          "field": "Auth_Token",
          "message": "Auth  Token cannot be blank."
        },
        {
          "field": "User_Type_Id",
          "message": "User  Type  ID cannot be blank."
        },
        {
          "field": "User_Status_Id",
          "message": "User  Status  ID cannot be blank."
        }
    ]
    

1 个答案:

答案 0 :(得分:0)

  1. 使用getter / setter方法在用户模型中加载帖子数据。
  2. 参考:Yii2 REST create with fields()

    1. 覆盖addError()方法以更改错误字段名称

      hadoopFile -> groupByKey -> map