auto SUM

Hi.

i’m using v1.1.5 to create my 1st yii application and i can’t find an example for my needs.

i have a table Goods where i ned to insert products.

nr of products = X

price per product = Y

i want to auto SUM the total value into the filed Total value which is equal to Z = X * Y

this is the form for creating new product

then when i view all the products i want to have a final raw that sums all the "total values" which is S = Z1 + Z2 +… Z100

could someone give me some hints ?

Thanx in advance

I think we can do it by model

But we need more information from yii experts.

i have solve it very simple into the controller

public function actionCreate()

{


	$model=new Marfuri;





	// Uncomment the following line if AJAX validation is needed


	// $this->performAjaxValidation($model);





	if(isset($_POST['Marfuri']))


	{			


		[color="#FF0000"]// calculeaza valoarea pentru "valoare_stoc"


		$_POST['Marfuri']['valoare_stoc'] = $_POST['Marfuri']['in_stoc'] * $_POST['Marfuri']['pret_vanzare'];[/color]


		


		$model->attributes=$_POST['Marfuri'];


		if($model->save())


			$this->redirect(array('view','id'=>$model->id));


	}





	$this->render('create',array(


		'model'=>$model,


	));


}

If you want to keep that logic on the model end, you could add a method to your model which does the calculation.




    // Add private property to model

    private $_valoare_stoc;




    public function getValoare_Stoc()

    {

        if ( $this->_valoare_stoc === null )

        {

           $this->_valoare_stoc = $this->in_stoc  * $this->pret_vanzare;

        }

        return $this->_valoare_stoc;

    }



Then, whenever you need it in your controller or anywhere, simply:




   echo $model->valoare_stoc; // should show your calculated amount



Or, if you have an actual attribute for valoare_stoc, you could add a beforeValidate method for the model which triggers it calculating the valoare_stoc value.

Before Validate API Doc

Something like:




    protected beforeValidate()

    {

       $this->valoare_stoc = $this->in_stoc * $this->pret_vanzare;

       return parent::beforeValidate();

    } 



Whether you use before/afterValidate or beforeSave would depend on what your rules are for the three fields. Any of the three would do the job, but I’d probably best put it in the afterValidate so that you’re sure the in_stoc and pret_vanzare attributes are good before calculating off them.

We want to do it in the form of Create by using ajax.

Box 1 : contain quantity

Box 2 : contain Price

Box 3 : contain Total for Box 1 * box 2 ( by using Ajax in the same form )

How we can do it by using ajax as auto total ?

Thanks,

So you want it to auto-fill as part of the ajax form validation? Or you have a separate ajax call you wish to make?

If you want it to auto-validate while the form is being filled out, you could add a validator to your model like so:

Custom Validation API Doc




   public function rules(){

      ...

      array('valoare_stoc', 'calculate_total'),

      ...

   }


   public function calculate_total( $attribute, $params )

   {

       if( $this->in_stoc !== null && $this->pret_vanzare !== null )

          $this->valoare_stoc = $this->in_stoc * $this->pret_vanzare;

   }



Since you’re using it for a calculation, not a check, you don’t need to worry about flagging any error with it, assuming that you’ve got other validators before it which ensure that pret_vanzare and in_stoc are valid.

I want auto-fill in the form , when user fill box 1 & 2 , the result appears in the total Box.

Ok, so IMO use a totally javascript solution to populate the total field.

Add a listener to each of the other two fields, and then onchange call a function which calculates the value of each field into the total field. You don’t need to use an AJAX call to do it, just basic javascript.

Thank you Dana,

i’ll try what you explained to me nicely.

Thank you again but i still don’t know how to do it in Yii.

i have added your function into my model Marfuri.php.

Now i don’t know how to use


 echo $model->valoare_stoc; // should show your calculated amount 

in my form from _form.php so the calculated total should be submit to the mysql table.




<div class="row">

   <?php echo $form->labelEx($model,'valoare_stoc'); ?>

   <?php echo $form->textField($model,'valoare_stoc',array('size'=>10,'maxlength'=>10)); ?>

   <?php echo $form->error($model,'valoare_stoc'); ?>

</div>

and how do i use triggers in Yii forms fields to autofill the result with javascript ?

Thank you and please forgive my stupid questions.

Something along the lines of (there’s a more elegant solution I’m sure):

In the Controller where you render the create file or in the view:




// if not already covered

Yii::app()->clientScript->registerCoreScript('jquery');


// Put this common function in the head

Yii::app()->clientScript->registerScript("

  function totalValues()

  {

    var tot = $('#Marfuri_in_stoc').val() * $('#Marfuri_pret_vanzare').val();

    $('#Marfuri_valoare_stoc').val( tot );

  }

", CClientScript::POS_HEAD);


// This one will appear in the body

Yii::app()->clientScript->registerScript("

  $('#Marfuri_in_stoc').change( function(){ totalValues();} );

  $('#Marfuri_pret_vanzare').change( function(){ totalValues();} );

");



Dear all,

Im newbie in Yii, I got a problem and need your help. I have created webapp using yii, created model Credit from table in my DB, I have a column named ‘cost’ I want to make query “SELECT SUM(cost) FROM credit” in mysql it returns me result, but how to realize it using Yii and fetch result? THANK YOU for your answers. I have done this :

<?php

$connection=Yii::app()->db;

$sql=‘SELECT SUM(cost) from credit’;

$command=$connection->createCommand($sql);

$dataReader=$command->query();

foreach($dataReader as $row){

echo $row;

}

?>

but it returns me ‘Array’.

Shortly I need the sum of whole column in the bottom and display SUM.

Please help me

This should work:





$dbCommand = Yii::app()->db->createCommand('SELECT SUM(cost) AS credit_cost from credit');

$results = $dbCommand->queryAll();

$creditCost = $results[0]['credit_cost];




:)

thank you , it worked!

It looks like what I submitted had a minor typo. For the record, the sol’n is:




$dbCommand = Yii::app()->db->createCommand('SELECT SUM(cost) AS credit_cost from credit');

$results = $dbCommand->queryAll();

$creditCost = $results[0]['credit_cost'];



:)

i have corrected it. i got one more question:

$this->widget(‘zii.widgets.grid.CGridView’, array(

'id'=&gt;'gelen-kasa-grid',


'dataProvider'=&gt;&#036;model-&gt;search(),


'filter'=&gt;&#036;model,


'columns'=&gt;array(


	'id',


	'tarih',


	'aciklama',


	'uah',


	'usd',


	array(


		'class'=&gt;'CButtonColumn',


	),


),

)); ?>

while managing records I want to make "uah=usd*8" , it has to be done in mysql or php??

Thank you

You could do this in MySQL, by writing a view, no problem. However, in my experience, it’s best to use database tables, represented by active records, rather than views. Views can be represented as active records, but, unlike tables, the active records will not have all of the db relationships built in, so they’re less powerful. (That being said, I still have to use views when representing data with a lot of relationships, but I only do so for the “admin” view of the data. Views rarely work for the “update” view, because, with few exceptions, most views are not “updateable”.)

If you do this in php, I believe the code below will work. Take care that the value of the uah column is enclosed in tic marks as shown.





$this->widget('zii.widgets.grid.CGridView', array(

	'id'=>'gelen-kasa-grid',

	'dataProvider'=>$model->search(),

	'filter'=>$model,

	'columns'=>array(

		'id',

		'tarih',

		'aciklama',


	   array('name'=>'uah', 

		   'value'=>'$data->usd * 8'),

		'usd',

		array(

			'class'=>'CButtonColumn',

		),

	),

)); ?>




thank you very much!!! one more question, if i want to do the same in my model class? i mean if I enter USD value it automatically fills UAH with USD*8 into database table.

I wish you r not tired of my questions. I ask it on forums because i could not find solutions on internet.

again thank you…