Sum of Several Fields

Dear Yii users,

I am facing a problem of inserting a data into a field. This field is is a sum from several fields in the same table. It should be working for new entry and also update.

Am I to create beforeSave() function in model? Or should I use afterSave(), grab the fields to add and insert into a field?

Example: A is the sum of fields B, C and D (I need to insert this into a field)

Any guidance is appreciated.

Thank you.

Before saving makes more sense. If you save first and then change the field, you’d have to save again.

You should use beforeSave(). In case of afterSave, you will need to save model again which in turn will make recursive calls to afterSave which will cause troubles for you.

Understood that beforeSave() will be the right direction, but how should I code to get the sum of the related fields? It should be in model, right?

I will need to insert to database.

Thank you.

Yes beforeSave is in model so your code for getting sum of fields also goes in model

I have managed to test like this.

	public function beforeSave() {


            if ($this->isNewRecord) {

                $this->salary = 1+1; //to edit

                $this->salary = $this->salary;

            } else {

                $this->salary = 2+2; //to edit


            return true;

        } else  {

            return false;



Creating a new record or updating works fine. My main question is how do i actually get the values from a form and add it? It needs to sum up and save in the database field.

Have you read the guide?

Thanks for the heads up. Managed to get it working now.

Thanks again.