Menus

Wednesday 6 September 2017

Yii2 Masked Input


Class yii\widgets\MaskedInput



MaskedInput generates a masked text input.
MaskedInput is similar to yii\helpers\Html::textInput() except that an input mask will be used to force users to enter properly formatted data, such as phone numbers, social security numbers.

Yii2 MaskedInput to collect phone numbers:

echo MaskedInput::widget([
    'name' => 'phone',
    'mask' => '999-999-9999',
]);
You can also use this widget in an yii\widgets\ActiveForm using the widget() method, for example like this:
<?= $form->field($model, 'from_date')->widget(\yii\widgets\MaskedInput::className(), [
    'mask' => '999-999-9999',
]) ?>

Demonstration and usage examples for the Yii 2.0 Masked Input widget


Masked input to collect date from users


More Masked Inputs

Code paste to your view
use yii\widgets\MaskedInput;


  1. echo MaskedInput::widget([
  2. 'name' => 'input-31',
  3. 'clientOptions' => ['alias' => 'date']
  4. ]);




Example

Masked date input use in active form.


<?= $form->field($model, 'date_of_birth')->widget(\yii\widgets\MaskedInput::className(), [
        'name' => 'input-31',
        'clientOptions' => ['alias' =>  'dd-mm-yyyy'],
        
]) ?>



Retype your date format in  'clientOptions' => ['alias' =>  'dd-mm-yyyy']


Masked  Amount input 

  1. echo MaskedInput::widget([
  2. 'name' => 'input-33',
  3. 'clientOptions' => [
  4. 'alias' => 'decimal',
  5. 'groupSeparator' => ',',
  6. 'autoGroup' => true
  7. ],
  8. ]);


Masked  URL input 

  1. echo MaskedInput::widget([
  2. 'name' => 'input-35',
  3. 'clientOptions' => [
  4. 'alias' => 'url',
  5. ],
  6. ]);


Masked  Email input 

  1. echo MaskedInput::widget([
  2. 'name' => 'input-36',
  3. 'clientOptions' => [
  4. 'alias' => 'email'
  5. ],
  6. ]);

Masked  Other Phone | US Phone input 


  1. echo MaskedInput::widget([
  2. 'name' => 'input-5',
  3. 'mask' => ['99-999-9999', '999-999-9999']
  4. ]);

More



Yii2 Bootstrap DatePicker Widget for Yii2

/yii2-date-picker-widget



Related Links

Yii Tabular Input



Monday 14 August 2017

PHP more useful functions




PHP strlen() Function

The strlen() function returns the length of a string.

Syntax

strlen(string)

Example

<?php
echo strlen("Hello world!");
?>

PHP substr() Function


Return part of a string


The substr() function returns a part of a string.

Syntax

substr(string,start,length)



ParameterDescription
stringRequired. Specifies the string to return a part of
startRequired. Specifies where to start in the string
  • A positive number - Start at a specified position in the string
  • A negative number - Start at a specified position from the end of the string
  • 0 - Start at the first character in string
lengthOptional. Specifies the length of the returned string. Default is to the end of the string.
  • A positive number - The length to be returned from the start parameter
  • Negative number - The length to be returned from the end of the string

Get first n characters of a string

Examples

echo substr("Hello world",0,4);
Output is print  "Hello"


$category_name=substr($cat['description'],3,  strlen($cat['description'])-1);


PHP fmod() Function


The fmod() function returns the remainder (modulo) of x/y.

Syntax

fmod(x,y);

             if(fmod($i, 2)==0){                  

                  //  Reminder is zero.
             
            }
            else{

                //  Reminder is one.

            }



Converting separate month, day and year values into a timestamp



using setDate funtion

<?php
$date = new DateTime();
$date->setDate(2001, 2, 3);
echo $date->format('Y-m-d');
?>




Tuesday 8 August 2017

YII2 Useful Tips


Filter to force lowercase on all operations


Yii change case each word in a string and save model.


Yii2 change model case

['student_name', 'filter', 'filter'=>'strtolower'],

['student_name', 'filter', 'filter'=>'strtoupper'],

To convert to Lowercase or Uppercase 





Thursday 3 August 2017

Yii2 Transaction


Yii2 save related records in single save call in single transaction


Database Transaction in Yii


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 represents a DB transaction.
It is usually created by calling yii\db\Connection::beginTransaction().
The following code is a typical example of using transactions (note that some DBMS may not support transactions):
$transaction = $connection->beginTransaction();
try {
    $connection->createCommand($sql1)->execute();
    $connection->createCommand($sql2)->execute();
    //.... other SQL executions
    $transaction->commit();
} catch (\Exception $e) {
    $transaction->rollBack();
    throw $e;
} catch (\Throwable $e) {
    $transaction->rollBack();
    throw $e;
}

Example

$transaction = Yii::$app->db->beginTransaction(); 

 try { 

 $user = new User(); 
 $user->name = 'Name'; 
 $user->save(); 

 $ua = new UserAddress(); 
 $ua->city = 'City'; 
 $user->link('userAddress', $ua); // <-- it creates new record in UserAddress table with ua.user_id = user.id 

 $transaction->commit(); 

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


Example


if ($model->load(Yii::$app->request->post()))
        {
         
           $transaction = \Yii::$app->db->beginTransaction();
           try {  
         
         
            $stockitem=Stockitem::find()->where(['id'=>$model->stockitem_id])->one();
            $stockitem->stock=$stockitem->stock-$model->stock;
         
            $stockitem->save();
         
            //Stock add to center
            $st=  Stockcenter::find()->where(['stockitem_id'=>$model->stockitem_id,'center_ccid'=>$model->center_ccid])->one();
            if($st)
            {
              $st->stock=$st->stock+$model->stock;
              $st->amount=$model->amount;
              $st->save();
            }
            else
            {
                $st= new Stockcenter();
                $st->stockitem_id=$model->stockitem_id;
                $st->center_ccid=$model->center_ccid;
                $st->stock=$model->stock;
                $st->amount=$model->amount;
                $st->save();              
            }
         
         
            $model->date=date('Y-m-d',strtotime($model->date));
            $model->save();
         
            $transaction->commit();

            } catch (Exception $e) {
                        $transaction->rollBack();
            }
         
            //Redirect...
         
         
        }


Example

$transaction = Yii::$app->db->beginTransaction(); 
              
                try {
                    
                                     
                    $command=Yii::$app->db->createCommand('UPDATE receipt SET type="STUDENTS" , students_admission_number = '. $std->admission_number . ', students_ccid = '. $std->ccid .' WHERE type = "ENQUIRY" AND students_admission_number = '. $model->enquiry_number . ' and students_ccid = ' . $model->ccid);
                    
                    if($std->save() && $model->save() && $command->execute())                    
                        $transaction->commit();
                    
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    throw $e;
                } catch (\Throwable $e) {
                    $transaction->rollBack();
                    throw $e;
                }


http://www.yiiframework.com/doc-2.0/yii-db-transaction.html


Sunday 25 June 2017

Yii2 Database Operations




Using yii2 date range in active record


search between two dates in yii2



Correct way of date range check
$model = ModelName::find()->where(['between', 'date', "2015-06-21", "2015-06-27" ])
->all();
Using between 

$query= Stockdistributelog::find();    
$query->where(['center_ccid'=>$model->center_ccid]);
$query->andwhere(['between', 'date', date('Y-m-d',strtotime($model->date)),date('Y-m-d',strtotime($model->date_to)) ]);
$query->all();

$programs = Programs::find()->where(['>=', 'close_date', $today])->all();


Check official documentation for more details:




check exist ActiveRecord model in database


How to find record exist in database table ?


Yii2 you can add exists() to your query.
User::find()
    ->where( [ 'id' => 1 ] )
    ->exists(); 


 if(Mastersettings::find()->where(['id'=>1,'status'=>1])->exists())
                    {
                        
                        ....... Your code Here ......

                    } 

exists() return value of true or false.



ActiveRecord model in database


Yii2 Using distinct() in SQL Query


$total = YourMOdel::find()->select('company_name')->distinct()->count();

or

$teachers= Students::find()->select('employee_teachersid')->distinct()->where(['palce_or_subcenter'=>$model->palce_or_subcenter])->all();

or

$query = YourMOdel::find()->select(['company_name', 'client_code'])->distinct();


yii2 active record find column not equal


andWhere(['!=', 'field', 'value'])





Yii2 Database Some Example

Example 1

$teachers= Employee::find()->select(['staff_id','staff_name'])->where(['status'=>'Working','ccid'=>$center_id])
->orderBy('staff_name')
->all();
                                         
                   
                     foreach ($teachers as $value) {
                         echo $value['staff_name'];
                     }










Friday 9 June 2017

Add date picker in dynamic form Yii2


Solutions for date picker does not work properly in dynamic forms


         Date picker widget add in dynamic form of yii2.



Problem using your yii2 extension, especialy the bootstrap datepicker is not show up.
You should add datepicker manually for dynamically genereted instances:

Add code in register javascript

$(".dynamicform_wrapper2").on("afterInsert afterDelete", function(e, item) {
        
        var VarItemsQuantity = $('.item2').length, VarCounter = 1;
        for(VarCounter; VarCounter < VarItemsQuantity; VarCounter++) {                     
            $('#dailyaccountbank-'+VarCounter+'-date').
                parent().datepicker({"autoclose":true,  "format":"d-m-yyyy", 'language':'ru',});                        
        };


View form like this



<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
use yii\helpers\ArrayHelper;
use dosamigos\datepicker\DatePicker;


/* @var $this yii\web\View */
/* @var $model backend\modules\master\models\Students */

$this->title = 'Daily Account From';
//$this->params['breadcrumbs'][] = ['label' => 'Daily', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;

?>

<?php
           
    $script = <<< JS
            
        $(".dynamicform_wrapper").on("afterInsert afterDelete", function(e, item) {
        
        var VarItemsQuantity = $('.item').length, VarCounter = 1;
        for(VarCounter; VarCounter < VarItemsQuantity; VarCounter++) {                     
            $('#dailyaccountbank-'+VarCounter+'-date').
                parent().datepicker({"autoclose":true,  "format":"d-m-yyyy", 'language':'ru',});                        
        };
         
    });
            
            
JS;
$this->registerJs($script);
?>




<div class="students-create">


    <?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>



    <!--Bank details-->
    
    <div class="lb-box-header lb-with-border">
        <h4 class="lb-box-title"><span class="glyphicon glyphicon-list-alt"></span> &nbsp;&nbsp;BANK REMITANCE DETAILS </h4>
    </div>

    <div class="row">        
        <div class="panel-body">
             <?php DynamicFormWidget::begin([
                'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
                'widgetBody' => '.container-items', // required: css class selector
                'widgetItem' => '.item', // required: css class
                'limit' => 4, // the maximum times, an element can be cloned (default 999)
                'min' => 1, // 0 or 1 (default 1)
                'insertButton' => '.add-item', // css class
                'deleteButton' => '.remove-item', // css class
                'model' => $modelsDailyaccountbank[0],
                'formId' => 'dynamic-form',
                'formFields' => [
                    'date',
                    'particulars', 
                    'individual',
                    'mode',
                    'amount',
                ],
            ]); ?>

            <table width = "100%">
                <tr bgcolor="#ddd"><td  width="15%"><b><center>DATE</center></b></td><td><b><center>PARTICULARS</center></b></td><td><b><center>INDIVIDUAL/COMPANY</center></b></td><td width="10%"><b><center>MODE</center></b></td><td width="10%"><b><center>AMOUNT</center></b></td><td width="6%"><b><center>Action</center></b></td></tr>
            </table>
            <div class="container-items"><!-- widgetContainer -->
            <?php foreach ($modelsDailyaccountbank as $i => $modelDailyaccountfee): ?>
                <div class="item"><!-- widgetBody -->
                                               
                      
                        <table width = "100%">
                            <tr>
                                <td width="15%">
                                    <?= $form->field($modelDailyaccountfee, "[{$i}]date") //->textInput(['maxlength' => true])->label(false) 
                                    ->widget(
                    DatePicker::className(), [
                        // inline too, not bad
                         'inline' => FALSE,
                         // modify template for custom rendering
                        //'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
                        'clientOptions' => [
                            'autoclose' => true,            
                            'format' => 'd-m-yyyy',
                            'todayHighlight' => true            
                            //'startDate' => $model->edate,
                        ]
                    ])->label(FALSE);
                                    
                                    
                                    ?>
   
                                    
                                </td>
                                <td>
                                    <?= $form->field($modelDailyaccountfee, "[{$i}]particulars")->textInput(['maxlength' => true])->label(false) ?>
                                </td>
                                <td>
                                    <?= $form->field($modelDailyaccountfee, "[{$i}]individual")->textInput(['maxlength' => true])->label(false) ?>
                                </td>
                                <td width="10%">
                                    <?= $form->field($modelDailyaccountfee, "[{$i}]mode")->textInput(['maxlength' => true])->label(false) ?>
                                </td>
                                <td width="10%">
                                    <?= $form->field($modelDailyaccountfee, "[{$i}]amount")->textInput(['maxlength' => true , 'style'=>'text-align:right'])->label(false) ?>
                                </td>
                                
                                <td width="6%">
                                    <button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
                                    <button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
                                </td>
                            </tr>
                        </table>
                            
                </div> 
            <?php endforeach; ?>
            </div>
            
            
            
            <?php DynamicFormWidget::end(); ?>
        </div>
    
    </div>




<!--    <div class="form-group">
        <= Html::submitButton('Create', ['class' => 'btn btn-success']) ?>
    </div>-->
    
<br>

    
    
    <div class="form-group col-xs-12 col-sm-6 col-lg-4 no-padding">
<div class="col-xs-6">
        <?= Html::submitButton('<i class="fa fa-print"></i> Print', ['class' => 'btn btn-block btn-success','formtarget'=>"_blank"]) ?>            
</div>
<div class="col-xs-6">
<?= Html::resetButton('Reset', ['class' => 'btn btn-default btn-block']) ?>
</div>
     </div>
    
    
    

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


</div>



You should add datepicker manually for dynamically genereted instances:


function multipleDatepickers()
{
    $(".dynamicform_wrapper").on("afterInsert afterDelete", function(e, item) {
        var VarItemsQuantity = $('.item').length,
            VarCounter = 1;
        for(VarCounter; VarCounter < VarItemsQuantity; VarCounter++) {
            $('#WorkExperiencesModel-' + VarCounter + '-StartDate').
                parent().datepicker({"autoclose":true,  "format":"dd-M-yyyy", 'language':'ru',});
            $('#WorkExperiencesModel-' + VarCounter + '-EndDate').
                parent().datepicker({"autoclose":true,  "format":"dd-M-yyyy", 'language':'ru',});
        };
    });
}




Related Links



Dynamic Forms in Yii2 Operations
Yii Tabular Input