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';

             $inputFileType = \PHPExcel_IOFactory::identify($inputFiles);
             $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
             $objPHPExcel = $objReader->load($inputFiles);
         } catch (Exception $ex) {             
         $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];

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'];

break (PHP 4, PHP 5)

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


                        echo $model[$i]['month_year'];    
                        if($i<12) break;

while ($result_row = mysql_fetch_assoc($query))
    echo $result_row['id'];

Tuesday, 18 August 2015


Steps in Use DropDwonList

In controller

          $model = new SomeModel();


          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

    $model->palce_or_subcenter = Yii::$app->user->identity->subcenter;   //default value set
    echo $form->field($model, 'palce_or_subcenter')->dropDownList(
                    ['prompt'=>'Select One']

Yii2 dropdownList select default option

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


readonly dropdown

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(

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.

    function($model, $defaultValue) {
        return $model['medicine_name'].'-'.$model['medicine_id'];


<?= $form->field($modelSalesitem, "[{$i}]stockitem_id")
                                    'stockitem_id' ,  function($model, $defaultValue) {
                                                    return $model['stockitem']['item_name'].'    -'.$model['stock'].'  -                                                     -'.$model['amount'];}),

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

Thursday, 13 August 2015

Yii2 more useful programming tips.

Returns the values of a specified column in an array.

getColumn() public method
Returns the values of a specified column in an array.
The input array should be multidimensional or an array of objects.
For example,
$array = [
    ['id' => '123', 'data' => 'abc'],
    ['id' => '345', 'data' => 'def'],
$result = ArrayHelper::getColumn($array, 'id');
// the result is: ['123', '345']

// using anonymous function
$result = ArrayHelper::getColumn($array, function ($element) {
    return $element['id'];

Automatic Logout after 30 minutes of inactive

$authTimeout public property
The number of seconds in which the user will be logged out automatically if he remains inactive. If this property is not set, the user will be logged out after the current session expires (c.f. yii\web\Session::$timeout). 

Add your config/web.php file

'user' => [
            'identityClass' => 'app\models\User',
            //'enableAutoLogin' => true,
            'enableSession' => true,
            'authTimeout' => 60,

CheckboxList Advanced Operations

Yii2.0 CheckboxList items as checked as the form loads?

 HTML Helper checkboxlist

Method of check boxes to be checked as the form loads.

$list = [0 => 'PHP', 1 => 'MySQL', 2 => 'Javascript'];

$list2 = [0,2];

using the following line

<?= Html::checkboxList('CuisineId',$list2,$list); ?>

Output as above and below codes 

Other Way:

Just to add the following line of codes

$record->CuisineId = $list2;
<?= $form->field($record, 'CuisineId')->checkboxlist($list);?> 

Monday, 3 August 2015

Configuration of Layouts, Asset and Theme Integration

Yii2 AdminLTE


Layout file located at views/layouts/main.php


Theme Integration

AdminLTE download last version.

Installation Steps in GitHub

Yii2 AdminLTE  header section add menu in Navbar Left side

Edit file header.php in views/layouts

add this code

use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;

/* @var $this \yii\web\View */
/* @var $content string */

<header class="main-header">

    <?= Html::a('<span class="logo-mini">APP</span><span class="logo-lg">' . Yii::$app->name . '</span>', Yii::$app->homeUrl, ['class' => 'logo']) ?>

    <nav class="navbar navbar-static-top" role="navigation">

        <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
            <span class="sr-only">Toggle navigation</span>
       <!-- Navbar left Menu -->
        <ul class="nav navbar-nav">
          <li ><a href="index.php?r=master%2Fsalespayments%2Fcreate&type=s"><span class="fa fa-shopping-cart"></span></a></li>        



Saturday, 1 August 2015

Role-Based Access Control (RBAC)

Role-Based Access Control (RBAC) provides a simple yet powerful centralized access control.

Using RBAC involves two parts of work. The first part is to build up the RBAC authorization data, and the second part is to use the authorization data to perform access check in places where it is needed.

Basic Concepts

A role represents a collection of permissions (e.g. creating posts, updating posts). A role may be assigned to one or multiple users. To check if a user has a specified permission, we may check if the user is assigned with a role that contains that permission.

Associated with each role or permission, there may be a rule. A rule represents a piece of code that will be executed during access check to determine if the corresponding role or permission applies to the current user. For example, the “update post” permission may have a rule that checks if the current user is the post creator. During access checking, if the user is NOT the post creator, he/she will be considered not having the “update post” permission.

Yii2 Lesson RBAC Part I
Yii2 Lesson RBAC Part II

Implementing a role based access control is a very easy process and you can even load your roles from the database if you want.

Creating necessary tables in the database

drop table if exists `auth_assignment`;
drop table if exists `auth_item_child`;
drop table if exists `auth_item`;
drop table if exists `auth_rule`;

create table `auth_rule`
`name` varchar(64) not null,
`data` text,
`created_at` integer,
`updated_at` integer,
    primary key (`name`)
) engine InnoDB;

create table `auth_item`
`name` varchar(64) not null,
`type` integer not null,
`description` text,
`rule_name` varchar(64),
`data` text,
`created_at` integer,
`updated_at` integer,
primary key (`name`),
foreign key (`rule_name`) references `auth_rule` (`name`) on delete set null on update cascade,
key `type` (`type`)
) engine InnoDB;

create table `auth_item_child`
`parent` varchar(64) not null,
`child` varchar(64) not null,
primary key (`parent`, `child`),
foreign key (`parent`) references `auth_item` (`name`) on delete cascade on update cascade,
foreign key (`child`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;

create table `auth_assignment`
`item_name` varchar(64) not null,
`user_id` varchar(64) not null,
`created_at` integer,
primary key (`item_name`, `user_id`),
foreign key (`item_name`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;

Setting up the config file

This is done by adding the following lines to the components section of your config file

'authManager' => [
                           'class' => 'yii\rbac\DbManager',
                           'defaultRoles' => ['guest'],

Building authorization data is all about the following tasks:

 • defining roles and permissions;
 • establishing relations among roles and permissions;
 • defining rules;
 • associating rules with roles and permissions;

 • assigning roles to users.