Question

I'm new to Yii framework so I'm trying to understand the way it is working. I have the following validation rules for a user creating form, now what I need is to check in afterValidation() method, if all the validation rules have passed an the hash the user password. What I don't know is, if Yii has a build-in method that returns true or false if the validation rules have passed or not.

 public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('email, password, username', 'required'),
            array('email, username, password', 'length', 'max'=>256),
            array('email, username', 'unique'),
            array('password', 'compare'),
            array('password_repeat', 'safe'),
        );
    }




 protected function afterValidate()
        {
            parent::afterValidate();
          if("VALIDATION RULES HAVE PASSED, ther is no error message")
{  
            $this->password = $this->encrypt($this->password);
}
        }
        public function encrypt($value)
        {
          return md5($value);
        }
Était-ce utile?

La solution

The method you should be using is $this->hasErrors() since your form validation has already been performed. The likely reason for the nesting error is due to it calling your afterValidate() after each $this->validate() since I would think this is called automatically if validation is performed and you just end up with an infinite loop

Autres conseils

Instead if putting anything in afterValidate(), which gets run in a validation cycle, I think you want to put your code in beforeSave().

beforeSave() will only be run if your validation rules run and don't have errors.

As a bonus: if you are just doing standard password stuff, consider using the Yii Password behavior. It will save you lots of time and has already been thoroughly checked by some of the best Yii programmers out there.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top