Yii2 overriding fields() to rename fields in case

2019-07-25 08:51发布

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

I am overriding fields() to rename fields in User model.

GET - response data fields are renamed as expected

POST - validation error field names are not renamed

1. User table columns

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

2. overriding fields()

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. Get User data (fields renamed as expected)

[
  {
    "user_id": "1",
    "access_token": "123",
    "user_name": "kiran",
    "user_type": "Customer",
    "name": "customer"
  }
]
  1. Validate model (error field names are not renamed)
 [
    {
      "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条回答
Bombasti
2楼-- · 2019-07-25 09:45
  1. Using getter/setter methods to load the post data inside user model.

Ref: Yii2 REST create with fields()

  1. Overwriting addError() method to change error field name

    public function addError($attribute, $error = '') {
        $renamed_attr = $this->renamedFields($attribute);
        parent::addError($renamed_attr, $error);
    }
    
查看更多
登录 后发表回答