Friday, November 18, 2016

yii2 custom validator multiple attributes


public function rules()
    {
 [['is_property_owner', 'is_property_renant'], 'validateproperty'],

 }

    public  function validateproperty($attribute, $params){

        if(empty($this->is_property_owner) && empty($this->is_property_renant)){
            $this->addError('is_property_renant', 'Please select at least one option.');
        }


    }

yii2 custom validator multiple attributes


public function rules()
    {
 [['is_property_owner', 'is_property_renant'], 'validateproperty'],

 }

    public  function validateproperty($attribute, $params){

        if(empty($this->is_property_owner) && empty($this->is_property_renant)){
            $this->addError('is_property_renant', 'Please select at least one option.');
        }


    }

Wednesday, September 14, 2016

Yii2 Transaction


Transaction: A transaction is used to run a group of operations in single process. When you we run multiple query in single process, It will be used. If you get any problem, It will not complete successfully and also rollback the executed query.
 $transaction = Yii::$app->db->beginTransaction();
            try  {
               if($model->save()){
                $itemprice->item_id=$model->id;
                $itemprice->price=$model->price;
                $itemprice->item_cost=$model->item_cost;
                $itemprice->wholesale=$model->wholesale;
                $itemprice->taxed=$model->tax;
                $itemprice->type=$model->taxed;
                $itemprice->save(false);
                if($model->discount==1){
                    $discount->amount=$discountamount;
                    $discount->date_from=$discountdate_from;
                    $discount->date_to=$discountdate_to;
                    $discount->item_id=$model->id;
                    $discount->type=$discounttype;
                    $discount->status=1;
                    $discount->date_from=strtotime($discount->date_from);
                    $discount->date_to=strtotime($discount->date_to);
                    $discount->save(false);
                }
                $transaction->commit();
                return $this->redirect(['view', 'id' => $model->id]);
            }
} catch (Exception $e) {
                $transaction->rollBack();
            }
OR
$transaction = $connection->beginTransaction();
try {
$user = $connection->createCommand()->insert('user', [
'name' => 'jibon',
'email' => 'jibon.bikash@gmail.com',
])->execute();
$connection->createCommand()->insert('user_role', ['role = "admin",
'user_id'=$user->id
])->execute();

$transaction->commit();

} catch(Exception $e) {
    $transaction->rollback();
}

Yii2 Transaction


Transaction: A transaction is used to run a group of operations in single process. When you we run multiple query in single process, It will be used. If you get any problem, It will not complete successfully and also rollback the executed query.
 $transaction = Yii::$app->db->beginTransaction();
            try  {
               if($model->save()){
                $itemprice->item_id=$model->id;
                $itemprice->price=$model->price;
                $itemprice->item_cost=$model->item_cost;
                $itemprice->wholesale=$model->wholesale;
                $itemprice->taxed=$model->tax;
                $itemprice->type=$model->taxed;
                $itemprice->save(false);
                if($model->discount==1){
                    $discount->amount=$discountamount;
                    $discount->date_from=$discountdate_from;
                    $discount->date_to=$discountdate_to;
                    $discount->item_id=$model->id;
                    $discount->type=$discounttype;
                    $discount->status=1;
                    $discount->date_from=strtotime($discount->date_from);
                    $discount->date_to=strtotime($discount->date_to);
                    $discount->save(false);
                }
                $transaction->commit();
                return $this->redirect(['view', 'id' => $model->id]);
            }
} catch (Exception $e) {
                $transaction->rollBack();
            }
OR
$transaction = $connection->beginTransaction();
try {
$user = $connection->createCommand()->insert('user', [
'name' => 'jibon',
'email' => 'jibon.bikash@gmail.com',
])->execute();
$connection->createCommand()->insert('user_role', ['role = "admin",
'user_id'=$user->id
])->execute();

$transaction->commit();

} catch(Exception $e) {
    $transaction->rollback();
}

Yii2 Transaction


Transaction: A transaction is used to run a group of operations in single process. When you we run multiple query in single process, It will be used. If you get any problem, It will not complete successfully and also rollback the executed query.
 $transaction = Yii::$app->db->beginTransaction();
            try  {
               if($model->save()){
                $itemprice->item_id=$model->id;
                $itemprice->price=$model->price;
                $itemprice->item_cost=$model->item_cost;
                $itemprice->wholesale=$model->wholesale;
                $itemprice->taxed=$model->tax;
                $itemprice->type=$model->taxed;
                $itemprice->save(false);
                if($model->discount==1){
                    $discount->amount=$discountamount;
                    $discount->date_from=$discountdate_from;
                    $discount->date_to=$discountdate_to;
                    $discount->item_id=$model->id;
                    $discount->type=$discounttype;
                    $discount->status=1;
                    $discount->date_from=strtotime($discount->date_from);
                    $discount->date_to=strtotime($discount->date_to);
                    $discount->save(false);
                }
                $transaction->commit();
                return $this->redirect(['view', 'id' => $model->id]);
            }
} catch (Exception $e) {
                $transaction->rollBack();
            }

Saturday, June 11, 2016

Yii2 Show image at a GridView

[
                'attribute' => 'itm_image',
                'format' => 'image',
                'value' => function($data) {
                    if($data->itm_image){
                        return \Yii::getAlias('@web/uploads/products/').$data->itm_image;
                    }
                    else{
                        return \Yii::getAlias('@web/uploads/products/no.png');
                    }
                },
                'contentOptions' => ['class' => 'item_image_grid img-responsive img-rounded']
            ],
            [
                'attribute' => 'itm_image',
                'format' => 'html',
                'value' => function ($data) {
                    if($data->itm_image) {
                        return Html::img('@web/uploads/products/' . $data->itm_image,
                            ['width' => '60px', 'class' => 'img-responsive img-rounded']);
                    }
                    else{
                        return Html::img('@web/uploads/products/no.png',
                            ['width' => '60px', 'class' => 'img-responsive img-rounded']);
                    }
                },
            ],

Sunday, June 5, 2016

yii2 file upload


if ($model->load(Yii::$app->request->post())){
            $image = UploadedFile::getInstance($model, 'image_file');
            $fileext=time();
            $image->saveAs('uploads/' . $fileext.$image->baseName . '.' . $image->extension);
            $model->image_file = $fileext.$image->baseName.'.'.$image->extension;
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        }
        else{
            return $this->render('create', [
                'model' => $model,
            ]);
        }

Saturday, February 20, 2016

Yii2 change the value in GridView


            [
                'attribute' => 'active',
                'value' => function ($model) {
                    return $model->active == 1 ? 'Yes' : 'No';
                },
      //        'value' => function ($data){
       //             return $data->credit==1 ? "On": ($data->credit==2 ? "Pending": "Off");
        //        }

                'filter'=>array("1"=>"Yes","0"=>"No"),
          //      'filter' => Html::activeDropDownList($searchModel, 'attribute_name', ArrayHelper::map(ModelName::find()->asArray()->all(), 'ID', 'Name'),['class'=>'form-control','prompt' => '']),
            ],

Yii2 static dropDownList


$form->field($model, 'active')->dropDownList(['1' => 'Yes', '0' => 'No'],['prompt'=>'']);

yii2 beforeSave() method


    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($this->isNewRecord) {
                $this->author = \Yii::$app->user->identity->id;
                $this->create_date = time();
            }
            else {
                $this->author=\Yii::$app->user->identity->id;
                $this->update_date=time();

            }

        }

        return true;
    }

Monday, February 8, 2016

Yii2 install

Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\Users\HP-14>composer config --global github-oauth.github.com 5c0cab55bca3f6cd
63c4efef------------

C:\Users\HP-14>composer
   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 1.0-dev (72cd6afdfce16f36a9fd786bc1b2f32b851e764f) 2015-12-28 1
7:35:19

Usage:
  command [options] [arguments]

Options:
  -h, --help                     Display this help message
  -q, --quiet                    Do not output any message
  -V, --version                  Display this application version
      --ansi                     Force ANSI output
      --no-ansi                  Disable ANSI output
  -n, --no-interaction           Do not ask any interactive question
      --profile                  Display timing and memory usage information
  -d, --working-dir=WORKING-DIR  If specified, use the given directory as workin
g directory.
  -v|vv|vvv, --verbose           Increase the verbosity of messages: 1 for norma
l output, 2 for more verbose output and 3 for debug

Available commands:
  about           Short information about Composer
  archive         Create an archive of this composer package
  browse          Opens the package's repository URL or homepage in your browser
.
  clear-cache     Clears composer's internal package cache.
  clearcache      Clears composer's internal package cache.
  config          Set config options
  create-project  Create new project from a package into given directory.
  depends         Shows which packages depend on the given package
  diagnose        Diagnoses the system to identify common errors.
  dump-autoload   Dumps the autoloader
  dumpautoload    Dumps the autoloader
  global          Allows running commands in the global composer dir ($COMPOSER_
HOME).
  help            Displays help for a command
  home            Opens the package's repository URL or homepage in your browser
.
  info            Show information about packages
  init            Creates a basic composer.json file in current directory.
  install         Installs the project dependencies from the composer.lock file
if present, or falls back on the composer.json.
  licenses        Show information about licenses of dependencies
  list            Lists commands
  remove          Removes a package from the require or require-dev
  require         Adds required packages to your composer.json and installs them

  run-script      Run the scripts defined in composer.json.
  search          Search for packages
  self-update     Updates composer.phar to the latest version.
  selfupdate      Updates composer.phar to the latest version.
  show            Show information about packages
  status          Show a list of locally modified packages
  suggests        Show package suggestions
  update          Updates your dependencies to the latest version according to c
omposer.json, and updates the composer.lock file.
  validate        Validates a composer.json and composer.lock

C:\Users\HP-14>cd f:\xampp\htdocs

C:\Users\HP-14>F:

f:\xampp\htdocs>composer create-project --prefer-dist yiisoft/yii2-app-basic
Installing yiisoft/yii2-app-basic (2.0.6)



  [InvalidArgumentException]
  Project directory F:/xampp/htdocs/yii2-app-basic/ is not empty.



create-project [-s|--stability STABILITY] [--prefer-source] [--prefer-dist] [--r
epository-url REPOSITORY-URL] [--dev] [--no-dev] [--no-plugins] [--no-custom-ins
tallers] [--no-scripts] [--no-progress] [--keep-vcs] [--no-install] [--ignore-pl
atform-reqs] [--] [] [] []



f:\xampp\htdocs>composer create-project --prefer-dist yiisoft/yii2-app-basic
Installing yiisoft/yii2-app-basic (2.0.6)
  - Installing yiisoft/yii2-app-basic (2.0.6)
    Loading from cache

Created project in F:\xampp\htdocs\yii2-app-basic
Loading composer repositories with package information
Installing dependencies (including require-dev)
  - Installing yiisoft/yii2-composer (2.0.4)
    Downloading: 100%

  - Installing ezyang/htmlpurifier (v4.6.0)
    Downloading: 100%

  - Installing bower-asset/jquery (2.1.4)
    Downloading: 100%

  - Installing bower-asset/yii2-pjax (v2.0.5)
    Downloading: 100%

  - Installing bower-asset/punycode (v1.3.2)
    Downloading: 100%

  - Installing bower-asset/jquery.inputmask (3.1.63)
    Downloading: 100%

  - Installing cebe/markdown (1.1.0)
    Downloading: 100%

  - Installing yiisoft/yii2 (2.0.6)
    Downloading: 100%

  - Installing swiftmailer/swiftmailer (v5.4.1)
    Downloading: 100%

  - Installing yiisoft/yii2-swiftmailer (2.0.4)
    Downloading: 100%

  - Installing yiisoft/yii2-codeception (2.0.4)
    Downloading: 100%

  - Installing bower-asset/bootstrap (v3.3.5)
    Downloading: 100%

  - Installing yiisoft/yii2-bootstrap (2.0.5)
    Downloading: 100%

  - Installing yiisoft/yii2-debug (2.0.5)
    Downloading: 100%

  - Installing bower-asset/typeahead.js (v0.10.5)
    Downloading: 100%

  - Installing phpspec/php-diff (v1.0.2)
    Downloading: 100%

  - Installing yiisoft/yii2-gii (2.0.4)
    Downloading: 100%

  - Installing fzaninotto/faker (v1.5.0)
    Downloading: 100%

  - Installing yiisoft/yii2-faker (2.0.3)
    Downloading: 100%

fzaninotto/faker suggests installing ext-intl (*)
Writing lock file
Generating autoload files
> yii\composer\Installer::postCreateProject
chmod('runtime', 0777)...done.
chmod('web/assets', 0777)...done.
chmod('yii', 0755)...done.

f:\xampp\htdocs>composer create-project --prefer-dist yiisoft/yii2-app-advanced
Installing yiisoft/yii2-app-advanced (2.0.6)
  - Installing yiisoft/yii2-app-advanced (2.0.6)
    Downloading: 100%

Created project in F:\xampp\htdocs\yii2-app-advanced
Loading composer repositories with package information
Installing dependencies (including require-dev)
  - Installing yiisoft/yii2-composer (2.0.4)
    Loading from cache

  - Installing ezyang/htmlpurifier (v4.6.0)
    Loading from cache

  - Installing cebe/markdown (1.1.0)
    Loading from cache

  - Installing bower-asset/jquery (2.1.4)
    Loading from cache

  - Installing bower-asset/jquery.inputmask (3.1.63)
    Loading from cache

  - Installing bower-asset/punycode (v1.3.2)
    Loading from cache

  - Installing bower-asset/yii2-pjax (v2.0.5)
    Loading from cache

  - Installing yiisoft/yii2 (2.0.6)
    Loading from cache

  - Installing swiftmailer/swiftmailer (v5.4.1)
    Loading from cache

  - Installing yiisoft/yii2-swiftmailer (2.0.4)
    Loading from cache

  - Installing yiisoft/yii2-codeception (2.0.4)
    Loading from cache

  - Installing bower-asset/bootstrap (v3.3.5)
    Loading from cache

  - Installing yiisoft/yii2-bootstrap (2.0.5)
    Loading from cache

  - Installing yiisoft/yii2-debug (2.0.5)
    Loading from cache

  - Installing bower-asset/typeahead.js (v0.10.5)
    Loading from cache

  - Installing phpspec/php-diff (v1.0.2)
    Loading from cache

  - Installing yiisoft/yii2-gii (2.0.4)
    Loading from cache

  - Installing fzaninotto/faker (v1.5.0)
    Loading from cache

  - Installing yiisoft/yii2-faker (2.0.3)
    Loading from cache

fzaninotto/faker suggests installing ext-intl (*)
Writing lock file
Generating autoload files

f:\xampp\htdocs>cd yii2-app-advanced

f:\xampp\htdocs\yii2-app-advanced>php init
Yii Application Initialization Tool v1.0

Which environment do you want the application to be initialized in?

  [0] Development
  [1] Production

  Your choice [0-1, or "q" to quit] 0

  Initialize the application under 'Development' environment? [yes|no] yes

  Start initialization ...

   generate backend/config/main-local.php
   generate backend/config/params-local.php
   generate backend/web/index-test.php
   generate backend/web/index.php
   generate common/config/main-local.php
   generate common/config/params-local.php
   generate console/config/main-local.php
   generate console/config/params-local.php
   generate frontend/config/main-local.php
   generate frontend/config/params-local.php
   generate frontend/web/index-test.php
   generate frontend/web/index.php
   generate yii
   generate cookie validation key in backend/config/main-local.php
   generate cookie validation key in frontend/config/main-local.php
      chmod 0777 backend/runtime
      chmod 0777 backend/web/assets
      chmod 0777 frontend/runtime
      chmod 0777 frontend/web/assets
      chmod 0755 yii
      chmod 0755 tests/codeception/bin/yii

  ... initialization completed.

E:\xampp\htdocs\yii2-app-advanced>yii migrate
Yii Migration Tool (based on Yii v2.0.7)

Creating migration history table "migration"...Done.
Total 1 new migration to be applied:
        m130524_201442_init

Apply the above migration? (yes|no) [no]:yes
*** applying m130524_201442_init
    > create table {{%user}} ... done (time: 0.641s)
*** applied m130524_201442_init (time: 0.788s)


1 migration was applied.

Migrated up successfully.

E:\xampp\htdocs\yii2-app-advanced>

Wednesday, January 27, 2016

Select2 get update value

input type hidden value and get value in ID

jQuery(function($) {
 //var selectedValues = val(subject;?>).split(',');
 var selectedsub = $("#subjectval").val().split(',');
 var selectedrelevant_law = $("#relevant_lawval").val().split(',');
 var selectedsectionval = $("#relevant_sectionval").val().split(',');
 var selectedcourtval = $("#courtval").val().split(',');
 var selectedjudgeval = $("#judgeval").val().split(',');
 var selectedadvocateval = $("#advocateval").val().split(',');
 $("#subject").select2().select2('val',selectedsub);
 $("#relevant_law").select2().select2('val',selectedrelevant_law);
 $("#relevant_section").select2().select2('val',selectedsectionval);
 $("#court").select2().select2('val',selectedcourtval);
 $("#judge").select2().select2('val',selectedjudgeval);
 $("#advocate").select2().select2('val',selectedadvocateval);

});


Tuesday, January 19, 2016

Yii countByAttributes or findAllByAttributes

    return $count = InstituteClassSummary::model()->countByAttributes(
    array(
      'zillaid' => $zilaid,
    ),
    array(
    //  'order' => 'date desc',
      'group' => 'institude_id',
    //  'offset' => 15
    ));

$allLogins = InstituteClassSummary::model()->findAllByAttributes(
array(
    'zillaid' => Yii::app()->user->id,
    'type' => $zilaid
),
array(
    'order' => 'date desc',
    'limit' => 10,
    'offset' => 15
));