Wednesday, May 2, 2018

yii2 session handling

use  yii\web\Session;

$session = Yii::$app->session;

// start session
$session->open();

// close session
$session->close();

// destroys session.
$session->destroy();

//store value in session
$session['user_id'] = 2;

echo $session['user_id'];
//result will be 2

// check if a session is set
if ($session->isActive)

//unset session variable
unset($_SESSION['user_id']);

yii2 kartik datepicker

Step 1: Install below extension from github

$ php composer.phar require kartik-v/yii2-widget-datepicker "@dev"

Step 2: Use below code in your view file

use kartik\date\DatePicker;

// usage without model
echo '';
echo DatePicker::widget([
 'name' => 'birth_date', 
 'value' => date('d-M-Y'),
 'options' => ['placeholder' => 'Select birth date'],
 'pluginOptions' => [
  'format' => 'dd-M-yyyy',
 ]
]);

Tuesday, May 1, 2018

yii2 bootstrap modal popup

For implementing this you need to call default modal of Yii2 and begin and end modal is must

In step 2 you need to add javascipt for call the modal on button click.

In step 3 you need to create a action which render the data into your view.

How to add bootstrap modal in yii2

Add in your view:
//php code
Modal::begin([
    'header' => 'your header',
    'id'=>'modal',
     size'=>'modal-lg',
]);

echo '';

Modal::end();

Html::button('Button Name', ['value' => Url::to(['url/to']), 'title' => 'Title', 'class' => 'showModalButton btn btn-success']);

//javascript code
$('button').click(function(){
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
})

Add in your controller/action:
//php code
if(Yii::$app->request->isAjax){
        return $this->renderAjax('your-view-file', [
            'data' => $data,
        ]);

yii2 generate random string

You can easily generate random string using security class.

Yii2 generate unique number

$string = Yii::$app->security->generateRandomString(12);
        
        print_r($string);
//result
JCt-5GeUlR8q
      

yii2 gridview custom column

In this example you can see Name attribute using as custom column.

Yii2 gridview custom column

GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'id',
        'username',
        'created_at',
        [
       'label' => 'Name',
       'value' => function ($model) {
           return $model->user->first_name;
       }
     ],
        ['class' => 'yii\grid\ActionColumn'],
    ],
]);

Monday, April 30, 2018

yii2 custom validator

In this example create a function checkStatus() and apply in the rules like below:

If the status is false then it will display the error message.

Yii2 custom validation rules

//model file
public function rules()
    {
        return [
            [['status'], 'checkStatus'], 

            // other rules
        ];
    }

    public function checkStatus($attribute, $params)
    {
        if($this->status == false){
        $this->addError($attribute, 'Status cannot be false');
        }
        
    }

yii2 compare validation

In this example you can see password and password_again attributes comparing using compare and compareAttribute.

Another example is validates if price is greater than or equal to 5000 using the compare and compareAttribute.

Yii2 Compare validation Rules

[
    // validates "password" attribute equals to "password_again"
    ['password', 'compare'],

    // same as above but with explicitly specifying the attribute to compare with
    ['password', 'compare', 'compareAttribute' => 'password_again'],

    // validates if price is greater than or equal to 5000
    ['price', 'compare', 'compareValue' => 5000, 'operator' => '>=', 'type' => 'number'],
]

yii2 flash message

Yii2 session flash message

Write below code in your controller

Yii::$app->session->setFlash('success', "This is a flash message");

Write below code in your view

Yii::$app->session->getFlash('success');

yii2 dropdownlist onchange

Dropdownlist onchange example is showing below. In dropdownlist first attribute is $name ,second attribute should be null, third attribute is $items array and fourth attribute is $options. In this example we are using a callAFunction() on onchange method.

Yii2 Html dropdownlist onchange

use yii\helpers\Html;
Html::beginForm()
Html::dropDownList(
    'username', 
    'null',
    ['1'=>'abc', '2'=>'xyz'],
    ['onchange'=>'callAFunction()']);
 Html::endForm()

//Javascript function
function callAFunction(){
alert('I am here');
}


yii2 dropdownlist without model

Yii2 html dropdownlist

Dropdownlist without model example is showing below. In this section Arrayhelper and Html classes are uses. In dropdownlist the first attribute is $name ,the second attribute is $options and third attribute is $items array.

use yii\helpers\Html;
use yii\helpers\ArrayHelper;

Html::dropDownList('user_id', null,
      ArrayHelper::map(User::find()->all(), 'user_id', 'name'))

yii2 file upload

Input file upload Yii2

Steps:
1. Create a action fileUpload
2. Create a model FileUploadForm
3. Create a form

FileUploadForm model:

namespace backend\models;

use yii\base\Model;
use yii\web\UploadedFile;

class FileUploadForm extends Model
{
 
    public $Files;

    public function rules()
    {
        return [
            [['Files'], 'file', 'skipOnEmpty' => false, 'extensions' => 'jpg', 'maxFiles' => 2],
        ];
    }
    
    public function uploadHere()
    {
        if ($this->validate()) { 
            foreach ($this->Files as $file) {
                $file->saveAs('path/to/uploads/' . $file->baseName . '.' . $file->extension);
            }
            return true;
        } else {
            return false;
        }
    }
}

Action FileUpload:

public function actionFileUpload()
    {
        $model = new FileUploadForm();

        if (Yii::$app->request->isPost) {
            $model->Files = UploadedFile::getInstances($model, 'Files');
            if ($model->uploadHere()) {
                // your code here
                return;
            }
        }

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

File input form:

use yii\widgets\ActiveForm;

$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']])

$form->field($model, 'Files[]')->fileInput(['multiple' => true, 'accept' => 'image/*'])

ActiveForm::end()

yii2 encrypt decrypt

Yii2 encrypt decrypt data

Yii2 have inbuilt functions for encrypt/decrypt data using secret key. You need secret key to decrypt the data. So if the person have secret key he/she will be decrypt the data easily using the getSecurity() method. Below example is showing the data encrypt/decrypt:

$data = 'FORM DATA';
$secretKey = 'YOUR SECRET KEY'
$encryptData = Yii::$app->getSecurity()->encryptByPassword($data, $secretKey);

$data = Yii::$app->getSecurity()->decryptByPassword($encryptData, $secretKey);

yii2 decrypt password

Password Decryption in Yii2

Yii2 have inbuilt functions for encrypt/decrypt data using secret key. Yii2 getSecurity() method return the pseudo random data which is useful for encrypt/decrypt your hash data. The given example describe the validate password and set password methods:

public $key = 'SECRET KEY';
public function setPassword($pwd)
{
    $this->password_hash = Yii::$app->getSecurity()->encryptByPassword($pwd, $this->key);
}
public function validatePassword($pwd)
{
    $decryptPassword = Yii::$app->getSecurity()->decryptByPassword($this->password_hash, $this->key);
    return $decryptPassword === $pwd;
}

Tuesday, April 24, 2018

Yii2 Select2 onchange

kartik Select2 onChange and Ajax Call

In this example you can see a function userAlert() and this will call after typing in select2 text input

In below example you can also see ajax calling. In the parameter set your URL.

You can also set your own label in this example.

echo $form->field($model, 'user')->widget(Select2::classname(), [
                                'options' => ['id' => 'user_id', 'class'=>'kartik2', 'title'=>'User', 'onchange' =>"userAlert();"],
                                'pluginOptions' => [
                                        'ajax' => [
                                        'url' => 'Your Url',
                                        'dataType' => 'json',
                                    ],
                                    'allowClear' => false,
                                    'minimumInputLength' => 3,
                                    'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
                                    'templateResult' => new JsExpression('function(user) { return user.text; }'),
                                    'templateSelection' => new JsExpression('function (user) { return user.text; }'),
                                ],
                            ])->label('Label you can set here');


Yii2 send attachment

Yii2 send attachment using swiftmailer

You can send attachment using swiftmailer using below method

Before send an attachment you need to set swiftmailer configuration:
Swiftmailer configuration

$mail = Yii::$app->mailer->compose();

// file path
$mail->attach('path/to/image.jpg');

$mail->send();

Yii2 swiftmailer

Yii2 send email using swiftmailer

Default config in Yii2

'components' => [
                'mailer' => [
                    'class' => 'yii\swiftmailer\Mailer', 
                    'transport' => [
                        'class' => 'Swift_SmtpTransport',
                        'host' => 'localhost',
                        'username' => 'username',
                        'password' => 'password',
                        'port' => '587',
                        'encryption' => 'tls',
                    ],
                ],
            ]

Send email usage:
After mailer component settings, you can use below example to send an email

$mail = Yii::$app->mailer->compose()
    ->setFrom('from@xyz.com')
    ->setTo('to@xyz.com')
    ->setSubject('Subject')
    ->setTextBody('Text')
    ->setHtmlBody('Html data');

     $mail->send();

Yii2 cryptography

Yii2 cryptography

Generating Pseudo random

Pseudo random is helpful in security. You can use Pseudo random data as a token while sending the email for reset password or while sending the confidential data on the server.

$securityKey = Yii::$app->getSecurity()->generateRandomString();

You can also pass the integer value in generateRandomString() function.
For Example:

$securityKey = Yii::$app->getSecurity()->generateRandomString(10);

Thursday, April 12, 2018

Yii Activeform

Active Form Widget

Yii Activeform is a powerful widget which provides form inputs as well as validation. We can handle validation through the model. In this section we need to create a User Model and you can set the validation in the model.

Yii Active is based on Active Record. It uses yii\helpers\Html and yii\widgets\ActiveForm Classes.

Active form should be begin and must be end.

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

$form = ActiveForm::begin([
    'id' => 'user-form',
    'options' => ['class' => 'form-control'],
])
$form->field($model, 'name')->input([//options]) 
$form->field($model, 'email')->input([//options]) 
Html::submitButton('Save', ['class' => 'btn btn-success'])
ActiveForm::end();

Yii Actions

Create action in Yii2

Yii actions define public under the controller class. It starts with action keyword and it can be camel case like actionTestScript.

Yii Url format like: controller/action.

In below example controller name is sample and action name is TestScript, So if you want to access this controller/action, You need to write like sample/test-script.

Another example is sample/home.

use yii\web\Controller;
namespace app\controllers;

class SampleController extends Controller
{
    public function actionTestScript($params)
    {
        return $this->render('test');
    }

    public function actionHome()
    {
        return 'This is my controller';
    }
}

Yii Controllers

Create Controller and action in Yii2

Yii controller is a part of MVC. Yii controller define under the contollers directory.

Yii Controller extends the base class yii\web\Controller.

namespace app\controllers;

use Yii;
use app\models\User;
use yii\web\Controller;
use yii\web\NotFoundHttpException;

class UserController extends Controller
{
    public function actionUpdate($id)
    {
        $model = User::findOne($id);
        if ($model === null) {
            throw new NotFoundHttpException;
        }

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

    public function actionCreate()
    {
        $model = new User;

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

How to remove index.php in Yii Framework

Yii Url Routing

In this example user can remove index.php from the URL. You need to set showScriptName false and enablePrettyUrl should be true.

In below example /user/profile will be replaced with /profile.

You need to change file config/main.php

'urlManager' => [
   'showScriptName' => false,
   'enablePrettyUrl' => true,
   'rules' => [
      'profile' => 'user/profile',
   ]
],

Yii Group By

Group By in Yii2

In Yii framework we can use GroupBy Just like we do in raw sql statements.You can define column name in group by and you can set multiple columns in array.For example below:

$model = (new \yii\db\Query())
      ->select(['col_1','col_2','col_3'])
      ->from('tableName')
      ->groupBy('col_name')
      ->having('id < 8')
      ->all();
   print_r($model);

Tuesday, April 10, 2018

Yii2 Listview

ListView in Yii2

A list view is used to display the data from the dataprovider. Dataprovider can be ActiveDataProvider or ArrayDataProvider or SqlDataProvider.

In below example we are using ActiveDataProvider and _item_view for displaying by itemView property of ListView widget

use yii\widgets\ListView;
use yii\data\ActiveDataProvider;

$provider = new ActiveDataProvider([
    'query' => User::find(),
    'pagination' => [
        'pageSize' => 30,
    ],
    'defaultOrder' => [
    'id' => SORT_ASC
   ]
]);

echo ListView::widget([
    'dataProvider' => $provider,
    'itemView' => '_item_view',
]);

Yii2 Detail View

DetailView is used to display the data by model. You can also use array instead of model.

You can also set $attribues property which columns you want to display using the detailView.

Detail View in Yii2

echo DetailView::widget([
    'model' => $userModel,
    'attributes' => [
        [
            'attribute' => 'user',
            'value' => function ($data) {
                return $data->user->name;
            }
        ],
    ],
]);

Yii2 Sorting

In Yii2 we can use Sort class for sort the data and also define multiple columns for sorting.

Yii provides multiple types of sorting like asc, desc and user can also set default sort for all attributes.

Sorting in Yii2

use yii\data\Sort;

$sorting = new Sort([
    'attributes' => [
        'name' => [
            'asc' => ['name' => SORT_ASC, 'id' => SORT_ASC],
            'desc' => ['username' => SORT_DESC],
            'default' => SORT_DESC,
        ],
    ],
]);

$user= User::find()
    ->where(['is_visible' => 1])
    ->orderBy($sorting->orders)
    ->all();

Yii2 limit

Create a new instance of yii db Query.

Offset() define which is starting point and limit() define the number of rows.

Limit Query in Yii2

$query = (new Query())->select(['id'])->from('user');
$query->limit(10)->offset(10);

Sunday, April 8, 2018

Yii2 sqldataprovider

SqlDataProvider is a plain sql query. It is also provide pagination and sorting methods.

SqlDataProvider representing data in arrays form. You can use LIMIT, GROUP BY , ORDER BY in the statements.

How to use Sql dataprovider in Yii2

$provider = new SqlDataProvider([
    'sql' => 'SELECT * FROM customer WHERE id=:id',
    'params' => [':id' => 1],
    'sort' => [
        'attributes' => [
            'name' => [
                'asc' => ['name' => SORT_ASC, 'username' => SORT_ASC],
                'default' => SORT_DESC
            ],
        ],
    ],
    'pagination' => [
        'pageSize' => 10,
    ],
]);

// get the customer results
$data = $provider->getModels();

Yii2 arraydataprovider

ArrayDataProvider just name represent based on data array. It is uses $allModels property which occupied all the data and it can be sorted.

You can set $sort and $pagination methods for sorting and pagination behaviors.

How to use Arraydataprovider in Yii2

$query = new Query;
$arrayDataProvider = new ArrayDataProvider([
    'allModels' => $query->from('user')->where(['status'=>true])->all(),
    'sort' => [
        'attributes' => ['name', 'id'],
    ],
    'pagination' => [
        'pageSize' => 5,
    ],
]);
// get the user query result
$user = $arrayDataProvider->getModels();

Yii2 activedataprovider

ActiveDataProvider data based on yii\db\Query or yii\db\ActiveQuery.

It provides data by using DB queries using $query.

You can use ORDER BY, GROUP BY, LIMIT, OFFSET just like normal sql statements in ActiveDataProvider.

How to use active dataprovider in Yii2


use yii\data\ActiveDataProvider;

$userQuery = User::find()->where(['id' => 9]);

$provider = new ActiveDataProvider([
    'query' => $userQuery,
    'pagination' => [
        'pageSize' => 5,
    ],
    'sort' => [
        'defaultOrder' => [
            'updated_by' => SORT_DESC
        ]
    ],
]);

Saturday, April 7, 2018

Yii2 phantomjs

First of all you need to install Yii2 phantomjs extension using below Command
$ composer require "jonnyw/php-phantomjs:4.*"

Phantomjs Usage:

use JonnyW\PhantomJs\Client;
    $c = Client::getInstance();
    $request = $c->getMessageFactory()->createRequest('http://example.com', 'GET');
    $res = $c->getMessageFactory()->createResponse();
    // Make the request
    $c->send($request, $res);
    if($res->getStatus() === 200) {
        echo $res->getContent();

Friday, March 30, 2018

How to hide frontend/web and backend/web in Yii2

Yii2 provide default url with frontend/web and backend/web. In real web application these type of URL is not well, So in this case we need to remove frontend/web from the URL. Below example is best to remove the frontend/web from the URL.

First of all you need to set enablePrettyUrl true and showScriptName false.

In second step you just replace frontend/web with blank space.

In third step you need to create a .htaccess file inside the web folder.

frontend/config/main.php

use \yii\web\Request;
$baseUrl = str_replace('/frontend/web', '', (new Request)->getBaseUrl()); // you set override the frontend/web with blank space and it will return the baseUrl.

'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'enableStrictParsing' => false,
        'rules' => [
        ],
   ]

'request' => [
 'baseUrl' => $baseUrl,
 ]

frontend/web/.htaccess

Options -Indexes
RewriteEngine on
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_URI} !^/backend/web/(assets|css)/
RewriteCond %{REQUEST_URI} admin
RewriteRule .* backend/web/index.php [L]
RewriteCond %{REQUEST_URI} !^/(frontend|backend)/web/(assets|css)/
RewriteCond %{REQUEST_URI} !admin
RewriteRule .* frontend/web/index.php [L]
</IfModule>

Wednesday, March 28, 2018

Yii2 Join Query

Yii2 provides many types of join:

  • Join()
  • leftJoin()
  • rightJoin()
  • joinWith()
  • innerJoinWith()
In below example we are using Join() method.

Yii2 Join Query


$query = (new Query())->from('user');
$query->select('user.id , user_profile.first_name , user_profile.last_name');
$result = $query->join('left join', 'user_profile', 'user_profile.user_id = user.id')->all();

Yii2 batch update

In batch query method we can retrieve data in batches. We can use batch using yii\db\Query::batch().

Yii2 batch update


$rows = $query->select(['name','email'])
                    ->from('tblName1')
                    ->all();
$columnNames = ['name','email'];
$result = \Yii::$app->db->createCommand()->batchInsert('tblName2', $columnNames, $rows)->execute();

Yii2 update column with query builder

Yii2 also provide update method for update the table records.

In below example we are just updating the single record with where condition.

How to update record in Yii2

Yii::$app->db->createCommand()
             ->update('tblName', ['name' => 'Ram'], ['id'=> 4])
             ->execute();

Monday, March 26, 2018

How to create custom widget in Yii2

Create custom widget in Yii2


In this example We am creating a dropdown widget. This is only provide a basic structure of how to create your own custom widget.


Following files you need to create for widget.

1. _template.php
        print_r($model);
        die;

2.GridviewDropdown.php
namespace common\widgets\dropdownWidget;
use yii\base\Widget;
public function init(){
    parent::init(); } public function run(){     return $this->render('_template', ['items' => $this->data]);
   }
}
3.viewFile.php
echo \common\widgets\dropdownWidget\GridviewDropdown::widget([
            'model' => $model
    ])


Where query in Yii2

In this example we are just fetching two columns data and also set limit 5. You can set your own limits and also set your own columns.

How to build where query in Yii2

$data = (new \yii\db\Query())
    ->select(['columnName1', 'columnName2'])
    ->from('table_name')
    ->where(['columnName' => 'value'])
    ->limit(5) //set limit
    ->all();

Recent Update

yii2 session handling

use yii\web\Session; $session = Yii::$app->session; // start session $session->open(); // close session $session->close(); ...

Most Search