Trigger A Controller On An Aftersave Event In Model

Hi the procedure I want to fulfill is the following:

When the users updates a model, I want to check if there is a change in data. If there is, I want to send an informative email. The mail triggering happens in the controller.

After some reading, I end up using the afterSave procedure in combination with afterFind. Using these, I am checking the old values of attributes vs new values. But I don’ t know how to inform the controller that there is a change in the data in order to trigger the mail procedure.

1)Should I use an event, and in this case how the controller could notice the event that happens in model;

2)Is there a way from the controller to call the afterSave procedure of the model and get the response; (probably wrong)

For the moment I see that afterSave procedure is called in the update method of the model, but the update procedure does not check the response of afterSave procedure. So I cannot understand which object takes into consideration the response of the afterSave procedure.

If somebody has an idea, please help

The solution I followed is this:

first, create the after save procedure

	protected function afterSave() {

		if (!$this->isNewRecord) {

			$flag = false;

			$newattributes = $this->getAttributes();

			$oldattributes = $this->_oldattributes;

			foreach ($newattributes as $name => $value) {

				if (!empty($oldattributes)) {

					$old = $oldattributes[$name];

				} else {

					$old = '';


				if ($value != $old) {

					$flag = true;




			if($this->hasEventHandler('onAfterSave')) {

				$e = new CEvent($this, array("dataChanged" => $flag));



		} else {


			$this->onAfterSave(new CEvent($this));


Here I am checking if the attribute values have changed after an update, and then pass an event which has as a param, the boolean status.

Next make the controller to listen to this event by attaching the event handler in the initialization of the model

	public function init() {

		$contr = Yii::app()->getController();



And finally creating the method which will be executed to the controller in the controller class

	public function test($event) {

		$dataChanged = $event->params["dataChanged"];

		if ($dataChanged=='true')

			echo 'change';


			echo 'notChange';


You could also use CActiveRecordbehavior to listen to the afterSave event and send the email from there.


As I have said in the beggining the mail triggering happens in the controller. Otherwise, I would use the afterSave method itself to trigger the mail. As I have understand, the behavior feature is used mainly for multiple inheritance.