password hashing before save

Just wondering where you guys typically do your password hashing in your User model.

I was thinking that onAfterSave() would be the best place to do it, but then I was thinking about if an admin modifies a User record – you don’t want the password rehashing if he hasn’t changed it.

thoughts? :D

See here:

thanks Mike, a simple solution is usually the best! :g:

I have resolved this a bit different:

public function beforeSave() {

     if ($this->isNewRecord) // <---- the difference


     return true;



But this way you overwrite any existing password in db, even if the password field is empty.

$hash = new CSecurityManager;


It will be not empty, because beforeSave is after the execution of required validation.

Just hash for the new records. For update the password, I usually do it in another specific form.

In this case it works, of course. I usually use the same model also for update forms where an empty password field indicates "no change".