2012-07-01 2 views
0

Im возникли проблемы с доступом сообщения, порожденными некоторыми пользовательскими правилами в моей модели ..Дисплей Сообщение от модели Validation Rule

В модели:

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); 
    } 

Если модель не тестирует я хочу, чтобы отобразить сообщения из моей модели. Я пробовал getError и getErrors, но я получаю сообщение об ошибке: _error не определен.

Спасибо за помощь в том, что, вероятно, простой вопрос.

ответ

1

После еще некоторых поисков я нашел ответ:

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 в качестве массива или сообщения об ошибках