Onchange Field


(Linux Serg) #1

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?


(Edwvee) #2

use beforeSave() method in your model


(Konapaz) #3

Hi

ovverides beforeSave or afterSave method

to do that check this

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


(Linux Serg) #4

How will i know about changed field?


(Konapaz) #5

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 }

}




(Linux Serg) #6

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'; }

}




(Konapaz) #7

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 :)


(Linux Serg) #8

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?


(Ankit Modi) #9

update query


(Linux Serg) #10

I do just the same


(Konapaz) #11

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