简体   繁体   中英

$model->validate() always return false

I read similar topics of this problem, but I don't found solution.I have a form which load via ajax. When all data is valid, they don't save in database and show me validate error in console.in my User model I ** set return parent::beforeSave(); in beforeSave method set return parent::beforeSave(); in beforeSave method ** Here is my action:

          public function actionRegister()
{       
                $model = new RegistrationForm;
                if(isset($_POST['ajax']) && $_POST['ajax']==='register-form')
                {
                    $this->ajaxValidate($model);
                }
                if(isset($_POST['RegistrationForm']))
                {
                    if($model->validate())
                    {
                     $model->attributes =  $_POST['RegistrationForm'];
                     $user = new User;
                     $user->attributes = $model->attributes;
                     if($user->save())
                        echo 1;
                    }else{
                          $errors = $model->getErrors();
                            var_dump($errors);
                            exit;
                    }
                }
                 $this->renderPartial('register', array('model' => $model),false,true);
     public function ajaxValidate($model)
    {   
                echo CActiveForm::validate($model); 
                Yii::app()->end();     
    }

you have not set model's attributes and trying to do validation. correct it as ,set attributes before validation by :-

$model->attributes =  $_POST['RegistrationForm'];

use above statement before:-

if($model->validate())

I just move

$model->attributes =  $_POST['RegistrationForm'] 

and set before

if($model->validate())

You called $model->validate() without setting any values to the attributes of class RegistrationForm .

validate works this way:

You have a class RegistrationForm and a required attribute fooField .

class RegistrationForm extends \CModel
{
    public $fooField;

    public function rules()
    {
        return [
          ['fooField', 'required']
        ];
    }
}

When RegistrationForm is called by another class, let's say Bar :

class Bar
{
    public function actionRegister()
    {
        $form = new RegistrationForm();
        $form->validate(); // This will return false since `RegistrationForm->fooField` is required.

        $form->fooField = 'Some value';
        $form->validate(); // This will return true since `RegistrationForm->fooField` has a value.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM