Menus

Monday, 25 April 2016

Yii2 Grid View Operations


INDEX
Adding Classes to Rows in the GridView
Grid view action column change
Yii2 Gridview merge two columns
Yii2 Gridview change column background and text color



Gridview In Yiiframework 2.0


In yiiframework 2.0, The gridview widget is used to display the data like image, text, etc in a grid. It is having a lot features like sorting, pagination, filtering, styling etc.


Adding Classes to Rows in the GridView

Yii2 Gridview row by row css expression



Dynamically change GridView Row Background Color based on condition 


<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
     
       //Check conditions and add to row color in gridview.
        'rowOptions' => function ($model){
          if($model->status == 0){
            return ['class' => 'danger'];
          }else{
            return ['class' => 'success'];
          }
        },
             
        'columns' => [          
            [
                'header' =>'Sl.No',
                'class' => 'yii\grid\SerialColumn',            
                'options' => ['width' => '50']
            ],          
            'eid',          
            [
                'attribute' => 'expence_date',
       'format' =>  ['date', 'php:d-m-Y'],
       'options' => ['width' => '150'],              
   ],
            'pay_to',
            'description',          
            [                              
                            'attribute'=>'head',
                            'content' => function($data){
                                        return Groupitems::getGroupitems($data->head);
                                        }
                            ],
            'amount',
            [        
                'class' => 'yii\grid\ActionColumn',
                'contentOptions' => ['style' => 'width:60px;'],
                'header'=>'Actions',
            ],
        ],
    ]); ?>



Output of above script







Grid view action column change


How to change view, update and delete url on action column in yii2


[
          'class' => 'yii\grid\ActionColumn',
          'header' => 'Actions',
          'headerOptions' => ['style' => 'color:#337ab7'],
          'template' => '{view}{update}{delete}',
          'buttons' => [
            'view' => function ($url, $model) {
                return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url, [
                            'title' => Yii::t('app', 'lead-view'),
                ]);
            },

            'update' => function ($url, $model) {
                return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [
                            'title' => Yii::t('app', 'lead-update'),
                ]);
            },
            'delete' => function ($url, $model) {
                return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
                            'title' => Yii::t('app', 'lead-delete'),
                ]);
            }

          ],
          'urlCreator' => function ($action, $model, $key, $index) {
            if ($action === 'view') {
                $url ='index.php?r=client-login/lead-view&id='.$model->id;
                return $url;
            }

            if ($action === 'update') {
                $url ='index.php?r=client-login/lead-update&id='.$model->id;
                return $url;
            }
            if ($action === 'delete') {
                $url ='index.php?r=client-login/lead-delete&id='.$model->id;
                return $url;
            }

          }
          ],

Example 1

I want to gridview action column only show edit and view button and change to url.




Gridview code here


    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [

        ....
        .....                                  

        [
          'class' => 'yii\grid\ActionColumn',
          'header' => 'Actions',
          'headerOptions' => ['style' => 'color:#337ab7'],
          'template' => '{view}{update}',
          'buttons' => [
            'view' => function ($url, $model) {
                return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url, [
                            'title' => Yii::t('app', 'view-student'),
                ]);
            },

            'update' => function ($url, $model) {
                return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [
                            'title' => Yii::t('app', 'update-register number'),
                ]);
            },
            

          ],

          'urlCreator' => function ($action, $model, $key, $index) {
            if ($action === 'view') {                
                $url = 'index.php?r=master/students/view&ccid='.$model->ccid.'&admission_number='.$model->admission_number;
                return $url;
            }

            if ($action === 'update') {
                $url = 'index.php?r=master/students/addregisternochange&ccid='.$model->ccid.'&admission_number='.$model->admission_number;
                return $url;
            }
            
          }
          ],                            
                                        

    ], 
                                 
                                 
    ]); ?>




Example 1

This example gridview to show only view and edit without change url.


            [          
                'class' => 'yii\grid\ActionColumn',
                'contentOptions' => ['style' => 'width:50px;'],
                'header'=>'Actions',
                'template' => '{view} {update}',
            ], 



Yii2 Gridview merge two columns


//add columns in gridview

            [
                'label'=>'Rem/TotFee',
                'value' => function($model) { return $model->remitted_fee.'/'.$model->total_fee ;}
                 
            ],



Yii2 Gridview change column background and text color

Text colur

[
                'attribute'=>'student_name',
                'contentOptions' => function ($model, $key, $index, $column) {
                    if($model->employee_teachersid)            
                                return ['style' => 'color:green'];
                    else
                                return ['style' => 'color:black'];
                }
            ],

Background color

        [
                'label'=>'Rem/TotFee',
                'value'=> function($data)
                  {  
                      return  $data->remitted_fee.'/'.$data->total_fee;              
                  },
                          
                'contentOptions' => function ($model, $key, $index, $column) {
                                             
                        if($model->remitted_fee < $model->total_fee){
                           return ['style' => 'background-color:red'];     
                        }else{
                            return ['style' => 'background-color:lime'];
                        }
                        
                },          
                'format' => 'raw'              
            ], 


Gridview column text with badge

[
        'attribute'=>'color',
        'value'=>function ($model, $key, $index, $widget) {
            return "<span class='badge' style='background-color: {$model->color}'> </span>  <code>" . 
                $model->color . '</code>';
        },
        'filterType'=>GridView::FILTER_COLOR,
        'vAlign'=>'middle',
        'format'=>'raw',
        'width'=>'150px',
        'noWrap'=>true
    ],


Grid view column color with value


'value'=>function ($model, $key, $index, $widget) 
                  {  
                      
                            $d =  'Text here';
                            $color="red";
                            return "<td  style='background-color: {$color}'> {$d}</td> " ;
                          
                  },





Related Links

Yii2 gridview widget filter

YII2 Grid View Advanced Options

Yii2 grid with Editable column

Importing data from Excel Sheet




Tuesday, 22 March 2016

Event Calendar in Yii


A JavaScript event calendar.

 FullCalendar is great for displaying events.


Installation
Package is although registered at packagist.org - so you can just add one line of code, to let it run!
add the following line to your composer.json require section:
  "philippfrenzel/yii2fullcalendar":"*",
And ensure, that you have the follwing plugin installed global:
php composer.phar global require "fxp/composer-asset-plugin:~1.0"


Viedo for how to use event calendar in Yii2

Part I




Part II






Links


https://github.com/philippfrenzel/yii2fullcalendar
http://www.yiiframework.com/extension/yii2fullcalendar/
http://fullcalendar.io/



Steps in Implement Yii2 event calendar


Step 1
              Create Table event in Your database

Table structure for table `event`
--

CREATE TABLE IF NOT EXISTS `event` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(200) NOT NULL,
  `description` varchar(500) NOT NULL,
  `created_date` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;


Step 2

          Using Gii module create an event CRUD operations.
          Create Model, Controller and View of event table.

Check
http://localhost/yii2.7/backend/web/index.php?r=tools%2Fevent%2Findex



Step 3

Installation
add line to  composer.json require section:
  "philippfrenzel/yii2fullcalendar":"*",

and run command on terminal

sudo composer update

Calendar automatically update after few minutes.


Step 4


Edit EventController.php


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

        $events = Event::find()->all();
        
      $tasks=[];  
      foreach ($events AS $eve){
      //Testing
      $event = new \yii2fullcalendar\models\Event();
      $event->id = $eve->id;
      $event->backgroundColor='red';
      $event->title = $eve->title;
      $event->start = $eve->created_date; 
      
      $tasks[] = $event;
    }
        
        return $this->render('index', ['events' => $tasks,
            ]);
        
    }


 /**
     * Creates a new Event model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($date)
    {
        $model = new Event();
        $model->created_date = $date;
        

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            //return $this->redirect(['view', 'id' => $model->id]);
            return $this->redirect(['index']);
        } else {
            return $this->renderAjax('create', [
                'model' => $model,
            ]);
        }
    }


Edit view/Index.php 


<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\bootstrap\Modal;
use yii\helpers\Url;


/* @var $this yii\web\View */
/* @var $searchModel backend\modules\tools\models\EventSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

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

    <h1><?= Html::encode($this->title) ?></h1>
    

    <?php   //for popup create window
     modal::begin([
         'header'=>'<h4>Event<h4>',
         'id'=>'modal',
         'size'=>'modal-lg',         
     ]);
     echo "<div id='modalContent'></div>";
     modal::end();   
    ?>

<!-- Calender view -->
     <?= \yii2fullcalendar\yii2fullcalendar::widget(array(
      'events'=> $events,
  ));
    ?>
   
</div>


edit main.js files in backend/web/js
for popup create window

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
$(function(){
    $(document).on('click','.fc-day',function(){
        var date = $(this).attr('data-date');
        
        $.get('index.php?r=tools/event/create',{'date':date},function(data){
                $('#modal').modal('show')
                .find('#modalContent')
                .html(data);
        });
        
        
    });


$('#modalButton').click(function(){
    //get the click of the create button.
    $('#modal').modal('show')
            .find('#modalContent')
            .load($(this).attr('value'));
});
});


add main.js register in backend/assest/AppAssest.php

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace backend\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
    ];
    public $js = [
        'js/main.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}




AJAX Usage

If you wanna use ajax loader, this could look like this:
<?= yii2fullcalendar\yii2fullcalendar::widget([
      'options' => [
        'lang' => 'de',
        //... more options to be defined here!
      ],
      'ajaxEvents' => Url::to(['/timetrack/default/jsoncalendar'])
    ]);
?>
and inside your referenced controller, the action should look like this:
public function actionJsoncalendar($start=NULL,$end=NULL,$_=NULL){

    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    $times = \app\modules\timetrack\models\Timetable::find()->where(array('category'=>\app\modules\timetrack\models\Timetable::CAT_TIMETRACK))->all();

    $events = array();

    foreach ($times AS $time){
      //Testing
      $Event = new \yii2fullcalendar\models\Event();
      $Event->id = $time->id;
      $Event->title = $time->categoryAsString;
      $Event->start = date('Y-m-d\TH:i:s\Z',strtotime($time->date_start.' '.$time->time_start));
      $Event->end = date('Y-m-d\TH:i:s\Z',strtotime($time->date_end.' '.$time->time_end));
      $events[] = $Event;
    }

    return $events;
  }






Sunday, 6 March 2016

Installing Yii





Yii 2

The latest version of Yii 2 is 2.0.7, released on February 14, 2016. Yii 2.0 is a complete rewrite of Yii on top of PHP 5.4.0. It is aimed to become a state-of-the-art of the new generation of PHP framework. Yii 2.0 is not compatible with 1.1.
Yii2 Website.
Yii2 Documentation.

Installing Yii

  1. Installing via Composer
  2. Installing from an Archive File
  3. Other Installation Options
  4. Verifying the Installation
  5. Configuring Web Servers

You can install Yii in two ways, using the Composer package manager or by downloading an archive file. The former is the preferred way, as it allows you to install new extensions or update Yii by simply running a single command.


Steps - Install from an Archive File
  • Yii 2 with advanced application template       (Download one of the following archive files, and then extract it to a Web-accessible folder (eg /var/www/html).)
  • Yii Application Initialization.     eg var/www/html/yii2.7# php init
Open your browser goto  http://localhost/yii2.7/frontend/web/index.php
Get result is


Database Configuration
  1. Preparing the Database
  2. Configuring a DB Connection
  3. Creating an Active Record
  4. Creating an Action
  5. Creating a View

* Database configuration placed in the common/config directory of application folder.
/application/common/config/main_local.php

Example of set database configuration 
'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=students',
            'username' => 'root',
            'password' => 'root123',
            'charset' => 'utf8',
        ],

More Details

Migrate Database
yii basic working tables add to own database
This will create tables needed for the application to work.

Command for migration
php yii migrate

Video Installing the Advance Template in Yii



GETTING STARTED
After you install the application, you have to conduct the following steps to initialize
the installed application. You only need to do these once for all.
1. Run command `init` to initialize the application with a specific environment.
2. Create a new database and adjust the `components['db']` configuration in `common/config/main-local.php` accordingly.
3. Apply migrations with console command `yii migrate`. This will create tables needed for the application to work.
4. Set document roots of your Web server:
- for frontend `/path/to/yii-application/frontend/web/` and using the URL `http://frontend/`
- for backend `/path/to/yii-application/backend/web/` and using the URL `http://backend/`
To login into the application, you need to first sign up, with any of your email address, username and password.Then, you can login into the application with same email address and password at any time.