How get Id from Cgridview

Hello everyOne!!

Plz help me!! I use CgridView that have checkbox.When I’m select checkbox (id 1 ,2)when I’m click save button I want to get Id from it. plz help!!! thank in advance

hi phosltc: read the yiigridview.js source code ; use $.fn.yiiGridView.getselection() method in js code,




           //js code:

           function saveIt(){


                var ids =  $.fn.yiiGridView.getselection(); // this is  a  js  array

               var url = "<?php Yii::app()->controller->createUrl('batchOp'); ?>";

              var params = {

                         'ids':ids

                  };

                $.post(url,params,function(response){

                        alert(response);  

                        response = $.parseJSON(response);

                         if(response.error){

                                window.location = response.url;

                          }else{

                            

                            }

                     });


           }

     //  php  code  , in your controller

        

            public function actionBatchOp(){

               if(Yii::app()->request->getIsPostRequest()){

                      $ids = $_POST['ids'];

                       foreach($ids as $id){

                                //do someThing with $id

                        }

                    echo CJSON::encode(array('error'=>true,'url'=>$this->createUrl('admin')));

                 }

               


               }






above just some pseudo-code

thank so much yiqing95 for ur reply!!! :)

Hi Phosltc,

The solution can work for you? can show what have you done to get it work!! =)

hi yiqing95 I’m still can’t do it!! plz help

this my View.php


<?php 

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

	'id'=>'fcr-grid',

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

	'filter'=>$mode,

	'selectableRows'=>2,

	'columns'=>array(

		 array(

                    'header'=>'Id',

                    'class'=>'CDataColumn',

                    'type'=>'raw',

                    'htmlOptions'=>array('style'=>'text-align:center'),

                    //'value' => 'CHtml::checkBox("id[]", $data->id)',

					'value'=> 'CHtml::checkBox("id[]")',

					

                ),

		

		'id',

		'fcr_no',

		array(

					'name'=>'shipment_mode',

					'filter'=>CHtml::listData(ShipmentMode::model()->findAll(),'id','type'),

					'value'=>'ShipmentMode::Model()->FindByPk($data->shipment_mode)->type',

				),

				

		

		'place_of_delivery',

		array(

				'name'=>'status',

				'filter'=>array(1=>'Accept',2=>'Shipped',3=>'Deliver',4=>'Received'),

		),

		

		

	),

)); ?>




       

    


	<?php echo CHtml::submitButton($mode->isNewRecord ? 'Create' : 'Save'); ?>

and this is my controller




public function actionView($id)

	{

		$model=new FcrShipment('search');

		

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['FcrShipment']))

			$model->attributes=$_GET['FcrShipment'];

			

			$mode = new Fcr('search');

			$mode->unsetAttributes();

			if(isset($_GET['Fcr']))

			{

				$mode->attributes=$_GET['Fcr'];

				 //$fcrId=$mode->id= Yii::app()->request->getQuery('id');

				  $fcrId=$model->id;

					foreach($fcrId as $a)

					{

						$_mode= new FcrShipment;

						$_mode->shipment_id=$id;

						$_mode->fcr_id=$a;

						$_mode->save();

						

					}

				$this->redirect(array('view'));

				}


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

			'model'=>$model,

			'mode'=>$mode,

		));

	}



Add this: in the view/admin.php page




  <?php

    Yii::app()->clientScript->registerScript('search', "

$('.search-button').click(function(){

$('.search-form').toggle();

return false;

});

$('.search-form form').submit(function(){

$.fn.yiiGridView.update('employee-grid', {

data: $(this).serialize()

});

return false;

});


$('.deleteall-button').click(function(){

        

        var atLeastOneIsChecked = $('input[name=\"employee-grid_c0[]\"]:checked').length > 0;


        if (!atLeastOneIsChecked)

        {

                alert('Please select atleast one Item to delete');

        }

        else if(window.confirm('Are you sure you want to delete the Selected?'))

        {

        

                document.getElementById('employee-search-form').action='deleteall';

                document.getElementById('employee-search-form').submit();

        }

});

");

    ?>



and before:




 <?php

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

        'id' => 'employee-grid',

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

        'filter' => $model,

        'selectableRows' => 2,

        'columns' => array(

            array(  

                        'value'=>'$data->id',

                        'class'=>'CCheckBoxColumn',            

                ),

          

            'name',

            'designation',

            array

                (

                'header' => 'Options',

                'class' => 'CButtonColumn',


            ),

        )

    ));

    ?>



add this:




 <?php $form=$this->beginWidget('CActiveForm', array(

        'id'=>'employee-search-form',

        'enableAjaxValidation'=>true,

        'htmlOptions'=>array('enctype' => 'multipart/form-data')

));

?>



and at the bottom of all add a deleteAll button like this:




<div class="deleteAllCustomDiv">

 <?php 

echo CHtml::button('Delete All',array('name'=>'btndeleteall','class'=>'deleteall-button')); 

?>

</div>


<?php $this->endWidget(); ?>




and the last thing is in your controller/action :

add this:




public function actionDeleteAll() {

        if (isset($_POST['employee-grid_c0'])) {

            $del_item = $_POST['employee-grid_c0'];

            $model_item = new Employee;

            $model_item_all = new Employee;

            foreach ($del_item as $_id) {

                $model_item->deleteByPk($_id);

                $model_item_all->deleteAllByAttributes(array('id' => $_id));

            }

            $this->actionAdmin();

        } else {

            Yii::app()->user->setFlash('error', 'Please select at least one record to delete.');

            $this->actionAdmin();

        }

    }



hope this will help you

hi tanimgt!! thank so much for ur reply…:) I follow with ur code u give me but still not work(It not delete Item from my database.)This is my code I don;t know problem with what?

my view code admin.php


 

<?php $form=$this->beginWidget('CActiveForm', array(

        'id'=>'book-search-form',

        'enableAjaxValidation'=>true,

        'htmlOptions'=>array('enctype' => 'multipart/form-data')

));

?>


<?php

$this->breadcrumbs=array(

	'Books'=>array('index'),

	'Manage',

);


$this->menu=array(

	array('label'=>'List Book', 'url'=>array('index')),

	array('label'=>'Create Book', 'url'=>array('create')),

);


Yii::app()->clientScript->registerScript('search', "

$('.search-button').click(function(){

	$('.search-form').toggle();

	return false;

});

$('.search-form form').submit(function(){

	$.fn.yiiGridView.update('book-grid', {

		data: $(this).serialize()

	});

	return false;

});


$('.deleteall-button').click(function(){

        

        var atLeastOneIsChecked = $('input[name=\"book-grid_c0[]\"]:checked').length > 0;


        if (!atLeastOneIsChecked)

        {

                alert('Please select atleast one Item to delete');

				

        }

        else if(window.confirm('Are you sure you want to delete the Selected?'))

        {

        

                document.getElementById('book-search-form').action='deleteall';

                document.getElementById('book-search-form').submit();

        }

});


");

?>


<h1>Manage Books</h1>





<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>

<div class="search-form" style="display:none">

<?php $this->renderPartial('_search',array(

	'model'=>$model,

)); ?>

</div><!-- search-form -->


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

	'id'=>'book-grid',

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

	'filter'=>$model,

	'selectableRows'=>2,

	'columns'=>array(

	

			array(

				'value'=>'id',

				'class'=>'CCheckBoxColumn',

      

                ),

		'title',

		'status',

		'type',

		

	),

)); ?>


<div class="deleteAllCustomDiv">

 <?php echo CHtml::button('Delete All',array('name'=>'btndeleteall','class'=>'deleteall-button')); ?>

</div>

<?php $this->endWidget(); ?>



And this is my controller


 

public function actionDeleteAll() {

        if (isset($_POST['book-grid_c0'])) {

            $del_item = $_POST['book-grid_c0'];

            $model_item = new Book;

            $model_item_all = new Book;

            foreach ($del_item as $_id) {

                $model_item->deleteByPk($_id);

                $model_item_all->deleteAllByAttributes(array('id' => $_id));

			  

            }

            $this->actionAdmin();

        } else {

            Yii::app()->user->setFlash('error', 'Please select at least one record to delete.');

            $this->actionAdmin();

        }

    }



I’m waiting ur reply… hope u will reply me soon… :)

Ok, what you are doing wrong is you put




<?php $form=$this->beginWidget('CActiveForm', array(

        'id'=>'book-search-form',

        'enableAjaxValidation'=>true,

        'htmlOptions'=>array('enctype' => 'multipart/form-data')

));

?>



before your





Yii::app()->clientScript->registerScript('search', "

$('.search-button').click(function(){

	$('.search-form').toggle();

	return false;

});

$('.search-form form').submit(function(){

	$.fn.yiiGridView.update('book-grid', {

		data: $(this).serialize()

	});

	return false;

});


$('.deleteall-button').click(function(){

        

        var atLeastOneIsChecked = $('input[name=\"book-grid_c0[]\"]:checked').length > 0;


        if (!atLeastOneIsChecked)

        {

                alert('Please select atleast one Item to delete');

				

        }

        else if(window.confirm('Are you sure you want to delete the Selected?'))

        {

        

                document.getElementById('book-search-form').action='deleteall';

                document.getElementById('book-search-form').submit();

        }

});


");



section, you have to put




<?php $form=$this->beginWidget('CActiveForm', array(

         'id'=>'book-search-form',

         'enableAjaxValidation'=>true,

         'htmlOptions'=>array('enctype' => 'multipart/form-data')

 ));

 ?>




just before your





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

	'id'=>'book-grid',

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

	'filter'=>$model,

	'selectableRows'=>2,

	'columns'=>array(

	

			array(

				'value'=>'id',

				'class'=>'CCheckBoxColumn',

      

                ),

		'title',

		'status',

		'type',

		

	),

));



hope you will fix this, thanks ;D

Thank so much all of you!!! now It work for me!!! :) :) ;D :unsure: B) ^_^

hi phosItc,

u follow tanimgt code above to get the multiple checkbox value izzit?? Any changes from above code with your code?

Thanks,