本文介绍了Yii2覆盖fields()以在验证错误的情况下重命名字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
参考: http://www.yiiframework .com/doc-2.0/guide-rest-resources.html#overriding-fields
我要重写fields()以重命名用户模型中的字段.
I am overriding fields() to rename fields in User model.
GET-响应数据字段已按预期重命名
GET - response data fields are renamed as expected
POST-验证错误字段名称未重命名
POST - validation error field names are not renamed
public function rules()
{
return [
[['User_Name', 'Password', 'Auth_Token', 'User_Type_Id', 'User_Status_Id'], 'required'],
]
}
2.覆盖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.获取用户数据(字段已按预期重命名)
[
{
"user_id": "1",
"access_token": "123",
"user_name": "kiran",
"user_type": "Customer",
"name": "customer"
}
]
- 验证模型(错误字段名称未重命名)
- 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."
}
]
推荐答案
- 使用getter/setter方法将帖子数据加载到用户模型中.
-
覆盖addError()方法以更改错误字段名称
Overwriting addError() method to change error field name
public function addError($attribute, $error = '') {
$renamed_attr = $this->renamedFields($attribute);
parent::addError($renamed_attr, $error);
}
这篇关于Yii2覆盖fields()以在验证错误的情况下重命名字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!