Menus

Tuesday, 27 September 2016

Yii2 grid with Editable column



How to save data in model using Yii2 grid with Editable column


Actually the solution is easy and need to the id of that specific row to update.
We are use ajax.


Explain how in Yii 2 Framework, we can setup the enhanced Krajee EditableColumn to work with theKrajee GridView widget. The objective is to achieve the following functionality using kartik\grid\GridView andkartik\grid\EditableColumn:
  1. configure a grid cell content to be editable
  2. use advanced input widgets to edit content
  3. capture the editable content POSTED via controller and update database via ajax
  4. trigger model validation and validation error messages if needed


Inputs

  • Editable::INPUT_HIDDEN or 'hiddenInput'
  • Editable::INPUT_TEXT or 'textInput'
  • Editable::INPUT_PASSWORD or 'passwordInput'
  • Editable::INPUT_TEXTAREA or 'textArea'
  • Editable::INPUT_CHECKBOX or 'checkbox'
  • Editable::INPUT_RADIO or 'radio'
  • Editable::INPUT_LIST_BOX or 'listBox'
  • Editable::INPUT_DROPDOWN_LIST or 'dropDownList'
  • Editable::INPUT_CHECKBOX_LIST or 'checkboxList'
  • Editable::INPUT_RADIO_LIST or 'radioList'
  • Editable::INPUT_HTML5_INPUT or 'input'
  • Editable::INPUT_FILE or 'fileInput'
  • Editable::INPUT_WIDGET or 'widget', use this for any custom widget class to be used

More Details


Yii2 Grid View add editable column









Most Popular Extension for Gridview Inline Edit is Kartik-v Yii2 Editable.
Few Reference Links and Demos:



Yii 2 Editable

Easily set any displayed content as editable in Yii Framework 2.0. This is an enhanced editable widget for Yii 2.0 that allows easy editing of displayed data, using inputs, widgets and more with numerous configuration possibilities.

More Details http://demos.krajee.com/editable

Date Control yii2-datecontrol


The Date Control module allows controlling date formats of attributes separately for View and Model for Yii Framework 2.0. 

More Details http://demos.krajee.com/datecontrol



Example


Editable Column type Editable::INPUT_DATE is not recognized as date by Formatter

Solution 1


[
    'class' => 'kartik\grid\EditableColumn',
    'attribute'=>'publish_date',
    'vAlign' => 'middle',
    'headerOptions' => ['class' => 'kv-sticky-column'],
    'contentOptions' => ['class' => 'kv-sticky-column'],
    'editableOptions' => [
        'header' => 'PublishDate', 
        'size' => 'md',
        'inputType'=>\kartik\editable\Editable::INPUT_WIDGET,
        'widgetClass'=> 'kartik\datecontrol\DateControl',
        'options'=>[
            'type'=>\kartik\datecontrol\DateControl::FORMAT_DATE,
            'options' => [
                'pluginOptions' => [
                    'autoclose' => true
                ]
            ]
        ]
    ],
],


Output as






Example

This example add editable column in kartik grid view.
This grid view contains three types of editable controls such as DATE, TEXTVIEW and DROP DOWN LIST.




***************************
Source code of above grid view.
***************************

Use packeges are
use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\editable\Editable;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;

 
$dataProvider->setPagination(false);
echo GridView::widget([
    'dataProvider' => $dataProvider,
    'formatter' => ['class' => 'yii\i18n\Formatter','nullDisplay' => ''],  
    'pjax'=>true,
    'export'=>false,
 
    'columns' => [
            ['class' => 'yii\grid\SerialColumn'],          

            [
                'attribute'=>'students_admission_number',
                'label'=>'ADD NO',
                'contentOptions' => ['style' => 'width:50px;'],                  
            ],
            [
                'attribute'=>'ccid',    
                'label'=>'Cid',
                'contentOptions' => ['style' => 'width:30px;'],
            ],
            [
                'attribute'=>'Name',              
                'value'=>'studentsAdmissionNumber.student_name',
            ],
            [
                'attribute'=>'semester_year',
                'label'=>'S/Y',
                'contentOptions' => ['style' => 'width:30px;'],
            ],  
            [
                'attribute' => 'requested_date',    
                'format' =>  ['date', 'php:d-m-Y'],              
            ],
         
            [
                'class' => 'kartik\grid\EditableColumn',
                'attribute'=>'issued_date',
                'vAlign' => 'middle',
                'headerOptions' => ['class' => 'kv-sticky-column'],
                'contentOptions' => ['class' => 'kv-sticky-column'],
                'format' =>  ['date', 'php:d-m-Y'],        
                'editableOptions' => [
                    'header' => 'Issued Date', 
                    'size' => 'md',
                    'inputType'=>\kartik\editable\Editable::INPUT_WIDGET,
                    'widgetClass'=> 'kartik\datecontrol\DateControl',
                    'options'=>[
                        'type'=>\kartik\datecontrol\DateControl::FORMAT_DATE,
                        'options' => [
                            'pluginOptions' => [
                                'autoclose' => true
                            ]
                        ]
                    ]
                ],
            ],
   
            [
                'class' => 'kartik\grid\EditableColumn',
                'header'=>'Remarks',
                'attribute' => 'remarks',
                'editableOptions'=> [
                    'format' => Editable::FORMAT_BUTTON,
                    'inputType' => Editable::INPUT_TEXTAREA,      
                ]
            ],

     
           [
                'class'=>'kartik\grid\BooleanColumn',
                'class' => 'kartik\grid\EditableColumn',

                'attribute'=>'status', 
                'vAlign'=>'middle',
                'editableOptions'=> [
                        //'format' => Editable::FORMAT_BUTTON,
                        'inputType' => Editable::INPUT_DROPDOWN_LIST,

                        'data' => [0 => 'No', 1 => 'Ok'],
                        'options' => ['class'=>'form-control'], //, 'prompt'=>'status...'],
                        'displayValueConfig'=> [
                            '0' => '<i class="glyphicon glyphicon-remove"></i>',
                            '1' => '<i class="glyphicon glyphicon-ok"></i>',                        
                        ],

                    ],
                ],
   
        ],
 
 
    'bordered' => true,
    'striped' => false,
    'condensed' => false,
    'responsive' => true,
    'hover' => true,
    'floatHeader' => true,
    'showFooter'=>TRUE,
    'panel' => [
        'type' => GridView::TYPE_PRIMARY,          
        'heading' => '<i class="fa fa-book"></i> <b>List of Study Materials for Despatch</b>',
    ],
 
    'toolbar' => [],

]);


**********************************
Controller called method includes codes 
**********************************

 public function actionDespatch(){
     
     
        $model = new StudentsstudymaterialsSearch();
     
        //codes for working editable columns
        if (Yii::$app->request->post('hasEditable')) 
        {

            $model =Yii::$app->request->post('editableKey');
              
            //my code 
            $data = json_decode($model, true); 
            
            $model  = $this->findModel($data['id'],$data['ccid']);
            $out    = Json::encode(['output'=>'', 'message'=>'']);
            
            $post = [];
            $posted = current($_POST['StudentsstudymaterialsSearch']);  //model
            $post['Studentsstudymaterials'] = $posted;
         
            if ($model->load($post)) {
            $model->save();
            $output = '';
            if (isset($posted['remarks'])) 
            {
              $output =  $model->remarks;
            }
            if (isset($posted['issued_date'])) 
            {
              $output =  date('d-m-Y',strtotime($model->issued_date));
            }
            
             $out = Json::encode(['output'=>$output, 'message'=>'']); 
          }
          
          $out = Json::encode(['output'=>$output, 'message'=>'']); 
          echo $out;
          return;
        }

         return $this->render('despatch',['model'=>$model]);
     
    }







Next Example


Easily set any displayed content as editable in Yii Framework 2.0


Ajax Usage Example for editable gridview


STEP 1: SETUP YOUR CONTROLLER ACTION
add this your header section

use yii\helpers\Json;



public function actionIndex()
    {

        $searchModel = new MastersettingsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        // Check if there is an Editable ajax request
        if (Yii::$app->request->post('hasEditable'))
        {

            $id =Yii::$app->request->post('editableKey');          
            $model  = $this->findModel($id);
           
            $out    = Json::encode(['output'=>'', 'message'=>'']);          
            $post = [];
            $posted = current($_POST['Mastersettings']);  //model
            $post['Mastersettings'] = $posted;
       
            if ($model->load($post)) {
                $model->save();              
           
            $output = '';
            if (isset($posted['status']))
            {
              $output =  $model->status;
              $out = Json::encode(['output'=>$output, 'message'=>'']);
            }                                              
          }
                 
         // return JSON encoded output in the below format
          echo $out;
          return;
        }
       
       
       
        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);

    }



STEP 2: SETUP WIDGET IN VIEW

<?php

use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\editable\Editable;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;

$this->title = 'Mastersettings';
$this->params['breadcrumbs'][] = $this->title;
?>

<div class="mastersettings-index">

    <?php
   
$dataProvider->setPagination(false);
echo GridView::widget([
    'dataProvider' => $dataProvider,
    'formatter' => ['class' => 'yii\i18n\Formatter','nullDisplay' => ''],
    'pjax'=>true,
    'export'=>false,
   
    'columns' => [
       
            [
                'class'=>'kartik\grid\BooleanColumn',
                'class' => 'kartik\grid\EditableColumn',
                'attribute'=>'status', 
                'vAlign'=>'middle',                
                'editableOptions'=> [
                        //'format' => Editable::FORMAT_BUTTON,
                        'inputType' => Editable::INPUT_DROPDOWN_LIST,
                    
                        'data' => [0 => 'Set', 1 => 'Not Set'],
                        'options' => ['class'=>'form-control'], //, 'prompt'=>'status...'],
                        'displayValueConfig'=> [
                            '0' => '<i class="glyphicon glyphicon-remove"></i>',                        
                            '1' => '<i class="glyphicon glyphicon-ok"></i>',                        
                        ],

                    ],                                
                ], 
       
            'description',      
        ],
       
    'bordered' => true,
    'striped' => false,
    'condensed' => false,
    'responsive' => true,
    'hover' => true,
    'floatHeader' => true,
           
    'panel' => [
        'type' => GridView::TYPE_PRIMARY,          
        'heading' => '<i class="fa fa-cog"></i> <b> DSMS online software master settings</b>',
    ],
         
    // set your toolbar
    'toolbar'=> [
    ],
   
]);


?>
   
   
</div>



More further details

http://demos.krajee.com/editable



Related Links

Yii2 Grid View Operations


Yii2 gridview widget filter


YII2 Grid View Advanced Options


Event Calendar in Yii


Note : Please add your valuable comments and add your tutorial links in comments column for helps to others..

4 comments:

  1. Hello everyboby,

    I installed the yii2-grid, yii2-editable and yii2-touchspin and the first row always returning an error message.

    "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"

    I can see too that the first row is calling a Get method instead of a Post method and I don't know why and how to fix it.

    I would appreciate a lot if someone helps me to figure out a fix to that!

    Thank in advance.

    That is my code:

    [
    'class' => 'kartik\grid\EditableColumn',
    'attribute' => 'qtyWishItemDonate',
    'editableOptions' => [
    'asPopover' => TRUE,
    'formOptions' => [ 'action' => [ 'wishitem', 'id' => $campaign->id ], 'id' => 'wishitemaction' ],
    'format' => \kartik\editable\Editable::FORMAT_BUTTON,
    'inputType' => \kartik\editable\Editable::INPUT_SPIN,
    'options' => [
    'pluginOptions' => [
    'min' => 1,
    'max' => 100,
    'buttonup_class' => 'btn btn-primary',
    'buttondown_class' => 'btn btn-info',
    'buttonup_txt' => '',
    'buttondown_txt' => '',
    ]
    ]
    ],
    'hAlign' => 'center',
    'width' => '100px',
    ],

    ReplyDelete
    Replies
    1. check method
      'formOptions' => [ 'action' => [ 'wishitem', 'id' => $campaign->id ], 'id' => 'wishitemaction' ],

      Delete
  2. coding curriculum A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post.

    ReplyDelete
  3. The website is looking bit flashy and it catches the visitors eyes. Design is pretty simple and a good user friendly interface. www.jensensvacandsew.com

    ReplyDelete