Gridview Get Selected Colum

Hi all,

i want to know how to get checked Column and and pass it to controller.

How can i get the checked column using jquery to make a calculation.

Thanks for the help :D




GridView::widget([

        'dataProvider' => $dataProvider,

        'layout' => '{items}',

        'columns' => [

            ['class' => 'yii\grid\CheckboxColumn'],

            'id',

            'name',

            'beschreibung:ntext',

            'preis',

            'anzahl',

        ],

    ]);



You cannot get a checked column. I presume you mean you want to get SELECTED ROWS in a CheckboxColumn.

Something like this…




// javascript to call for your button on 

// the view - which on click - will process the 

// action for all selected rows

var keys = $('#grid').yiiGridView('getSelectedRows');

$.post({

   url: vUrl, // your controller action

   dataType: 'json',

   data: {keylist: keys},

   success: function(data) {

      alert('I did it! Processed checked rows.')

   },

});


// your controller action (php code)

public function actionProcessSelected() {

    if (isset($_POST['keylist'])) {

        $keys = \yii\helpers\Json::decode($_POST['keylist']);

        // you will have the array of pk ids to process in $keys

        // perform batch action on these keys and return status

        // back to ajax call above

    }

}



Thank you amazing…

karthik i am trying to calculate values out of selected rows like total price… using jquery.

can you give me an example code for that




$('element').one('click',function()

{

    

});

PS: i am fan of your widgets and plugins… amazing work you have done.

In your view button action, include a javascript similar to one below:




$('element').one('click',function() {

    var keys = $('#grid').yiiGridView('getSelectedRows'); // returns an array of pkeys, and #grid is your grid element id

    $.post({

       url: '/site/calculate-total', // your controller action

       dataType: 'json',

       data: {keylist: keys},

       success: function(data) {

          if (data.status === 'success') {

              alert('Total price is ' + data.total);

          }

       },

    });

});



In your controller (php code for action similar to below):




public function actionCalculateTotal() {

    if (isset($_POST['keylist'])) {

        $keys = \yii\helpers\Json::decode($_POST['keylist']);

        if (!is_array($keys)) {

            echo Json::encode([

                'status' => 'error',

                'total' => 0

            ]);

            return;

        }

        $total = 0;

        // you could alternatively write a single query using 

        // SQL IN CONDITION, instead of loop below to fetch the total 

        // from DB in ONE SINGLE fetch from the DB.

        foreach ($keys as $key) {

           $model = YourSourceModel::findOne($key);

           // get total price from your model's column e.g. price

           $total += !empty($model->price) ? $model->price : 0;

        }

        echo Json::encode([

            'status' => 'success',

            'total' => $total

        ]);

    }

    echo Json::encode([

        'status' => 'error',

        'total' => 0

    ]);

}



sorry for asking dumb question, but i have not used jquery with yii

how can i implement jquery in yii2?? any documentation

use yii\web\JqueryAssets; ???

In your view layout file add at the top




\yii\web\JqueryAsset::register($this);



You can also register the above asset as a dependency within an AssetBundle. In yii advanced app, this is included by default via the frontend\assets\AppAsset.php (check this line):




public $depends = [

        'yii\web\YiiAsset',

//

]



The YiiAsset includes JQueryAsset as a dependency.

my code look like this now:

ontop :


yii\web\JqueryAsset::register($this);




<script type="text/javascript">

	$(document).ready(function(){

		$("input[type=checkbox]").click(function(){

		      var keys = $('#grid').yiiGridView('getSelectedRows');

		      alert(keys);

			    

		});


	});

</script>



just for testing but nothing is happening when i select. no alert

You may need to debug your code using Firebug or some tool to understand where the error is received. BTW… your JS alert will not return a string because, the [font="Courier New"]var keys[/font] is an array.

this is working… when i use the var keys line then even this is not working… even when i do not alert keys;


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

	<script type="text/javascript">

		 $(document).ready(function(){

			 $("#w1 input[type=checkbox]").click(function(){

			 	

			    //var keys = $('#grid').yiiGridView('getSelectedRows');

			    alert('om');

			    

			  });


		});

	</script>

Check your DOM element identifiers.

You seem to be using a wrong grid id - change #grid to #w1 for your example - like below:




$(document).ready(function(){

    $("#w1 input[type=checkbox]").click(function(){

        var keys = $('#w1').yiiGridView('getSelectedRows');

        alert(keys[0]);

    });

});



The #grid I had provided earlier was an example for grid id to be changed as per what is there in your environment.

coooool… okay now working but without this line its not working.


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

how is to get if two or three are selected ?

yii2 is made so clever but this cannot be the way to calculate the price from a gridview by selecting :blink:

I am not sure you understood at all. The function $(’#w1’).yiiGridView(‘getSelectedRows’) returns an array of the primary keys (which are selected through checkbox in the grid). Please check the code I shared earlier in this page - the variable keys is an array. You need to read/loop through this array in your controller action (passed by an ajax call) to do whatever you want (read based on selected pkeys from db, and generate total or do any calculation).

Dear Kartik! I’m having serious problems with the URL of your piece of code. I’m getting always the same URL’s error:


POST http://localhost/cngrx/web/index.php/ponenciaresumen/[object%20Object] 404 (Not Found) 

It seems the code generete always this pattern: path/myController/[object%20Object]

It’s doesn’t matter wich url i set, the code generete always the same url, and its not what i need. My code is this:




<script>

  $(document).ready(function(){

    $('#MyButton').click(function(){

       

       var keys = $('#w1').yiiGridView('getSelectedRows');

        $.post({

           url: 'myController/myAction', 

           dataType: 'json',

           data: {keylist: keys}

         

        });

    });

  });

</script>



I’ve tried with absolutly url, and relatives one, but not. How can it be??

This is my action in myController:


 public function actionMyAction(    ) {

    if (isset($_POST['keylist'])) {

        $keys = \yii\helpers\Json::decode($_POST['keylist']);

        

        // you will have the array of pk ids to process in $keys

        // perform batch action on these keys and return status

        // back to ajax call above

    }

}

Thanks for advance!

This code does not work I get this error :

POST http://localhost/yii2immo/advanced/frontend/web/[object%20Object] 404 (Not Found)jQuery.ajaxTransport.send @ jquery.js:8630jQuery.extend.ajax @ jquery.js:8166jQuery.each.jQuery.(anonymous function) @ jquery.js:8311(anonymous function) @ index.php?r=bien%2Flisteaffecter:468jQuery.event.dispatch @ jquery.js:4435jQuery.event.add.elemData.handle @ jquery.js:4121

we have similar similar problem.

this is my code.

index in coutries table




    <?= GridView::widget([

        'dataProvider' => $dataProvider,

        'filterModel' => $searchModel,

        'columns' => [

            ['class' => 'yii\grid\CheckboxColumn'],


            'id',

            'name',


            ['class' => 'yii\grid\ActionColumn'],

        ],

    ]); ?>





<?php 

$script = <<< JS




    $("#w0").on('click',function(){

        var keys = $('#w0').yiiGridView('getSelectedRows');

        $.post('index.php?r=countries/calculate-total', {keylist : keys}, function(data)

        {

             var data = $.parseJSON(data);


                alert('total price is ' + data.total);

            });




        });


JS;

$this->registerJs($script);

?>



my controller in countries table


    public function actionCalculateTotal()

    {

        if (isset($_POST['keylist'])) {

            $keys = Json::decode($_POST['keylist']);

            if (!is_array($keys)) {

                echo Json::encode(['total' => 0]);

                return;}

            $total = 0;

            foreach ($keys as $key) {

                $model = Countries:: findOne($key);

                $total += !empty($model->id) ? $model->id : 0;

            }

            echo Json::encode([

                'total' => $total

                ]);

        }

        echo Json::encode([

            'total' => 0

            ]);

    }

i get this error in my firebug <pre>Exception ‘yii\base\InvalidParamException’ with message 'Invalid JSON data.&#039

tnx, I already solve it.

Hi,

I’m trying to follow your code but I get this error

"<pre>Exception ‘yii\base\InvalidParamException’ with message 'Invalid JSON data.&#039

; "

Here is my JS code from the view file

&lt;?php


&#036;this-&gt;registerJs(


        &quot;&#036;('#btnPostRecords').one('click',function() {

var keys = $(’#gridConsolidation’).yiiGridView(‘getSelectedRows’);

$.post({

url: ‘index.php?r=gac-data-trxdet-u/post-records’, // your controller action

dataType: ‘json’,

data: {keylist: keys},

success: function(data) {

  alert('I did it&#33; Processed checked rows.')

},

});

});

&quot;


);


?&gt;

And here is my controller action code

public function actionPostRecords() {


    if (isset(&#036;_POST['keylist'])) {


        //echo 'hapa';

// $keys = \yii\helpers\Json::decode($_POST[‘keylist’]);

        &#036;keys = &#092;yii&#092;helpers&#092;Json::decode(&#092;Yii::&#036;app-&gt;request-&gt;post('keylist'));


        // you will have the array of pk ids to process in &#036;keys


        // perform batch action on these keys and return status


        // back to ajax call above            


    }





    return TRUE;


}

Any help will be much appreciated. Thanks

@Kartik can you give example of inserting SELECTED ROWS to another table, where the other table has similar fields to the current table.