Menus

Saturday 12 November 2016

Dynamic Forms in Yii2 Operations


yii2-dynamicform

It is widget to yii2 framework to clone form elements in a nested manner, maintaining accessibility. 


Installation

The preferred way to install this extension is through composer.
Either run
php composer.phar require --prefer-dist wbraganca/yii2-dynamicform "*"
or add
"wbraganca/yii2-dynamicform": "*"
to the require section of your composer.json file.

Videos



Project Starting 


Step 1

First create table of po and po_item and relationship

Po table Structure


      * Set id as primary and auto increment

Po_item table Structure

     * Set id as primary and auto increment
     * po_id set INDEX

Now the next thing we have to create a relationship po_item.




Step 2

Using gii to create model, controller and view (CRUD Operations)






Step 3

Create operations

Edit view file _form.php under views/po
Edit controller file PoController.php under controllers
Add new file Model.php in models
Edit model PoItem.php, po_id property removed required 



Output View



The View   _form.php


<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;

?>

<div class="po-form">

    <?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>

    <?= $form->field($model, 'po_no')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'description')->textInput(['rows' => 6]) ?>

    
    <!--poitems-->    
    <div class="row">
        <div class="panel panel-default">
        <div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Po Items </h4></div>
        <div class="panel-body">
             <?php DynamicFormWidget::begin([
                'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
                'widgetBody' => '.container-items', // required: css class selector
                'widgetItem' => '.item', // required: css class
                'limit' => 4, // the maximum times, an element can be cloned (default 999)
                'min' => 1, // 0 or 1 (default 1)
                'insertButton' => '.add-item', // css class
                'deleteButton' => '.remove-item', // css class
                'model' => $modelsPoItem[0],
                'formId' => 'dynamic-form',
                'formFields' => [
                    'po_item_no',
                    'quantity',                
                ],
            ]); ?>

            <div class="container-items"><!-- widgetContainer -->
            <?php foreach ($modelsPoItem as $i => $modelPoItem): ?>
                <div class="item panel panel-default"><!-- widgetBody -->
                    <div class="panel-heading">
                        <h3 class="panel-title pull-left">Po Item</h3>
                        <div class="pull-right">
                            <button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
                            <button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
                        </div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="panel-body">
                        <?php
                            // necessary for update action.
                            if (! $modelPoItem->isNewRecord) {
                                echo Html::activeHiddenInput($modelPoItem, "[{$i}]id");
                            }
                        ?>
                        
                        <div class="row">
                            <div class="col-sm-6">
                                <?= $form->field($modelPoItem, "[{$i}]po_item_no")->textInput(['maxlength' => true]) ?>
                            </div>
                            <div class="col-sm-6">
                                <?= $form->field($modelPoItem, "[{$i}]quantity")->textInput(['maxlength' => true]) ?>
                            </div>
                        </div><!-- .row -->
                        
                    </div>
                </div>
            <?php endforeach; ?>
            </div>
            <?php DynamicFormWidget::end(); ?>
        </div>
    </div>
    </div>
    
    <!--poitems-->    
    
    
    
    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

Javascript Events


$(".dynamicform_wrapper").on("beforeInsert", function(e, item) {
    console.log("beforeInsert");
});

$(".dynamicform_wrapper").on("afterInsert", function(e, item) {
    console.log("afterInsert");
});

$(".dynamicform_wrapper").on("beforeDelete", function(e, item) {
    if (! confirm("Are you sure you want to delete this item?")) {
        return false;
    }
    return true;
});

$(".dynamicform_wrapper").on("afterDelete", function(e) {
    console.log("Deleted item!");
});

$(".dynamicform_wrapper").on("limitReached", function(e, item) {
    alert("Limit reached");
});


The Controller (sample code)

<?php

namespace backend\modules\dynamicform\controllers;

use Yii;
use backend\modules\dynamicform\models\Po;
use backend\modules\dynamicform\models\PoSearch;
use backend\modules\dynamicform\models\PoItem;
use backend\modules\dynamicform\models\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;

/**
 * PoController implements the CRUD actions for Po model.
 */
class PoController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Po models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PoSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Po model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Po model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    
    public function actionCreate()
    {
        $model = new Po();
        $modelsPoItem = [new PoItem];

        if ($model->load(Yii::$app->request->post())) {

            
            $modelsPoItem = Model::createMultiple(PoItem::classname());
            Model::loadMultiple($modelsPoItem, Yii::$app->request->post());

            // validate all models
            $valid = $model->validate();
            $valid = Model::validateMultiple($modelsPoItem) && $valid;

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    if ($flag = $model->save(false)) {
                        foreach ($modelsPoItem as $modelPoItem) 
                            {                            
                            $modelPoItem->po_id = $model->id;
                            if (! ($flag = $modelPoItem->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                    }
                    if ($flag) {
                        $transaction->commit();
                        return $this->redirect(['view', 'id' => $model->id]);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
        
            
        }
        
        else {
            return $this->render('create', [
                'model' => $model,
                'modelsPoItem' => (empty($modelsPoItem)) ? [new PoItem] : $modelsPoItem
            ]);
        }
    }
    


    /**
     * Updates an existing model.     
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $modelsPoItem = $model->poItems;

        if ($model->load(Yii::$app->request->post())) {
            
            $oldIDs = ArrayHelper::map($modelsPoItem, 'id', 'id');
            $modelsPoItem = Model::createMultiple(PoItem::classname(), $modelsPoItem);
            Model::loadMultiple($modelsPoItem, Yii::$app->request->post());
            $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsPoItem, 'id', 'id')));

            // validate all models
            $valid = $model->validate();
            $valid = Model::validateMultiple($modelsPoItem) && $valid;

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    if ($flag = $model->save(false)) {
                        if (! empty($deletedIDs)) {
                            PoItem::deleteAll(['id' => $deletedIDs]);
                        }
                        foreach ($modelsPoItem as $modelPoItem) {
                            $modelPoItem->po_id = $model->id;
                            if (! ($flag = $modelPoItem->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                    }
                    if ($flag) {
                        $transaction->commit();
                        return $this->redirect(['view', 'id' => $model->id]);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
            
        
        } 
        else {
             return $this->render('update', [
            'model' => $model,
            'modelsPoItem' => (empty($modelsPoItem)) ? [new Address] : $modelsPoItem
            ]);
    
        }
    }

    /**
     * Deletes an existing Po model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        PoItem::deleteAll(['po_id'=>$id]);
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Po model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Po the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Po::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


Model Class  Model.php


<?php
//add your name space
namespace backend\modules\dynamicform\models;

use Yii;
use yii\helpers\ArrayHelper;

class Model extends \yii\base\Model
{
    /**
     * Creates and populates a set of models.
     *
     * @param string $modelClass
     * @param array $multipleModels
     * @return array
     */
    public static function createMultiple($modelClass, $multipleModels = [])
    {
        $model    = new $modelClass;
        $formName = $model->formName();
        $post     = Yii::$app->request->post($formName);
        $models   = [];

        if (! empty($multipleModels)) {
            $keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
            $multipleModels = array_combine($keys, $multipleModels);
        }

        if ($post && is_array($post)) {
            foreach ($post as $i => $item) {
                if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']])) {
                    $models[] = $multipleModels[$item['id']];
                } else {
                    $models[] = new $modelClass;
                }
            }
        }

        unset($model, $formName, $post);

        return $models;
    }
}



Links
https://github.com/wbraganca/yii2-dynamicform#the-controller-sample-code


Please write your valuable comments 


Friday 4 November 2016

Updating Gridview Using Pajax


How to  save data to show grid view using ajax in yii2 ?


Here is a example on how to use Pjax with GridView (yii\grid\GridView) and ActiveForm (yii\widgets\ActiveForm) widgets in Yii2.


Output Form





The example uses a db table "itemsgrid" with field id, item_code, item_name, item_price.





index methord in Controller


    public function actionIndex()
    {
        
        $model = new Itemsgrid();

        if ($model->load(Yii::$app->request->post()) && $model->save())
        {
            $model = new Itemsgrid(); //reset model
        }        
        
        $searchModel = new ItemsgridSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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


index.php in Views



<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;


$this->title = 'Itemsgrids';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="itemsgrid-index">

    <br>
    <h1>Add Items in Stock</h1>
    <br>
    
<!-- Render create form -->    
    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>
    
    <br><br>
    
    <?php Pjax::begin(['id' => 'itemsgridtable']) ?>
    
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        //'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

          //  'id',
            'item_code',
            'item_name',
            'item_price',

            //['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
    
    <?php Pjax::end() ?>
    
</div>


_form.php in Views


<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;

?>

<?php

$this->registerJs(
   '$("#new_itemsgrid").on("pjax:end", function() {
        //commonLib.divAction("#div_new_model", "hide"); //hide form
        $.pjax.reload({container:"#itemsgridtable"});  //Reload GridView
    });', \yii\web\View::POS_READY
);
?>

<div class="itemsgrid-form">
    
    <?php yii\widgets\Pjax::begin(['id' => 'new_itemsgrid']) ?>
    <?php $form = ActiveForm::begin(['options' => ['data-pjax' => true ]]); ?>

    <table><tr><td>
                <?= $form->field($model, 'item_code')->textInput(['maxlength' => true]) ?>                         
            </td><td>
                <?= $form->field($model, 'item_name')->textInput(['maxlength' => true]) ?>
            </td><td>
                <?= $form->field($model, 'item_price')->textInput(['maxlength' => true]) ?>
            </td><td>
                <div class="form-group">
                    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
                </div>
            </td>    
    </tr></table>
    
    

    <?php ActiveForm::end(); ?>
    <?php yii\widgets\Pjax::end() ?>
    
</div>


www.yiiframework.com/wiki/772/pjax-on-activeform-and-gridview-yii2/

Yii2: Updating Grid-view using Pjax


Wednesday 2 November 2016

Yii2 Usefull Tips



Filter to force lowercase or uppercase on all operations


Use this way
['username', 'filter', 'filter'=>'strtolower'],
Add this code  your model in rules


 public function rules()
    {
        return [
            [['item_code', 'item_name', 'amount','qty'], 'required'],
            [['opening_stock', 'stock','addstock','qty'], 'integer'],
            [['amount'], 'number'],
            [['item_code'], 'string', 'max' => 20],
            [['item_name'], 'string', 'max' => 150],
            [['item_name'], 'unique'],            
            [['item_name','item_code'], 'filter', 'filter'=>'strtoupper'],
        ];
    }


How to set timezone in yii


When someone is reffering to application property or application config it means "root" config variable, in this case timeZone.
Config part:
<?php
// in protected/config/main.php
return array(
    'timeZone' => 'Asia/Calcutta'
    // Other configuration....
);

Example

project_folder/common/config/main.php

<?php
return [
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
    ],
    'timeZone' => 'Asia/Calcutta', //Time zone set
];



Configure at common/config/main.php:
'components' => [
    ...
    'formatter' => [
        'class' => 'yii\i18n\Formatter',
        'dateFormat' => 'php:j M Y',
        'datetimeFormat' => 'php:j M Y H:i',
        'timeFormat' => 'php:H:i',
        'timeZone' => 'Europe/Berlin',
    ],




Thursday 27 October 2016

Yii Tabular Input


Yii2 Insert multiple records of a same table




Collecting Tabular Input

           Sometimes we want to collect user input in a batch mode. That is, the user can enter the information for multiple model instances and submit them all at once. We call this tabular input because the input fields are often presented in an HTML table.
          To work with tabular input, we first need to create or populate an array of model instances, depending on whether we are inserting or updating the data. We then retrieve the user input data from the $_POST variable and assign it to each model. A slight difference from single model input is that we retrieve the input data using $_POST['ModelClass'][$i] instead of$_POST['ModelClass'].

In contrast to the single model forms explained before, we are working with an array of models now. This array is passed to the view to display the input fields for each model in a table like style and we will use helper methods of yii\base\Model that allow loading and validating multiple models at once:

This example for validate and save tabular data. Help to avoid insert many times the same table with ActiveForm.



Modify your controller code to use multiple models


<?php

namespace backend\modules\tools\controllers;

use Yii;
use backend\modules\tools\models\Products;
use backend\modules\tools\models\ProductsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\base\Model;

/**
 * ProductsController implements the CRUD actions for Products model.
 */
class ProductsController extends Controller
{

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

public function actionCreate()
    {

        //Find out how many products have been submitted by the form
        //$count = count(Yii::$app->request->post('Product', []));
        $count=4;

        //Send at least one model to the form
        $prts = [new Products()];

        //Create an array of the products submitted
        for($i = 1; $i < $count; $i++) {
            $prts[] = new Products();
        }
        
        
        //Load and validate the multiple models
        if (Model::loadMultiple($prts, Yii::$app->request->post()) && Model::validateMultiple($prts)) {

            foreach ($prts as $product) {

                //Try to save the models. Validation is not needed as it's already been done.
                $product->save(false);

            }
            return $this->redirect('view');
        }

        return $this->render('create', ['prts' => $prts]);
                
    }

..........
...........
}


 The view file for the form needs to be altered like this, to use the multiple models;


<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\modules\tools\models\Products */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="products-form">

    <?php $form = ActiveForm::begin(); ?>
 
   <table>
        <tr>
            <td>Product Name</td>
            <td>Product Qty</td>
            <td>Product Price</td>
        </tr>
        <?php foreach ($prts as $index => $product) { ?>       
        <tr>            
            <td><?= $form->field($product, "[$index]product_name")->textInput(['maxlength' => true])->label(FALSE) ?></td>
            <td><?= $form->field($product, "[$index]product_quantity")->textInput()->label(FALSE) ?></td>
            <td><?= $form->field($product, "[$index]product_price")->textInput(['maxlength' => true])->label(FALSE) ?></td>        
        </tr> 
       <?php } ?>
    </table>
     
    <div class="form-group">
        <?= Html::submitButton($product->isNewRecord ? 'Create' : 'Update', ['class' => $product->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>


View shows




Solutions:
I want to add multiple records from a form into a table.



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..