This behavior encrypts passwords for your data model on-the-fly and handles the case of updating a record with a blank password (which usually means leave the password as-is):
class PasswordBehavior extends CBehavior
{
public $password_field = 'password';
public function attach($component)
{
$component->attachEventHandler('onBeforeSave', array(&$this, 'encryptPassword'));
$component->attachEventHandler('onBeforeValidate', array(&$this, 'validatePassword'));
}
public function validatePassword($event)
{
$sender = &$event->sender;
$password = $sender->{$this->password_field};
if($sender->isNewRecord && empty($password)) {
$sender->addError('password', 'Password cannot be blank');
return false;
}
return true;
}
public function encryptPassword($event)
{
$sender = &$event->sender;
$sender->{$this->password_field} = md5($sender->{$this->password_field});
return true;
}
}
It handles the case where the record is new, and triggers a validation error if the password is blank. I’ve yet to put in a password confirmation check, coming soon.