Execute code if data is updated afterSave

I would like to execute a code if I detect that the user has changed details about


How can I implement this? How do I get after update the OLD and NEW values.

Your question is very vague so you will need to provide more information if you want a good answer.

It sounds like you need to set up a behavior but I can’t be sure base on what info you provided.


I want this


if ($this->current_occupant_number!=$this->previous_occupant_number) { 



Yes you need to implement a behavior, I will paste in some code from another project.

In your model you need to put in a behaviors function

public function behaviors()


        return array('SaveFileBehavior' => array('class' => 'SaveFileBehavior',

                                                 'nameField' => 'EventPhoto', // field in table which stores the file name

                                                 'pathField' => null, 

                                                 'saveName' => true, 







This points to a file "protected/components/SaveFileBehavior.php"

This file extends CActiveRecord

class SaveFileBehavior extends CActiveRecordBehavior

an example function within this file

public function afterSave($event)


        //If if the upload was successfull save it to disk

if ($this->upload != null)


// Name of the model that will be used to create the folder.

    $tableName = $event->sender->tableName();


    $uploadFile = Yii::app()->basePath . '/' . $this->folder . '/' . $tableName . '/' . $event->sender->$id . '/' . $this->originalName.'.'.$this->upload->getExtensionName();

    $path = dirname($uploadFile);

//if already it exists, to clean the directory of current image

if (is_dir($path))




   mkdir($path, 0777, true);

$assets = $this->webRoot .DIRECTORY_SEPARATOR. $this->assetsPath.DIRECTORY_SEPARATOR. $event->sender->$id;

if (is_dir($assets))



        } else {      

    mkdir($assets, 0777, true);


// save the uploaded file


// create a thumbnail


$thumb = Yii::app()->thumb;

$thumb->image = $uploadFile;


$thumb->directory = $path.'/';



// create a resized image


$resized = Yii::app()->resized;

$resized->image = $uploadFile;;


$resized->directory = $path.'/';



// copy into published directory




Check out this info in the guide.

hope this helps


I will not reuse this code elsewhere so there is no point for behavior for now. Thanks for sharing the code, the behavior.

I do have problems detecting if the value has actually been changed.

you could save your current attributes in a new property, use ActiveRecord::afterFind()

then compare old and new values in ActiveRecord::beforeSave() or ActiveRecord::afterSave()