Menus

Wednesday 16 September 2015

YII2 Grid View Advanced Options


INDEX
Karthik Grid View
How to group data in Grid View
Grid View Export Configuration



Karthik Grid View


GridView Demo yii2-grid

GridView yii2-grid Installation and more options


           Karthik Gridview Expand







How to group data in Grid View

Demonstration examples and scenarios for Grouping data using \kartik\grid\GridView





Grid View Export Configuration


Example Grid Code:

$exportFilename = 'custom-filename_' . date("Y-m-d_H-m-s");

        $exportConfig = [

            GridView::HTML  => [
                'label'           => 'HTML',
                'icon'            => 'file-text',
                'iconOptions'     => ['class' => 'text-info'],
                'showHeader'      => TRUE,
                'showPageSummary' => TRUE,
                'showFooter'      => TRUE,
                'showCaption'     => TRUE,
                'filename'        => $exportFilename,
                'alertMsg'        => 'The HTML export file will be generated for download.',
                'options'         => ['title' => 'Hyper Text Markup Language'],
                'mime'            => 'text/html',
                'config'          => [
                    'cssFile' => 'http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css'
                ]
            ],
            GridView::CSV   => [
                'label'           => 'CSV',
                'icon'            => 'file-code-o',
                'iconOptions'     => ['class' => 'text-primary'],
                'showHeader'      => TRUE,
                'showPageSummary' => TRUE,
                'showFooter'      => TRUE,
                'showCaption'     => TRUE,
                'filename'        => $exportFilename,
                'alertMsg'        => 'The CSV export file will be generated for download.',
                'options'         => ['title' => 'Comma Separated Values'],
                'mime'            => 'application/csv',
                'config'          => [
                    'colDelimiter' => ",",
                    'rowDelimiter' => "\r\n",
                ]
            ],
            GridView::EXCEL => [
                'label'           => 'Excel',
                'icon'            => 'file-excel-o',
                'iconOptions'     => ['class' => 'text-success'],
                'showHeader'      => TRUE,
                'showPageSummary' => TRUE,
                'showFooter'      => TRUE,
                'showCaption'     => TRUE,
                'filename'        => $exportFilename,
                'alertMsg'        => 'The EXCEL export file will be generated for download.',
                'options'         => ['title' => 'Microsoft Excel 95+'],
                'mime'            => 'application/vnd.ms-excel',
                'config'          => [
                    'worksheet' => 'Worksheet',
                    'cssFile'   => ''
                ]
            ],
            GridView::PDF   => [
                'label'           => 'PDF',
                'icon'            => 'file-pdf-o',
                'iconOptions'     => ['class' => 'text-danger'],
                'showHeader'      => TRUE,
                'showPageSummary' => TRUE,
                'showFooter'      => TRUE,
                'showCaption'     => TRUE,
                'filename'        => $exportFilename,
                'alertMsg'        => 'The PDF export file will be generated for download.',
                'options'         => ['title' => 'Portable Document Format'],
                'mime'            => 'application/pdf',
                'config'          => [
                    'mode'          => 'c',
                    'format'        => 'A4-L',
                    'destination'   => 'D',
                    'marginTop'     => 20,
                    'marginBottom'  => 20,
                    'cssInline'     => '.kv-wrap{padding:20px;}' .
                        '.kv-align-center{text-align:center;}' .
                        '.kv-align-left{text-align:left;}' .
                        '.kv-align-right{text-align:right;}' .
                        '.kv-align-top{vertical-align:top!important;}' .
                        '.kv-align-bottom{vertical-align:bottom!important;}' .
                        '.kv-align-middle{vertical-align:middle!important;}' .
                        '.kv-page-summary{border-top:4px double #ddd;font-weight: bold;}' .
                        '.kv-table-footer{border-top:4px double #ddd;font-weight: bold;}' .
                        '.kv-table-caption{font-size:1.5em;padding:8px;border:1px solid #ddd;border-bottom:none;}',
                    'methods'       => [
                        'SetHeader' => [
                            ['odd' => $ourPdfHeader, 'even' => $ourPdfHeader]
                        ],
                        'SetFooter' => [
                            ['odd' => $ourPdfFooter, 'even' => $ourPdfFooter]
                        ],
                    ],
                    'options'       => [
                        'title'    => 'Custom Title',
                        'subject'  => 'PDF export',
                        'keywords' => 'pdf'
                    ],
                    'contentBefore' => '',
                    'contentAfter'  => ''
                ]
            ]
        ];



Example and usage


echo GridView::widget([

    'dataProvider' => $dataProvider,
    'formatter' => ['class' => 'yii\i18n\Formatter','nullDisplay' => ''],
    'columns' => $gridColumns,   
    
    'containerOptions' => ['style'=>'overflow: auto',], // only set when $responsive = false
    
    'pjax' => true,
      
    'beforeHeader'=>[
            [
            'columns'=>[
            ['content'=>$content, 'options'=>['colspan'=>count($gridColumns), 'class'=>'text-left warning']],            
            ],
            //'options'=>['class'=>'skip-export'] // remove this row from export
            ]
            ],
    
    
    'bordered' => true,
    'striped' => false,
    'condensed' => false,
    'responsive' => true,
    'hover' => true,
    'floatHeader' => true,
    //'floatHeaderOptions' => ['scrollingTop' => $scrollingTop],
    //'showPageSummary' => true,
    'panel' => [
        'type' => GridView::TYPE_PRIMARY,    
        'before' => 'Date : '.date('d-m-Y'),
        'heading' => '<i class="glyphicon glyphicon-user"></i>&nbsp;<b>UNIVERSITY PAYMENT REPORT</b>',
        //'after' => 'Search Criteria : '.$query,
        //'showFooter' => false,
    ],
    
    
    'exportConfig' => [
                 GridView::CSV   => [
                'label'           => 'CSV',
                'icon'            => 'file-code-o',
                'iconOptions'     => ['class' => 'text-primary'],
                'showHeader'      => FALSE,
                'showPageSummary' => TRUE,
                'showFooter'      => TRUE,
                'showCaption'     => TRUE,
                'filename'        => $exportFilename,
                'alertMsg'        => 'The CSV export file will be generated for download.',
                'options'         => ['title' => 'Comma Separated Values'],
                'mime'            => 'application/csv',
                'config'          => [
                    'colDelimiter' => ",",
                    'rowDelimiter' => "\r\n",
                ]
            ],
            GridView::EXCEL => [
                'label'           => 'Excel',
                'icon'            => 'file-excel-o',
                'iconOptions'     => ['class' => 'text-success'],
                'showHeader'      => TRUE,
                'showPageSummary' => TRUE,
                'showFooter'      => TRUE,
                'showCaption'     => TRUE,
                'filename'        => $exportFilename,
                'alertMsg'        => 'The EXCEL export file will be generated for download.',
                'options'         => ['title' => 'Microsoft Excel 95+'],
                'mime'            => 'application/vnd.ms-excel',
                'config'          => [
                    'worksheet' => 'Worksheet',
                    'cssFile'   => ''
                ]
            ],
            ],

   
      
     // set your toolbar
    'toolbar'=> [
        ['content'=>
            Html::a('<i class="glyphicon glyphicon-plus"></i>',['universitypayment/index'], ['title'=>'Add New Criteria', 'class'=>'btn btn-success']), 
            
        ],
        '{export}',
        //'{toggleData}',
    ],
        
]);




Some examples of grid export
http://demos.krajee.com/grid#grid-export





Wednesday 2 September 2015

Yii2 Validation

Yii2 Validate value without model

Ad Hoc Validation


Yii2 email Validate without model


Sometimes you need to do ad hoc validation for values that are not bound to any model.
If you only need to perform one type of validation (e.g. validating email addresses), you may call the validate() method of the desired validator, like the following:

$email 'test@example.com';$validator = new yii\validators\EmailValidator();

if ($validator->validate($email$error)) {
    echo 'Email is valid.';
} else {
    echo $error;
}




PHP Code for email validation

Validating email addresses with filter_var()

<?php

$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_b) email address is considered valid.";
}

?>







Sunday 30 August 2015

Importing data from Excel Sheet


How to load Phpexcell in yii2


 "phpoffice/phpexcel": "dev-develop"


Put this code in composor.json and do a composer update.

open project folder in teminal and do composer update

First create a excell sheet same fields as import table.



Controller Action




 public function actionImportexcel()
    {

         $inputFiles = 'uploads/branches.xlsx';

         
         try{
             $inputFileType = \PHPExcel_IOFactory::identify($inputFiles);
             $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
             $objPHPExcel = $objReader->load($inputFiles);
             
         } catch (Exception $ex) {             
             die('Error');
         }
                  
         $sheet = $objPHPExcel->getSheet(0);
         $highestRow = $sheet->getHighestRow();
         $highestColumn = $sheet->getHighestColumn();
         
         //$row is start 2 because first row assigned for heading.         
         for($row=2; $row<=$highestRow; ++$row)
         {                  
         
             $rowData = $sheet->rangeToArray('A'.$row.':'.$highestColumn.$row,NULL,TRUE,FALSE);
             
            //save to branch table.
             $branch = new Branches;
             
             $branch->branch_id = $rowData[0][0];
             $branch->companies_company_id = $rowData[0][1];
             .
             .
             .
             $branch->save();
             
         }
    }




Video for Importing Excel Sheet















Saturday 29 August 2015

PHP knowledge for studying of Yii framework.



Two conditions in a for loop


$s = 1;

while ($result_row = mysql_fetch_assoc($query) && $s < 5)
{
echo $result_row['id'];
$s++;
}



break (PHP 4, PHP 5)

break ends execution of the current for, foreach, while, do-while or switch structure.


Examples:

            for($i=0;$i<count($model);$i++)
                    {
                        echo $model[$i]['month_year'];    
                        if($i<12) break;
                    }  




$s=1
while ($result_row = mysql_fetch_assoc($query))
{
    echo $result_row['id'];
    $s++;
    if($s>5){
        break;
    }
}







Tuesday 18 August 2015

DropDownList



Steps in Use DropDwonList


In controller


          $model = new SomeModel();

          $items=ArrayHelper::map(ModelName::find()->all(),'id','name');

          return $this->render('view',['model'=>$model, 'items'=>$items])


Add in view

         <?php $form = ActiveForm::begin(); ?>

                 <?= $form->field($model, 'item_id')->dropDownList($items) ?>


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


-----------------




Method of Add in DropDwonList in activeform

<?=
          $form->field($model, 'permissions')->dropDownList($model->getPermissions(),
         ['prompt'=>'- Choose Your Permissions -']) 
?>



<?= 
         $form->field($model, 'company_status')->dropDownList([ 'ACTIVE' => 'ACTIVE',                                 'INACTIVE' => 'INACTIVE', ], ['prompt' => 'Status']) 
?>



<?= 
          $form->field($model, 'status')->dropDownList([ 'Active' => 'Active', 'Droped' =>                         'Droped', 'Completed' => 'Completed', ],['selected'=>true], ['prompt' => '']) 
?>



Click to view - Dependent Drop Down List Tutorials



Default Selection DropDownList Yii2

<?php
 
    $model->palce_or_subcenter = Yii::$app->user->identity->subcenter;   //default value set
    echo $form->field($model, 'palce_or_subcenter')->dropDownList(
                    ArrayHelper::map(Groupitems::find()->andwhere(['category'=>6])->andwhere(['!=','id',0])->orderBy('description')->all(),'slid','description'),
                    ['prompt'=>'Select One']
                    );
 ?>

Yii2 dropdownList select default option

<?= $form->field($model, 'ccid')->dropDownList(
                        getCenter(),['options' => [$ccid => ['Selected'=>'selected']]) ?>

'options'=>['72'=>['Selected'=>true]]


readonly dropdown


"disabled"=>"disabled" 
instead of "readonly"=>true





Set Dropdown list width in yii2


You can just add style in dropDownList show below code


'style' => 'width:90px !important'


<?= $form->field($model, 'experience_month')->dropDownList([ '0' => 0,'1'=>1,'2'=>2,'3'=>3,'4'=>4,'5'=>5 ,'6'=>6,'7'=>7,'8'=>8,'9'=>9,'10'=>10,'11'=>11], 
['style' => 'width:90px !important', 'prompt' => 'Month'])->label('Year & Month') ?>



Yii2 Display DropDownList Values Using funtion


make a function in your model to return an array of your list


public function getOptions()
{
   return array(
      'EASY',
      'MEDIUM',
      'HARD',
   );
}

then you could use it like this


echo $form->dropdownList($model , 'category' , $model->options); // this will use that function to get the array



yii2:drop-down list for multiple values concat in one line


use this code concat multiple fields in single line.


ArrayHelper::map(\app\models\Medicine::find()->asArray()->all(),
    'id',
    function($model, $defaultValue) {
        return $model['medicine_name'].'-'.$model['medicine_id'];
    }
)


Example

<?= $form->field($modelSalesitem, "[{$i}]stockitem_id")
                                    ->dropDownList(
                                    ArrayHelper::map(Stockcenter::find()->where(['center_ccid'=>1])->all(),       
                                    'stockitem_id' ,  function($model, $defaultValue) {
                                                    return $model['stockitem']['item_name'].'    -'.$model['stock'].'  -                                                     -'.$model['amount'];}),

                                            ['prompt'=>'Select Item']          
                                            )->label(FALSE); ?>