CGridView and Forms


for the last couple of days i have tried to do the following , i have a form with a cgridview and i want to be able to select 1 or more of the rows and then press submit and retrieve the Ids on my controller, how can you get the selected rows off a gridview from that form and use them on a controller .

I am wondering the same thing.

In my controller I put this:

var_dump( $_REQUEST );

and prints this (in my case):

array(3) {   ["emailGroups"]=>   string(15) "Acknowledgments"   ["contact-grid_c0"]=>   array(2) {     [0]=>     string(1) "1"     [1]=>     string(1) "1"   }   ["yt0"]=>   string(4) "Save" } 

The array “contact-grid_c0” contains another array with 2 elements, which are the rows selected in my CGridView. However, I don’t know to what keys they belong to. This just tells me that 2 rows were selected out of 6 that are populating my CGridView.

If I find out some solution I will be posting it here.

Post your solution if you find one.

Hi there, maybe not the perfect solution or best practice but it works for me.

I used the jQuery function .val() to update a hidden form field with the key values from the CGridView.

Unfortunately it doesn’t pass it to the controller as an array, but as a comma separated string , but in my case I will just explode it to an array on the server side.

To get the key values from the CGridView I used the following javascript:


which returns an array of key values of the currently selected rows of the grid, where the id parameter specifies the id of the grid.

To make it happen automatically you can use the the CGridView’s selectionChanged property to run some JavaScript. The javascript function you specify in the selectionChanged property runs whenever a row is selected or deselected.

/* The form that will be submitted */

echo CHtml::beginForm(array('someaction'),'post');

echo CHtml::hiddenField('your_field_name',null,array('id'=>'your_field_ID')); 

echo CHtml::submitButton();

echo CHtml::endForm();

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





        'selectionChanged'=>'js:function(id) { $("#your_field_ID").val( $.fn.yiiGridView.getSelection(id) ); }', 	







jogasa21: I noticed you used var_dump, if you haven’t checked it out yet

CVarDumper::dump($var, $depth, $highlight)

is great. set the $highlight param to true and you get a nice human-readable var_dump

Thanks camac for the tip !!