Menus

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); ?>  







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

Layout file located at views/layouts/main.php



Asset



Theme Integration






AdminLTE download last version. https://github.com/almasaeed2010/AdminLTE/releases

Installation Steps in GitHub https://github.com/dmstr/yii2-adminlte-asset



Yii2 AdminLTE  header section add menu in Navbar Left side


Edit file header.php in views/layouts

add this code

<?php
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>
        </a>
             
       <!-- 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>        
        </ul>

..
..
..
..
..

</nav>
</header>