Onchange Field

Hello!

I have a field user_name. If i am changing the field then i have to change field "user_log" and append some text.

user_log will be look like:

How can i track changes of user_name?

use beforeSave() method in your model

Hi

ovverides beforeSave or afterSave method

to do that check this

http://www.yiiframework.com/doc/blog/1.1/en/post.create

How will i know about changed field?

You could save the attribute to another variable before changed


private $old_attr1;

public function afterFind()

{

    $this->old_attr1 = $this->attr1;

}


protected function afterSave()

{

    parent::afterSave();

    if ($this->old_attr1 !== $this->attr1) { //what you want to do }

}



Can I change $this->attr1?

I failed to do this:




protected function afterSave()

{

    parent::afterSave();

    if ($this->old_attr1 !== $this->attr1) { $this->attr1=$this->attr1+' text'; }

}



Hi

If you want just log the changes then




protected function afterSave()

{

    parent::afterSave();

    if ($this->old_attr1 !== $this->attr1) { $this->attr1 = $this->attr1 . ' text'; //or $this->attr1 = $this->old_attr1 . ' text';  //depending what you want to do... }

//some code to log

}



but if you want to do something to save in your database you should use beforeSave


protected function beforeSave()

{

    if(parent::beforeSave())

    {

        $this->attr1 = $this->attr1 . ' text'; //or $this->attr1 = $this->old_attr1 . ' text';  //depending what you want to do 

//some code to log...

        return true;

    }

    else

        return false;

}

Thanks for voting :)

But it does not work. Example:

Model:




class Product extends CActiveRecord

{

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	public function tableName()

	{

		return 'product';

	}




    public function beforeSave()

    {


        if(parent::beforeSave())

        {

            $this->p_name = 'another value';

            return true;

        }

        else

            return false;


    }

}



here is code which call the model




Product::model()->updateByPk(1,array('p_name'=>'This Value'));



But database saving value "This Value". Why if I tried to change it to "another value"?

What do I wrong?

update query

I do just the same

updateByPk is just a helper method and does not triggered beforeSave and afterSave methods like update method does, so use update method