Skip to main content

YII CGRIDVIEW, Add form actions to cgridview

This is a tutorial for how to add input text-Field, check-box, buttons in CGridView.

Scenario 

This is CRUD pages for admin menu management. So, Menu model have following things:
  • menuId : INT
  • menuName : VARCHAR
  • sortOrder : INT (Admin may change menu order, based on that front side menu will render)
  • isActive : BOOL (only values with '1' will be shown in front side)
  • isDelete : BOOL (only values with '0' will be shown, whenever admin deletes any menu value will be changed to '1')

Demo 

Below is how GRID will look like:
Screenshot

Fetch listing from model: 

Let's start with model file. There is only one change, I want default listing by sortOrder field.
public function search()
{
    .....
    return new CActiveDataProvider($this, array(
    'criteria'=>$criteria,
    'sort'=>array(
        'defaultOrder'=>'sortOrder ASC',
    ),
    ));
}

Add TextField, checkbox, buttons in CGridView: 

Now we will see view file.
  1. We need to add CGridView inside form so that we can save grid data after submission. We will use ajax to operate all things.
  2. We need to use CCheckBoxColumn which will generate checkbox first column as shown in image.
  3. We need some ajax button at bottom of the page using ajaxSubmitButton which will handle all events. Button names are self-explainable. Here i am going to use 4 buttons
    • To change status to 'Active'
    • To change status to 'In Active'
    • To delete multiple row.
    • To update sort order.
<?php $form=$this->beginWidget('CActiveForm', array(
    'enableAjaxValidation'=>true,
)); ?>
 
<?php 
    $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'menu-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        array(
            'id'=>'autoId',
            'class'=>'CCheckBoxColumn',
            'selectableRows' => '50',   
        ),
        'menuId',
        'menuName',
        array(
            'name'=>'sortOrder',
            'type'=>'raw',
            'value'=>'CHtml::textField("sortOrder[$data->menuId]",$data->sortOrder,array("style"=>"width:50px;"))',
            'htmlOptions'=>array("width"=>"50px"),
        ),
        array(
            'name'=>'isActive',
            'header'=>'Active',
            'filter'=>array('1'=>'Yes','0'=>'No'),
            'value'=>'($data->isActive=="1")?("Yes"):("No")'
        ),
        array(
            'class'=>'CButtonColumn',
        ),
    ),
)); ?>
<script>
function reloadGrid(data) {
    $.fn.yiiGridView.update('menu-grid');
}
</script>
<?php echo CHtml::ajaxSubmitButton('Filter',array('menu/ajaxupdate'), array(),array("style"=>"display:none;")); ?>
<?php echo CHtml::ajaxSubmitButton('Activate',array('menu/ajaxupdate','act'=>'doActive'), array('success'=>'reloadGrid')); ?>
<?php echo CHtml::ajaxSubmitButton('In Activate',array('menu/ajaxupdate','act'=>'doInactive'), array('success'=>'reloadGrid')); ?>
<?php echo CHtml::ajaxSubmitButton('Delete',array('menu/ajaxupdate','act'=>'doDelete'), array('success'=>'reloadGrid')); ?>
<?php echo CHtml::ajaxSubmitButton('Update sort order',array('menu/ajaxupdate','act'=>'doSortOrder'), array('success'=>'reloadGrid')); ?>
<?php $this->endWidget(); ?>
From above code you may wonder why i have taken Filter invisible button, reason is if you don't put it and type something in filter boxed and press enter it will invoke 'Active' button, as it the first submit button in form, you may also try some other options.

Save all grid data into database: 

Looking into controller file.
public function actionAjaxupdate()
{
    $act = $_GET['act'];
    if($act=='doSortOrder')
    {
        $sortOrderAll = $_POST['sortOrder'];
        if(count($sortOrderAll)>0)
        {
            foreach($sortOrderAll as $menuId=>$sortOrder)
            {
                $model=$this->loadModel($menuId);
                $model->sortOrder = $sortOrder;
                $model->save();
            }
        }
    }
    else
    {           
        $autoIdAll = $_POST['autoId'];
        if(count($autoIdAll)>0)
        {
            foreach($autoIdAll as $autoId)
            {
                $model=$this->loadModel($autoId);
                if($act=='doDelete')
                    $model->isDeleted = '1';
                if($act=='doActive')
                    $model->isActive = '1';
                if($act=='doInactive')
                    $model->isActive = '0';                     
                if($model->save())
                    echo 'ok';
                else
                    throw new Exception("Sorry",500);
 
            }
        }
    }
}
Friends, hope this may help to newbies like me :)
Share your comments for any bug or issue, Also if you have any new thing in GRID which can be helpful in admin CRUD please share your thoughts.
I am using MasterAdmin class for auto set model values, you can check it HERE
Happy Coding!

Popular posts from this blog

Yii, return to previous url after login or logout

If you want to return to your previous url after login or logout try this : <?php $this -> redirect (Yii :: app () -> request -> urlReferrer ); ?> To set the return url to be the url that was before the login page or registeration page was called you can put following code in views/layouts/main.php file : <?php //this checks id the controller action is not 'login' then it keeps the current url in returnUrl if (CController :: getAction () -> id != 'login' ) { Yii :: app () -> user -> setReturnUrl (Yii :: app () -> request -> getUrl ()); } ?>

Yii2: Using csrf token

Yii2: Using csrf token First, if you do not understand what is the CSRF token? and why should we use it, please refer to the following link : https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) One of the new features of Yii2 is CSRF validation enabled by default. If you use ajax or basic form as follows : <form action='#' method='POST'> ........... </form> You will get an error exception : Bad Request (#400): Unable to verify your data submission That is because you do not submit csrf token. The easiest way if you dont care about csrf just disable it in main config : 'components' => [ 'request' => [ .... 'enableCsrfValidation'=>false, ], ..... ], Or in Controller : public function beforeAction($action) { $this->enableCsrfValidation = false; return parent::beforeAction($action); } So how to use Csrf Validation for your strong security website: * Wi