Php 显示来自模型验证规则的消息
我在访问由我的模型中的某个自定义规则生成的消息时遇到问题 在模型中:Php 显示来自模型验证规则的消息,php,yii,Php,Yii,我在访问由我的模型中的某个自定义规则生成的消息时遇到问题 在模型中: public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('active_yn', 'numerical', 'integerOn
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('active_yn', 'numerical', 'integerOnly'=>true),
array('user_name', 'length', 'max'=>20),
array('password', 'length', 'max'=>100),
array('full_name', 'length', 'max'=>150),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('user_id, user_name, full_name, active_yn', 'safe', 'on'=>'search'),
array('user_name', 'unique', 'on'=>'api_save, insert', 'message'=>'User already in system'),
array('user_name, full_name', 'required', 'on'=>'api_save', 'message'=>'Required field, {attribute}, is missing'),
);
}
在我的控制器里。这是一个REST接口
public function actioncreate(){
$user = new User();
$user->scenario = 'api_save';
// Try to assign POST values to attributes
if(isset($_POST)){
foreach($_POST as $key=>$value) {
// Does the model have this attribute? If not raise an error
if($user->hasAttribute($key)){
$user->$key = $value;
}else{
$var = array('status'=>500,'body'=>'Parameter <b>'.$key.'</b> is not allowed for model');
$send = new sendResponse($var);
}
}
}else{
$var = array('status'=>500,'body'=>'Parameters required for creation');
$send = new sendResponse($var);
}
if(!$user->validate()){
$str .= $user->message;
$var = array('status'=>500,'body'=>$str);
$send = new sendResponse($var);
}
$user->save();
$var = array('status'=>200,'body'=>CJSON::encode($user));
$send = new sendResponse($var);
}
公共函数actioncreate(){
$user=新用户();
$user->scenario='api_save';
//尝试将POST值指定给属性
国际单项体育联合会(国际单项体育联合会){
foreach($\发布为$key=>$value){
//模型是否具有此属性?如果没有,则引发错误
如果($user->hasAttribute($key)){
$user->$key=$value;
}否则{
$var=array('status'=>500,'body'=>Parameter'.$key.'不允许用于模型');
$send=新发送响应($var);
}
}
}否则{
$var=array('status'=>500,'body'=>'Parameters required for creation');
$send=新发送响应($var);
}
如果(!$user->validate()){
$str.=$user->message;
$var=array('status'=>500,'body'=>$str);
$send=新发送响应($var);
}
$user->save();
$var=array('status'=>200,'body'=>CJSON::encode($user));
$send=新发送响应($var);
}
如果模型未验证,我希望显示来自模型的消息。我已经尝试了getError
和getErrors
,但是我收到一个错误,说“错误未定义”
感谢您对可能是一个简单问题的帮助 经过进一步搜索,我找到了答案:
if($user->save() === false){
$str = '';
foreach ($user->errors as $value) {
$str .= $value[0]."; ";
}
$var = array('status'=>500,'body'=>$str);
$send = new sendResponse($var);
}else{
$var = array('status'=>200,'body'=>CJSON::encode($user));
$send = new sendResponse($var);
}
我跳过了验证步骤,只是保存了模型。如果它返回了false
,那么我就能够将$user->errors
作为数组或错误消息拉出来