Delete Records With Multi Check Box

first up all i am new learner of yii frame work

I wanna delete all records when i am click the delete all button in cgride view

with alerts

please give me one example about this for better understanding

with view ,controller,model

Thanks&regards

Yarra

please help me any one i am waiting for your valuable post


// This is how I added delete all button with gridview checkboxes


<?php

$this->breadcrumbs=array(

        //'Campaigns'=>array('index'),

        //'Manage',

);


$this->menu=array(

        //array('label'=>'List Campaign', 'url'=>array('index')),

        //array('label'=>'New Campaign', '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('campaign-grid', {

                data: $(this).serialize()

        });

        return false;

});

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

        

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


        if (!atLeastOneIsChecked)

        {

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

        }

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

        {

                document.getElementById('campaign-search-form').action='index.php?r=campaign/deleteall';

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

        }

});

");


?>


<h2>Search Campaigns</h2>


<!--<p>

You may optionally enter a comparison operator (<b><</b>, <b><=</b>, <b>></b>, <b>>=</b>, <b><></b>

or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done.

</p>-->


<?php 

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

?>

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

<?php 

$this->renderPartial('_search',array('model'=>$model)); 

?>

</div>

<!-- search-form -->


<div class="wide form">


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

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

        'enableAjaxValidation'=>false,

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

));

?>

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

        'id'=>'campaign-grid',

        'selectableRows'=>2,

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

        'columns'=>array(

        

                        array(

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

        'class'=>'CCheckBoxColumn',

      

                ),

                'camp_id',

                'name',

                array('name'=>'start_time','value'=>'date(\'Y-m-d H:i:s\', $data->start_time)'),

                array('name'=>'end_time','value'=>'date(\'Y-m-d H:i:s\', $data->end_time)'),

                'manager',

                array('name' => 'priority','value'=>'$data->mPriorityOptions[$data->priority]'),

                array('name' => 'mode','value'=>'$data->mModeOptions[$data->mode]'),            

                array(

                        'class'=>'CButtonColumn',

                ),

        ),

)); ?>


<div class="row buttons">

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

</div>

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

</div>

in Controller


public function actionDeleteAll()

{

        if (isset($_POST['campaign-grid_c0']))

        {

                $del_camps = $_POST['campaign-grid_c0'];

                

                $model_camp=new Campaign;

                $model_receipiant = new Recipiants;

                

                foreach ($del_camps as $_camp_id)

                {

                        $model_camp->deleteByPk($_camp_id);

                        $model_receipiant->deleteAllByAttributes(array('camp_id'=>$_camp_id));

                }

                                        

                $this->actionAdmin();

        }

        else

        {

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

                $this->actionAdmin();

        }               

}

Thanks for your replay i will try it

its not working

Please Post Your code

in view

<?php

/* @var $this UsersController */

/* @var $model Users */

$this->breadcrumbs=array(

'Users'=&gt;array('index'),


'Manage',

);

$this->menu=array(

array('label'=&gt;'List Users', 'url'=&gt;array('index')),


array('label'=&gt;'Create Users', 'url'=&gt;array('create')),

);

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

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

&#036;('.search-form').toggle();


return false;

});

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

&#036;('#users-grid').yiiGridView('update', {


	data: &#036;(this).serialize()


});


return false;

});

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

    var atLeastOneIsChecked = &#036;('input[name=&#092;&quot;users-grid_c1[]&#092;&quot;]:checked').length &gt; 0;





    if (&#33;atLeastOneIsChecked)


    {


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


    }


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


    {


            document.getElementById('users-form').action='index.php?r=users/DeleteAll';


            document.getElementById('users-form').submit();


    }

});

");

?>

<h1>Manage Users</h1>

<!–<p>

You may optionally enter a comparison operator (<b>&lt;</b>, <b>&lt;=</b>, <b>&gt;</b>, <b>&gt;=</b>, <b>&lt;&gt;</b>

or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done.

</p>–>

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

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

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

'model'=&gt;&#036;model,

)); ?>

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

<div class="wide form">

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

    'id'=&gt;'users-form',


    'enableAjaxValidation'=&gt;false,


    'htmlOptions'=&gt;array('enctype' =&gt; 'multipart/form-data')

));

?>

<!-------date ficker---->

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

'id'=&gt;'users-form',


'enableAjaxValidation'=&gt;true,

)); ?>

<b>From :</b>

<?php

$this->widget(‘zii.widgets.jui.CJuiDatePicker’, array(

'name'=&gt;'from_date',  // name of post parameter


'value'=&gt;Yii::app()-&gt;request-&gt;cookies['from_date']-&gt;value,  // value comes from cookie after submittion


 'options'=&gt;array(


    'showAnim'=&gt;'fold',


    'dateFormat'=&gt;'yy-mm-dd',


),


'htmlOptions'=&gt;array(


    'style'=&gt;'height:20px;'


),

));

?>

<b>To :</b>

<?php

$this->widget(‘zii.widgets.jui.CJuiDatePicker’, array(

'name'=&gt;'to_date',


'value'=&gt;Yii::app()-&gt;request-&gt;cookies['to_date']-&gt;value,


 'options'=&gt;array(


    'showAnim'=&gt;'fold',


    'dateFormat'=&gt;'yy-mm-dd',





),


'htmlOptions'=&gt;array(


    'style'=&gt;'height:20px;'


),

));

?>

<?php echo CHtml::submitButton(‘Go’); ?> // submit button

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

<!-------end date ficker--------->

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

'id'=&gt;'users-grid',


 'selectableRows'=&gt;2,


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


'filter'=&gt;&#036;model,


'columns'=&gt;array(


 array('header' =&gt; '#', 'value' =&gt; '(&#036;row+1) . &quot;.&quot;', 'htmlOptions' =&gt; array('style' =&gt; 'text-align:right;')),


                         array(


            'value'=&gt;'&#036;data-&gt;id',


           'class'=&gt;'CCheckBoxColumn',


		    //'id'=&gt;'person-id',


		   //'selectableRows' =&gt; '50',  


  


            ),


	  array(


'name'=&gt;'id',


'value'=&gt;'CHtml::encode(&#036;data-&gt;id)'

),

array(

'name'=&gt;'username',


'value'=&gt;'CHtml::encode(&#036;data-&gt;username)'

),

array(

'name'=&gt;'image',


'value'=&gt;'CHtml::encode(&#036;data-&gt;image)'

),

array(

'name'=&gt;'createtime',


'value'=&gt;'CHtml::encode(date(&#092;'Y-m-d,H:i:s&#092;', &#036;data-&gt;createtime))'  //this will format the unix timestamp to a custom date format

),

array(

 'name'=&gt;'lastvisit',              


 'value'=&gt;'CHtml::encode(date(&#092;'Y-m-d&#092;', &#036;data-&gt;lastvisit))'      // format the cell with date format

),

array(

 'name'=&gt;'status',


 'value'=&gt;'CHtml::encode(&#036;data-&gt;status==1 ? &#092;'Active&#092;': &#092;'Inactive&#092;' )' 

// to render the gridview cell with a particular value

),


array(


		'class'=&gt;'CButtonColumn',


		//y'afterDelete'=&gt;'function(link,success,data){ if(success) &#036;(&quot;#statusMsg&quot;).html(data); }',


		 


	),


),


 // 'selectionChanged'=&gt;'userClicks',

)); ?>

<div class="row buttons">

    &lt;?php echo CHtml::button('Delete',array('name'=&gt;'btndeleteall','class'=&gt;'deleteall-button')); ?&gt;

</div>

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

</div>

In controller…

public function actionDeleteAll()

				{


						if (isset(&#036;_POST['campaign-grid_c0']))


						{


								&#036;del_camps = &#036;_POST['campaign-grid_c0'];


								


								&#036;model_camp=new Users;


								//&#036;model_receipiant = new Recipiants;


								


								foreach (&#036;del_camps as &#036;_camp_id)


								{


										&#036;model_camp-&gt;deleteByPk(&#036;_camp_id);


										&#036;model_receipiant-&gt;deleteAllByAttributes(array('id'=&gt;&#036;_camp_id));


								}


														


								&#036;this-&gt;actionAdmin();


						}


						else


						{


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


								&#036;this-&gt;actionAdmin();


						}               


				}

<?php $form=$this->beginWidget('CActiveForm', array([/size]

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

        'enableAjaxValidation'=>false,

        'htmlOptions'=>array('enctype' => 'multipart/form-data','action'=>Yii::app()->createUrl('Controller/action'))

));


?>

Specify the action Yii::app()->createUrl(‘Controller/action’) and add this form

i was added but not success

Do the values are posting in the controller ?

What is happening , any error is showing?

i was done like the following

print_r($_POST[campaign-grid_c1]);

in controller but not display anything

please help me any body

i was trying for this from 2 days but not getting success

please help me

please send the post

Dear Friend

Let us have a very simple Model.

Item:id,name.

Now in admin.php, we are going to make the following changes.

1.Add checkbox column.Make the selection multiple.




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

	'id'=>'item-grid',

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

	'filter'=>$model,

	'columns'=>array(

		'id',

		'name',

		array(

		'class'=>'CCheckBoxColumn',  //CHECKBOX COLUMN ADDED.

		'selectableRows'=>2,         //MULTIPLE ROWS CAN BE SELECTED.

		),

		array(

			'class'=>'CButtonColumn',

		),

	),

)); ?>

<?php



2.Then make a button at the bottom of the grid.




<?php

echo CHtml::button("Remove Selected Items",array("id"=>"butt"));

?>



3.Then registers the following script at the bottom of page.




<?php

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

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

	var checked=$("#item-grid").yiiGridView("getChecked","item-grid_c2");

	var count=checked.length;

	if(count>0 && confirm("Do you want to delete these "+count+" item(s)"))

	{

		$.ajax({

			data:{checked:checked},

			url:"'.CHtml::normalizeUrl(array('item/remove')).'",

			success:function(data){$("#item-grid").yiiGridView("update",{});},		

		});

	}

	});

');



NOTE:

1.In the above script "item-grid_c2" indicates that our checkbox column resides as third column.

2.We are deleting the records by ajax.

3.After successful deletion, we are updating the grid with existing records.

4.Create a method actionRemove in ItemController.




public function actionRemove()

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

	{

		$checkedIDs=$_GET['checked'];

		foreach($checkedIDs as $id)

			Item::model()->deleteByPk($id);

	}

}



5.Finally do not forget to put the action "remove" in accessController filter.




.........................................................................

array('allow', 

		'actions'=>array('admin','delete','remove'), //action remove added.

		'users'=>array('admin'),

	),

...........................................................................



Regards.

Cool…

awesome finally i got it

thank you so much