Issues related to afterSave() method

hi guys

I have to models user and expense. I wanted to change the balance field in my user model when i am creating any expense in my expense model. here is the code


protected function afterSave()

	{

		if (parent::afterSave())

			{

			$bal=User::model()->findByPk(Yii::app()->user->id);

			//Yii::trace($bal->balance);

			$bal->balance = ($bal->balance - $this->amount);

			//Yii::trace($bal->balance);

			$bal->save();	

			}	

		else

			return false;	

	}

I went through all the previous issues for afterSave(), I tried afterSave(false) as well and saveAttributes also but my User model is not getting saved. Although the trace statement give correct result. The only thing is it is not saving the changed value into the user model.

Use save(false) to skip validation.

/Tommy

Why you put parent::afterSave() in condition??? Its return type is void.

http://www.yiiframework.com/doc/api/1.1/CActiveRecord#afterSave-detail

Try this:




protected function afterSave()

{

    $bal = User::model()->findByPk(Yii::app()->user->id);

    $bal->balance = ($bal->balance - $this->amount);

    $bal->save(false);

    parent::afterSave();

}



I tried that nothing happened. Still not able to save. :(

I edited my previous post, because there’s really no need to check if user exists. It is currently logged in user :)

Just my coding habit to always check for proper data :)

Also I added false because you don’t need to run validation. Only you are assigning new value to balance.

It is working now with little modification in this code i.e


$bal->save(false);

. Thanks you very much :)

You’re welcome! ;)

Ya it is very fine. Thanks a lot :)