Perform calculations before recording in the BD

What better way to carry out an operation between two fields and save result to a third column? Must be made actionCreate or beforeSave? [b]

Columns:[/b]

value (user input)

commission (user input)

companys_revenue (just a field)

Example: value x commission = companys_revenue

I need to get the data that the user entered and apply the formula and write to the database

Depends on what you want to obtain.

If you put it in the controller on the create action it won’t run if the user update, maybe these filed once inserted, update is not allowed

If you put in beforeSave it is always runned does not matter which controller run it, it is the best place if you need to run it in several part of the code:

For example you insert update data via:

create and update action

API interface

command

cronjob

import data from file procedure

A third option is to put the calculation in a input validation method. If both input pass the validation , store the formula result in the column.

In this way, using scenario, you can chose if you want to perform the validation and therefore the calculation.

I did as follows:


	public function beforeSave($insert)

	{

    	if ($this->isNewRecord)

    	{

        	$companys_revenue = ($this->value*$this->commission_percent)/100;

        	$this->companys_revenue = abs($companys_revenue);


    	}

        	$companys_revenue = ($this->value*$this->commission_percent)/100;

        	$this->companys_revenue = abs($companys_revenue);

 

    	return parent::beforeSave($insert);

	}  

It seem that your formula is the same in both insert and update, therefore you do not need to check for if it is a new record.

Anyway if the save is an insert $insert parameter is true

It would be better and more readable like the following




public function beforeSave($insert)

{

	if (parent::beforeSave($insert)) {

    	$companys_revenue = ($this->value*$this->commission_percent)/100;

    	$this->companys_revenue = abs($companys_revenue);

    	return true;

	} else {

    	return false;

	}

}



yes… thanks man

Notice something? :)

Something new?

Like ‘$insert’ ?


	public function beforeSave($insert)

	{

    	if (parent::beforeSave($insert)) {


        	if($insert) {

           	// do your stuff

        	}

        	return true;


    	} else {

        	return false;

    	}

	}



The other way works, or not, but this is the good way of doing it.

@jacmoe even if your code is correct it does not do what Gustavo need.

Your code does the calculation only on insert.

Looking at the code Gustavo posted (even if it is wrong since on insert does the same calculation twice) it seem he need to do the calculation on both update and insert.

Roberto just that. The calculation needs to be done in both situations.

Thank you