How to tell if model field is new

I have a users model with a password field. Obviously, I need to hash it but I can’t seem to figure out the best way to tell if the field is newly updated or loaded from the DB. I don’t want to rehash it! Using Doctrine 2 and Zend I could create setters for each field which would hash the password when it was set so it was never an issue. How is this accomplished with Yii? I can think of some hacks (like checking the string length, etc…) but I’m having this same issue with some other situations - like a serialized array.

Frankie

Ps… Im new to Yii and loving it so far. Rapid development is my new best friend. Sorry Zend.

I wrote a quick base class which calls a setter if it exists:


class BaseModel extends CActiveRecord {

	public function __set($name,$value)

	{

		if(method_exists($this, 'set' . $name))

		{

			$method = 'set' . $name;

			$this->$method($value);

		}

		else

		{

			parent::__set($name, $value);

		}

	}

}

In my model I use this method:


	public function setPassword($password)

	{

		$this->password = md5($password);

	}

You just re-implemented what’s already implemented in CComponent. :)

Any model with functions named setSomething and getSomething will set and get something.

You don’t need to do anything besides implementing those two functions.

Thanks!

in AR’s afterFind() method you can memorize the old attribute , and in afterSave() method compare the old attribute to the current value of the same attribute . hope this wiki help you How to log changes of ActiveRecords :lol:

The best way that I’ve found is to not let the user touch the password attribute at all. Instead, create an attribute directly in the model and then let the user enter that.

Then, you can modify the beforeSave() function to check if it’s been entered. If so, hash it into the regular password field.


class User extends CActiveRecord

{

    public $newPassword;


    protected function beforeSave()

    {

        // call parent first and check if valid

        if (!parent::beforeSave())

        {

            return false;

        }


        if ($this->newPassword)

        {

            $this->password = hash_function($this->newPassword);

        }


        return true;

    }

}