selgridview

Remembers selected rows when sorting or paging and allows to select row programmatically
33 followers

SelGridView extends CGridView with following features:

  • remember selected rows on sorting / paging grid
  • select rows programmatically by GET param (e.g. to highlight new record, etc)

Demo

Try out a demo

Download

Latest version 2.3

Requirements

Tested on Yii 1.1.9.

Installation

Put selgridview folder from zip to your protected/extensions.

Usage

Use as standart CGridView widget (don't forget to set selectableRows >= 1).

Controller:

public function actionIndex()
{
    $dataProvider = new CActiveDataProvider('User', array(
           'pagination' => array(
                'pageSize' => 2,
            ),
    ));        
 
    $this->render('index', compact('dataProvider'));              
}

View index.php:

<? 
  $this->widget('ext.selgridview.SelGridView', array(
    'id' => 'mygrid',
    'dataProvider' => $dataProvider,
    'selectableRows' => 2,
    'columns'=>array(
        array(
          'class' => 'CCheckBoxColumn',
        ),
        'UserID',
        'UserName',
     ),
  ));
?>

When sorting or paging such grid, you will see in ajax GET params "User_sel={id}" as well as "User_page={page}". Value of User_sel is model primaryKey. Widget automatically proceess this value and select rows.

If you want to highlight newly created row in grid you need to set GET param User_sel={new-record-id}:

$this->createUrl('user/index', array('User_sel' => 123));

To get all selected keys on all pages in your javascript (when selectableRows >= 2):

var selected = $("#mygrid").selGridView("getAllSelection");

Usage with bootstrap

it is possible to use with bootstrap gridview.

Example:

$this->widget('ext.selgridview.BootSelGridView', array(
    'id' => 'mygrid',
    'dataProvider' => $dataProvider,
...

To highlight selected rows in such bootstrap-grid you can add to your css:

table.table tr.selected td, table.table tr.selected:hover td {
    background: none repeat scroll 0 0 #BCE774;
}

How it works

Standart CGridView can automatically select rows in grid when there is checkox column with checked = true values. But it does not keep selection on sorting / paging. This extension makes two things:

  • creates hidden CCheckBoxColumn that gets checked by GET param. If there is checkbox column in widget config, no hidden column generated
  • attach BeforeAjaxUpdate js function that adds GET params to URL when sorting and pagination

Note

When you have selectableRows > 1 SelGridview will remember all selected rows on all grid pages not only on visible page.

Issues

Please submit issues to github. Thanks for feedback!

History

Mar 21, 2012
Added support of BootGridView

Mar 18, 2012 (version 2.0)

  • widget significally rewriten with javascript, code became more clear
  • added JS method for getting all selected keys from all pages (comment #7371)

Mar 16, 2012

  • fixed #7346 (thanks to horacio.segura)
  • added support for several grids on one page
  • improved demo

Feb 25, 2012
Added support of CArrayDataProvider

Feb 24, 2012
Initial release

Total 20 comments

#12652 report it
karmraj at 2013/04/04 01:36am
Awesome extension !!!!

Really Good extension with very detailed description.

#11938 report it
lagogz at 2013/02/13 05:53pm
I'm very pleased

It's great that the code works for you.

Regards.

#11932 report it
zvik2004 at 2013/02/13 12:48pm
lagogz, thank you very much

Works like charm :-)

#11921 report it
lagogz at 2013/02/13 02:30am
Zvi, I do the following

Good morning all!

Suppose I have 3 tables:

Authors: AuthorId, Name

Books: BookId, Title

Authors_Books: AuthorId, BookId

A book can have multiple authors.

Then, when I add a new book, I want to select multiple authors in SelGridView and save data.

model Books

public $Authors; //I build this property that have authors ids separated by commas.
...
public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
                    array('Authors', 'required'),
...

Books _form.php

<script>
    function selAuthors()
    {
        var arraySel = $("#to-authors-grid").selGridView("getAllSelection");
 
        var stringSel=arraySel.join(',');                                                                          
        $('#Books_Authors').val(stringSel);//#Books_Authors is hidden field id.
    }
.....
 
//This hidden field will have authors ids separated by commas.
<div class="row">
            <?php 
                echo $form->hiddenField($modelBooks,'Authors');
                echo $form->error($modelBooks,'Authors'); 
            ?>
        </div>
 
//in SelGridView widget.
...
'selectionChanged'=>'js:selAuthors',
...

Books controller, in actionCreate:

$Authors=explode(',',$modelBooks->Authors);//Make an authors array.
 
                    foreach ($Authors as $IdAuthor)
                        //Save relation data.
                    }

I hope it will be helpful.

#11909 report it
zvik2004 at 2013/02/12 05:00pm
Problem when working with a form

Hi, I have a form and a table in it. If I select a row, and then move to the next page (so that the selected row can't be seen), and then press on the submit button, I get nothing in the selected rows. Note that: 1. I work with bootstrap (ext.selgridview.BootSelGridView) 2. I get the selected rows from the _POST parameters.

Thanks, Zvi.

#11795 report it
Vitalets at 2013/02/04 09:18am
Re: The clearing selection

hi, yes it was a bug.
Fixed in 2.3 version. Thanks!

#11772 report it
rclai89 at 2013/02/02 06:21pm
The clearing selection

Hey, I noticed that when I use selGridView("clearAllSelection"), the checkboxes of the current page are unchecked, but the other pages with checkboxes checked do not get unchecked. Is that a bug?

#11771 report it
rclai89 at 2013/02/02 06:14pm
Thanks

Ah.. I had version 2.0 of this extension, no wonder I could not see that method in the JS. Thanks.

#11762 report it
Vitalets at 2013/02/02 04:17am
Re: Ability to uncheck all?

yes:
$("#grid2").selGridView("clearAllSelection");

#11759 report it
rclai89 at 2013/02/01 11:05pm
Ability to uncheck all?

Hey, I really love this plugin to remember the checkboxes, however, is there a way to unselect them all and "forget" what was checked?

#11597 report it
Vitalets at 2013/01/22 10:51am
Re: I still have the problem.

answered in PM.

#11563 report it
lagogz at 2013/01/21 02:43am
I still have the problem.

Good morning.

The problem is AJAX post, no SelGridView.

With the code as I have the actionCreate isn't launched.

If I put

'enableAjaxValidation'=>true,

in CActiveForm configuration, ToMedicamentos data is saved but no data from the SelGridView.

Could it be that I have to put a button type different from submitButton?

I don't understand why it fails.

Thanks.

PD.:

Here is my ToMedicamentos/actionCreate:

public function actionCreate()
    {
        $modelMedicamentos=new ToMedicamentos;
        $IdMedicamento=0;
        $modelPActivos=new ToPrincipiosActivos;
 
        $modelMPA = new TvPactivosMedicamentos("searchIncludingPActivos($IdMedicamento)");
        $modelMPA->unsetAttributes();
        $modelMPA->scenario = 'searchIncludingPActivos';
 
        if(isset($_POST['ToMedicamentos']))
        {
            $modelMedicamentos->attributes=$_POST['ToMedicamentos'];
 
            if($modelMedicamentos->save())/* Save the Role model */
            {
                $IdMedicamento = $modelMedicamentos->IdMedicamento;
 
                $modelito=new ToMedicamentos;
                $modelito->Medicamento='jajejijoju';
                $modelito->save();
 
                $modelMPA = new TvPactivosMedicamentos();
                $modelMPA->IdMedicamento = $IdMedicamento;
                $modelMPA->IdPrincipio_Activo = 12;
                $modelMPA->save();
 
                $selectedItems=Yii::app()->request->getPost('selectedItems');
 
                foreach ($selectedItems as $IdPrincipio_Activo) {
                        $this->linkChildRecord($IdMedicamento, $IdPrincipio_Activo);
                    }
 
                $this->redirect(array('view','id'=>$IdMedicamento));
            }
        }
 
        $this->render('create',array(
                                    'modelMedicamentos'=>$modelMedicamentos,
                                    'modelMPA'=>$modelMPA,
                                    'modelPActivos'=>$modelPActivos,
                                    'IdMedicamento' => $IdMedicamento,
        ));
    }

Notice that I created one new ToMedicamentos model called $modelito and one TvPactivosMedicamentos called $modelMPA. When I press submitButton, $modelMedicamentos ,$modelito and $modelMPA are saved in database, but

$selectedItems=Yii::app()->request->getPost('selectedItems');
 
                foreach ($selectedItems as $IdPrincipio_Activo) {
                        $this->linkChildRecord($IdMedicamento, $IdPrincipio_Activo);
                    }

doesn't work.

selectedItems and ToMedicamentos sent by AJAX are empty. That is, AJAX does not send data. Why?

Furthermore,

$this->redirect(array('view','id'=>$IdMedicamento));

Doesn't work.

#11550 report it
Vitalets at 2013/01/20 06:35am
Re: Here my code!

maybe textfield value missing in ajax data?

$.ajax({
   type: "POST",
   url: "<?php echo Yii::app()->createUrl('toMedicamentos/create'); ?>",
   data: {selectedItems : selected, ToMedicamentos: $('#Medicamento').val()},
   ...

Anyway, if you see correct alert(selected.length) it's not a selgridview issue, try to comment all selgridview parts and submit textfireld only. hth

#11527 report it
lagogz at 2013/01/18 09:54am
Here my code!

****views/toMedicamentos/_form.php****

<script>
    $("body").on("click","#submitMedicamento",function(){
        var selected = $("#to-pactivos-grid").selGridView("getAllSelection");
 
        //if nothing's selected
        if ( ! selected.length)
        {
            alert('Please select minimum one item to be deleted');
            return false;
        }
 
        $.ajax({
                type: "POST",
                url: "<?php echo Yii::app()->createUrl('toMedicamentos/create'); ?>",
                data: {selectedItems : selected},
                success: (function (data){
                }),
                error: function(data) { // if error occured
                    alert("Error occured.please try again");
                    alert(data);
               },
               dataType:'html'
            });
 
        return false;
    });
</script>
 
...
 
<div class="form">
 
...
 
<?php $form=$this->beginWidget('CActiveForm', array(
            'id'=>'to-medicamentos-form',
            'enableAjaxValidation'=>false,
        )); ?>
 
...
 
           <div class="row">
                <?php echo $form->labelEx($modelMedicamentos,'Medicamento'); ?>
                <?php echo                           $form->textField($modelMedicamentos,'Medicamento',array
                ('size'=>60,'maxlength'=>64)); ?>
                <?php echo $form->error($modelMedicamentos,'medicamento'); ?>
            </div>
 
...
 
         <div class="textaligncenter">
     <?php
 
         $this->widget('application.components.SelGridViewGal', array(
                        'id'=>'to-pactivos-grid',
                        'dataProvider'=>$modelPActivos->search(),
                        'filter'=>$modelPActivos,
                        'selectableRows' => 2,
                        'columns'=>array(
                                        array(
                                            'class' => 'CCheckBoxColumn'
                                            ),
                                        'Principio_Activo',
                                        array(
                                                'class'=>'CButtonColumn',
                                            ),
                                    ),
                    )); 
 
...
 
            </div>
 
<div id="shortBottomBar"> 
            <?php 
                echo CHtml::submitButton(
                     $modelMedicamentos->isNewRecord ? 'Alta' : 'Actualizar',
                     array('id'=>'submitMedicamento')
                );
            ?>
        </div>
 
</div>
 
 <?php 
        $this->endWidget(); 
    ?>

ToMedicamentosController.php__

public function actionCreate()
    {
 
...
 
if(isset($_POST['ToMedicamentos']))
{
 
...
 
if(isset($_POST['selectedItems']))
        {   
         foreach ($_POST['selectedItems']as $IdPrincipio_Activo) {
                  $this->linkChildRecord($IdMedicamento, $IdPrincipio_Activo);
                    }
                }
...
 
}

When I press submit button, I want to send $_POST['selectedItems'] and $_POST['ToMedicamentos'] to create action on my controller.

With this code, if I do an "alert(selected [0]);" in my AJAX code, I can show it, but no actionCreate is launched.

Thanks for reply.

#11523 report it
Vitalets at 2013/01/18 08:25am
Re: Vitalets, I edit my post.

lagogz, for me everything looks correct.
1. could you just select 2 rows in grid and run in browser console:

$("#to-pactivos-grid").selGridView("getAllSelection")

to see what is actually returned?
2. if possible, please post selgridview widget config.

#11522 report it
lagogz at 2013/01/18 07:45am
Vitalets, I edit my post.

Please, view my post again.

SelectableRows is OK. I have AJAX pagination, I think.

#11521 report it
Vitalets at 2013/01/18 07:41am
Re: Selected items on another page are not saved.

hi, please check:

  1. have you set selectableRows = 2 in grid config ?
  2. pagination is ajax or non-ajax ?
#11515 report it
lagogz at 2013/01/18 03:55am
I can't save my form.

Good afternoon.

I have a form with a textfield and a selgridview.

I can't save my values for textfield aand selgrdiview.

<script>
    $("body").on("click","#submitMedicamento",function(){
        var selected = $("#to-pactivos-grid").selGridView("getAllSelection");
 
        //if nothing's selected
        if ( ! selected.length)
        {
            alert('Please select minimum one item to be deleted');
            return false;
        }
 
        $.ajax({
                type: "POST",
                url: "<?php echo Yii::app()->createUrl('toMedicamentos/create'); ?>",
                data: {selectedItems : selected},
                success: (function (data){
                    //document.getElementById('to-medicamentos-form').submit();
                }),
                error: function(data) { // if error occured
                    alert("Error occured.please try again");
                    alert(data);
               },
               dataType:'html'
            });
 
        return false;
    });
</script>
echo CHtml::submitButton(
                                $modelMedicamentos->isNewRecord ? 'Alta' : 'Actualizar',
                                array('id'=>'submitMedicamento')
                                );

Can anyone help me?

Tanks.

#11431 report it
le_top at 2013/01/14 02:47am
submitting selected trhough ajax - example 2

Or you can do something like this if you'ld like Yii to generate your code (CSRF may need to be added here);

$jsData=<<<EOJS
{
    'YourModel[field]': jQuery('#{$grid->id}').selGridView('getAllSelection').join()
}
EOJS;
echo CHtml::ajaxButton(
        'send','',
        array('data'=>"js:$jsData",)
 
);
#11430 report it
sangprabo at 2013/01/14 02:27am
Re: How to get all selected keys in the controller

I don't know the best practice, but I did it like this..

var selected = $("#items-grid").selGridView("getAllSelection");
 
            //if nothing's selected
            if ( ! selected.length)
            {
                alert('Please select minimum one item to be deleted');
                return false;
            }
 
            //confirmed?
            if ( ! confirm('Are you sure to delete ' + selected.length + ' items?')) return false;
 
            var multipledeleteUrl = "<?php echo Yii::app()->baseUrl;?>/items/multipledelete";
 
            $.ajax({
                type: "POST",
                url: multipledeleteUrl,
                data: {selectedItems : selected},
                success: (function (e){
                    //we refresh the CCGridView after success deletion
                    $.fn.yiiGridView.update("items-grid");
 
                    //just to make sure we delete the last selected items
                    $("#items-grid").selGridView("clearAllSelection");
                })
            });

On your items controller, on actionMultipleDelete()..

//.....
 
$selectedItems = Yii::app()->request->getPost('selectedItems');
 
            //iterate through all ids
            foreach ($selectedItems as $id)
            {
                //do your action here....
            }

Leave a comment

Please to leave your comment.

Create extension
Downloads
No downloadable files yet