How To Use Bulk Action In Yiibooster

I want to delete multiple(selected) rows by use yiiBooster,any code example.Thx :rolleyes:


    

    $this->widget('bootstrap.widgets.TbExtendedGridView', array(

    'type' => 'striped bordered',

    'dataProvider' => $gridDataProvider,

    'template' => "{items}",

    'bulkActions' => array(

    'actionButtons' => array(

    array(

    'buttonType' => 'button',

    'type' => 'primary',

    'size' => 'small',

    'label' => 'Testing Primary Bulk Actions',

    'click' => 'js:function(values){console.log(values);}'

    )

    ),

    // if grid doesn't have a checkbox column type, it will attach

    // one and this configuration will be part of it

    'checkBoxColumnConfig' => array(

    'name' => 'id'

    ),

    ),

    'columns' => $gridColumns,

    ));



What you receive to the function ‘values’, is in fact the checkboxes selected. The only thing you need to do is to handle the collection and submission of those checkboxes values




//...

 'click' => 'js:function(checked){

     var values = [];

     checked.each(function(){

         values.push($(this).val());

     }); 

     // now we go the values, do ajax call (for example, you can also do document.href)

    // we are going to push all selected values in a parameter named "IDS" and the ids will be separated by 

    // comma. I assume that you know how to handle that parameter with Yii

    $.ajax({

     url:"whereiamgoing", 

     data: {ids:values.join(",")},

     success:function(data){ 

         alert("Yahoo");

         // update the grid now

         $("#gridId").yiiGridView("update"); 

     }

     });

}'

//...



Hope it helps





<?php $this->widget('bootstrap.widgets.TbExtendedGridView',array(

	'type' => 'striped bordered',

	'id'=>'yiisession-grid',

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

	'filter'=>$model,

	'bulkActions' => array(

		'actionButtons' => array(

			array(

				'buttonType' => 'link', //'button',

				'type' => 'primary',

				'size' => 'small',

				'label' => 'bulkDelete',

                'url' => array('batchDelete'),

                'htmlOptions' => array(

                        'class'=>'bulk-action'

                ),

                    'click' => 'js:batchActions'

				)

			),

			// if grid doesn't have a checkbox column type, it will attach

			// one and this configuration will be part of it

			'checkBoxColumnConfig' => array(

				'name' => 'id'

			),

	),

	'columns'=>array(

		'id',

		'expire',

		'data',

		'user_id',

		array(

			'class'=>'bootstrap.widgets.TbButtonColumn',

		),

	),

)); ?>


<script type="text/javascript">

    // as a global variable

    var gridId = "yiisession-grid";


    $(function(){

        // prevent the click event

        $(document).on('click','#yiisession-grid a.bulk-action',function() {

            return false;

        });

    });

    function batchActions(values){

        var url = $(this).attr('href');

        var ids = new Array();

        if(values.size()>0){

            values.each(function(idx){

                ids.push($(this).val());

            });

            $.ajax({

                type: "POST",

                url: url,

                data: {"ids":ids},

                dataType:'json',

                success: function(resp){

                    //alert( "Data Saved: " + resp);

                    if(resp.status == "success"){

                       $.fn.yiiGridView.update(gridId);

                    }else{

                        alert(resp.msg);

                    }

                }

            });

        }

    }

</script>



in your controller :




 public function actionBatchDelete()

    {

        //  print_r($_POST);

        $request = Yii::app()->getRequest();

        if($request->getIsPostRequest()){

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

                $ids = $_POST['ids'];

            }

            if (empty($ids)) {

                echo CJSON::encode(array('status' => 'failure', 'msg' => 'you should at least choice one item'));

                die();

            }

            //print_r($ids);

            $successCount = $failureCount = 0;

            foreach ($ids as $id) {

                $model = $this->loadModel($id);

                ($model->delete() == true) ? $successCount++ : $failureCount++;

            }

            echo CJSON::encode(array('status' => 'success',

                'data' => array(

                    'successCount' => $successCount,

                    'failureCount' => $failureCount,

                )));

            die();

        }else{

            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

        }

    }

}




note : please use the "wip" branch not the "master" from github

some one said that if pagination used the buckActions will failed ! so you 'd better to wait Antonio fixed it in next version . :D

Thanks Antonio Ramirez,yiqing95 for your fast reply and a great extension now it worked like a charmed.Thank you very much. :rolleyes:




     ///

     'click' => 'js:function(checked){

     var values = [];

     checked.each(function(){

         values.push($(this).val());

     }); 

     // now we go the values, do ajax call (for example, you can also do document.href)

    // we are going to push all selected values in a parameter named "IDS" and the ids will be separated by 

    // comma. I assume that you know how to handle that parameter with Yii

     if (confirm("Are you sure you want to delete these"))

    {

    $.ajax({

     url:"batchDelete", 

     //type: "POST",

     data: {ids:values.join(",")},

     success:function(data){ 

         //alert("Yahoo");

         // update the grid now

         $("#yw2").yiiGridView("update"); 

     }

     });

     }

}'

     ///



note : to yiqing95,I 'd not try any pagination yet,thx for your information. :D

I’ve tried the above but the error message like this:

[color="#FF0000"]Each bulk action button should have its "id" attribute set to Ensure its functionality among ajax updates.[/color]

What which should I do?

Its just forcing you to add an id attribute to the button - it seems the example code is missing it.

After


'actionButtons' => array(

array(

'buttonType' => 'button',

'type' => 'primary',

'size' => 'small',

'label' => 'Testing Primary Bulk Actions',

'click' => 'js:function(values){console.log(values);}',

'id' => 'test_id',

)



Thank you Andrew1

What happen if i want appear checkbox to use bulkaction only in some rows? Some ideas? i am a little confused with this issue.

Hi yiqing95,

I read this article that helps me. Thank you. But I have a problem with the js function. The url = $(this).attr(‘href’); doesn’t capture the url of the button. What I need to do for call the action controller?

Thank you for any help,

Rolando

Is it possible to adjust position of bulk actions? I want to place them right before the grid (not in footer).

Hi,

Did you ever find a solution? I am facing the same issue!

Kind regards,

Stephen

In regards to my last reply - I have implemented a solution. Unfortunately it is not true Yii code, I have used some raw MySql code in order to make it work - I am new to the Yii framework but know PHP to some decent amount.

Here is my code - edit the parts in CAPS if you use it in your web app.

View file (.../admin.php):

[CODE]

<?php

$this->widget(‘bootstrap.widgets.TbGridView’, array(

    'id'=&gt;'GRID_ID_GOES HERE', // Add Grid ID here


'type' =&gt; 'striped bordered',


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


    'columns'=&gt;array(


	        array(


            'class'=&gt;'CCheckBoxColumn', // Checkboxes


            'selectableRows'=&gt;2,        // Allow multiple selections 


            ),


            'COLUMN_1', // Columns


            'COLUMN_2',


            'COLUMN_3',


            'COLUMN_4',


            'COLUMN_5',





            array(


                    'class'=&gt;'bootstrap.widgets.TbButtonColumn',


            ),


    ),

));

$this->widget(‘bootstrap.widgets.TbButton’,array( // Button to delete

‘label’ => ‘Delete Selected Items’,

‘type’ => ‘danger’,

‘size’ => ‘small’,

‘id’ => ‘delete’

));

?>

<?php

Yii::app()->clientScript->registerScript(‘delete’,’

$("#delete").click(function(){

    var checked=&#036;(&quot;#GRID_ID&quot;).yiiGridView(&quot;getChecked&quot;,&quot;GRID_ID_c0&quot;); // _c0 means the checkboxes are located in the first column, change if you put the checkboxes somewhere else


    var count=checked.length;


	if(count==0){


	alert(&quot;No items selected&quot;);


	}


    if(count&gt;0 &amp;&amp; confirm(&quot;Do you want to delete these &quot;+count+&quot; item(s)&quot;))


    {


            &#036;.ajax({


                    data:{checked:checked},


                    url:&quot;'.CHtml::normalizeUrl(array('CONTROLLER_NAME/RemoveChecked')).'&quot;,


                    success:function(data){&#036;(&quot;#GRID_ID&quot;).yiiGridView(&quot;update&quot;,{});},              


            });


    }


    });

');?>[/CODE]

In my controller file:

[CODE]…

public function actionRemoveChecked()

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

    {


            &#036;checkedIDs=&#036;_GET['checked'];


            foreach(&#036;checkedIDs as &#036;id){


			&#036;connect = mysql_connect ('DB_HOST', 'DB_USERNAME', 'DB_PASSWORD'); // Edit as appropriate 


			&#036;submit = mysql_query(&quot;DELETE FROM DATABASE.TABLE  WHERE id=&quot;.&#036;id); // Edit as appropriate


			}


    }

}

…[/CODE]

Hope this helps people!

Regards,

Stephen

For everyone who may still need an answer.

Maybe you can disable the checkbox using the value from others columns. example:




'checkBoxColumnConfig' => array(

		    'name' => 'id',

                    'disabled' => '$data->active<1'

		),



Use an external button as explained (+ related javascript):


$this->widget('bootstrap.widgets.TbButton',array( // Button to delete

'label' => 'Delete Selected Items',

'type' => 'danger',

'size' => 'small',

'id' => 'delete'

));

?>

(...)



For the URL of Ajax request, this works for me:


'click' => 'js:function(values){ //checked

                            var values = [];

                            checked.each(function(){

                                values.push($(this).val());

                            }); 

                           console.log(values);

                            // now we go the values, do ajax call (for example, you can also do document.href)

                           // we are going to push all selected values in a parameter named "IDS" and the ids will be separated by 

                           // comma. I assume that you know how to handle that parameter with Yii

                           $.ajax({

                            url:"deleteChecked",

                            type: "POST",

                            dataType:\'json\',

                            data: {ids:values},

                            

                            success:function(response){ 

                                alert("Eliminate " + response.data.keys.length + " righe.");

                                

                                console.log(response);

                                // update the grid now

                                $("#wrong-rows-grid").yiiGridView("update"); 

                            }

                            });

                       }'



Hi,

I licterally copied your example and tried to execute but even if I can confirm that the link of the button is calling the bacthDelete action in the corresponding controller, nothing really happensChecking with firebug I can see that ids is fullfilled correctly after mutiple selection but no action occurs.Where am I wrong?????????????????