How To Get Values From Gridview To Compute Total

Is there a way to get the values from certain gridview column to get its sum and display it in form?

I wanted to display the sum of all items (amount) in gridview, into the textfield on the form.

Can jQuery handle it? Any help is greatly appreciated. TIA.

I can’t figure out which jquery api should i use.

here’s my code

view




jQuery(function($) {


	$(document).ready(function(){

	        $("#Purchase_total").load(function(){

	        $.ajax({

	            url: "<?php echo $this->createUrl('/po/local/purchase/updateTotal', array('id'=>$childModel->po_number)); ?>",

	            data: $(this).serialize(),

	            type: "post",

	            dataType: "json",

	            success: function(data) {

	                 if (data.status === 'failure') {} 

	                 else {

	                     $("#Purchase_total").val(data.total);    

	                 }

	            }

	        });

	        });


	});

});



controller




	public function actionUpdateTotal($id){

		$curr_amount = 0;		

		if (isset($id)) {

			$purchaseModel = self::loadModel($id);

			if ($purchaseModel !== null) {

				$purchaseDetails = new PurchaseDetails('searchDetails($id)');

				if($purchaseDetails!==null){

					foreach ($purchaseDetails as $dtl) {

						$curr_amount += $dtl->amount;

					}

				}

				$purchaseModel->total = $curr_amount;

				if ($purchaseModel->save(false)) {

					$result = array(

						'status'=>'success',

						'total'=>$curr_amount,

					);

				}

				else {

					$result = array(

						'status'=>'failure',

						'po_number'=>$id,

					);

				}

			}

		}

		echo CJSON::encode($result);

	} 



Dear Friend

I hope the following is helpful to you.

Put the following code at the end in view file(admin.php)




//"columnCount"->script name

//"brand-grid"->id of grid view of Model Brand.

//2->third column in the grid.


Yii::app()->clientScript->registerScript('columnCount','

var els=$("#brand-grid").yiiGridView("getColumn",2 );

var total=0;

$.each(els,function(i,j){

	total+= parseFloat(j.textContent);

	});

	$("#count").val(total);

')

?>

<input type="text" id="count" placeholder="get the total value of third column" />



Will this run every reload of the page?

I tried it, however it displayed NaN in the textfield.

just to clarify, the number 2 signifies the column number of which the values will be getting?

Thanks for the effort.

EDIT:

It’s now working however i need to refresh the window before it will display the correct value, is there a jquery function to refresh the textfield?

Found out that the column number starts with 0.

THANKS!

Dear Friend

Number 2 means 3rd column of the grid which contain numerical values.

You can put the number as 0 and it will come with the total of column id.(first column).

I edited my reply. :D

Bonjour coy_coy

J’ai eu un problème similaire pour calculer le montant total des dons pour un projet sur lequel je travaille. Pour ma part, j’ai résolu ce problème en cuisinant le pied d’une colonne de type numérique.

Dans la vue ou se situe le gridview, j’ai ajouté un pied dans la colonne intituléé ‘montant’ à l’aide du paramètre ‘footer’. J’ai créé une méthode getTotalDons($dataprovider) qui permet de calculer le montant total pour les dons. Cette méthode retourne le total à partir du ‘dataprovider’ ainsi, le gridview affiche le total selon les critères de recherche.


# protected\views\tbldons\admin.php

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

	'id'=>'tbldons-grid',

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

	'filter'=>$model,

	'columns'=>array(

		'iddon',

		'idmembres',

                'solliciteur.prenom',

                'solliciteur.nom',

		'idfaculte',

                'faculte.faculte',

		'montant',

                array('name'=>'montant',

                      'type'=>'text',

                      'footer'=>Tbldons::model()->getTotalDons($model->search())),


                array ('header' => 'Reçu',

                    'value'=>'($data->recu == 1)? "OUI" : "NON"',),

                'date_reception',

		'mode_versement',

                

		array(

			'class'=>'CButtonColumn',

		),

	),

)); ?>

 

Dans le modèle j’ai créé une méthode getTotalDons($dataprovider) pour récupérer les données du ‘$dataprovider’. À l’aide d’une boucle simple foreach et d’un accumulateur, j’ai fait le total et ajouté une balise html pour appliquer un style particulier au résultat.


      #  protected\models\Tbldons.php

        public function getTotalDons($dataprovider){ 

          $dataprovider->setPagination(false);          

          $rows = $dataprovider->getData();          

          $total = 0;

          foreach ($rows as $don){

              $total += $don['montant'];

          }           

            $total = "<span class=\"csstotaltag\">".sprintf("$%0.2f",$total)."</span>";

            return $total;

        }