Menus

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

Friday, 5 May 2017

Yii2 gridview widget filter

Yii2 dropdown in gridview widget filter

How to add dropdown list in the filter field Grid View ?


Add this in Gridview columns array:
[
    'attribute' => 'attribute_name',
    'value' => 'attribute_value',
    'filter' => Html::activeDropDownList($searchModel, 'attribute_name', ArrayHelper::map(ModelName::find()->asArray()->all(), 'ID', 'Name'),['class'=>'form-control','prompt' => 'Select Category']),
],




View code as

<?php

use yii\helpers\Html;
use yii\grid\GridView;
use backend\modules\employee\models\Employee;
use yii\helpers\ArrayHelper;


$this->title = 'Employee Log Books';
$this->params['breadcrumbs'][] = $this->title;
?>

<div class="employeelogbook-index box box-body table-responsive">
 
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Add Employee Log', ['create'], ['class' => 'btn btn-success']) ?>
    </p>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            [
                'attribute'=>'employee_staff_id',
                'value'=>'employeeStaff.staff_name',
                'filter' => Html::activeDropDownList($searchModel, 'employee_staff_id', ArrayHelper::map(Employee::find()->where(['status'=>'Working'])->orderBy('staff_name')->all(),'staff_id','staff_name'),['class'=>'form-control','prompt' => 'Select Category']),
                'label'=>'Staff Name',
                'options' => ['width' => '200']
                
            ],
            [
       'attribute' => 'date',
       'format' =>  ['date', 'php:d-m-Y'],    
                'options' => ['width' => '150']
                //'filter'=>false,
   ],          
            //'center_ccid',
            'batch',
            'subject',
            'topic',
            'description',
            'rate',
            'ta',
            'hour',

         
            [        
                'class' => 'yii\grid\ActionColumn',
                'contentOptions' => ['style' => 'width:70px;'],
                'header'=>'Act',
                'template' => '{view} {update} {delete}',
                'options' => ['width' => '70']
            ],
        ],
    ]); ?>
</div>


Other solutions
[
    'attribute'=>'attribute name',
    'filter'=>array("ID1"=>"Name1","ID2"=>"Name2"),
],
OR
[
    'attribute'=>'attribute name',
    'filter'=>ArrayHelper::map(Model::find()->asArray()->all(), 'ID', 'Name'),
],


DatePicker in the Filter field GridView

use dosamigos\datepicker\DatePicker;


add this code in your gridview

        [
       'attribute' => 'date',
                'value' => 'date',
       'format' =>  ['date', 'php:d-m-Y'],    
                'options' => ['width' => '150'],
                'filter'=>DatePicker::widget([
                    'model' => $searchModel,
                    'attribute' => 'date',  
                        'clientOptions' => [
                            'autoclose' => true,
                            'format' => 'yyyy-m-d'
                        ]
                ])
   ],





Yii2: filtering gridview from a form outside the header


<?php echo  $this->render('_search', ['model' => $searchModel]) ?>

 <?php 
     echo GridView::widget([
         'dataProvider' => $dataProvider,
         'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
             ......
        ]);

 ?>

http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html#separate-filter-form





How to add a date range picker to filter for dates on a GridView for Yii2



Tuesday, 11 April 2017

Yii2 DetailsView Operations


DetailView is best used for displaying a model in a regular format (e.g. each model attribute is displayed as a row in a table.) The model can be either an instance of yii\base\Model or an associative array.
DetailView uses the $attributes property to determines which model attributes should be displayed and how they should be formatted.
A typical usage of DetailView is as follows:
echo DetailView::widget([
    'model' => $model,
    'attributes' => [
        'title',               // title attribute (in plain text)
        'description:html',    // description attribute in HTML
        [                      // the owner name of the model
            'label' => 'Owner',
            'value' => $model->owner->name,
        ],
        'created_at:datetime', // creation date formatted as datetime
    ],
]);

Examples of DetailsView


View Form

View Code

<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use backend\modules\tools\models\Groupitems;
$this->title = 'Note : '. $model->slno;
$this->params['breadcrumbs'][] = ['label' => 'Students Instructions Note', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="studentsgblinvoicenote-view box box-body table-responsive">  
    <p>
        <?= Html::a('Update', ['update', 'ccid' => $model->ccid, 'slno' => $model->slno], ['class' => 'btn btn-primary']) ?>
        <?= Html::a('Delete', ['delete', 'ccid' => $model->ccid, 'slno' => $model->slno], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => 'Are you sure you want to delete this item?',
                'method' => 'post',
            ],
        ]) ?>
    </p>

    <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'slno',
            'course',
             'note1',
            'note2'                  
        ],
    ]) ?>
</div>

Controller action

 public function actionView($ccid, $slno)
    {
        return $this->render('view', [
            'model' => $this->findModel($ccid, $slno),
        ]);
    }


More Details

Karthik DetailView: http://demos.krajee.com/detail-view

Put line break in DetailsView

Textarea saved data to display in DeatilsView



<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use backend\modules\tools\models\Groupitems;

$this->title = 'Note : '. $model->slno;
$this->params['breadcrumbs'][] = ['label' => 'Students Instructions Note', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

<div class="studentsgblinvoicenote-view box box-body table-responsive">

 

    <p>
        <?= Html::a('Update', ['update', 'ccid' => $model->ccid, 'slno' => $model->slno], ['class' => 'btn btn-primary']) ?>
        <?= Html::a('Delete', ['delete', 'ccid' => $model->ccid, 'slno' => $model->slno], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => 'Are you sure you want to delete this item?',
                'method' => 'post',
            ],
        ]) ?>
    </p>

    <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            //'ccid',
            'slno',                    
            [
                'label'  => 'Course',
                'value'  => Groupitems::getGroupitems($model->course),           
            ],
         
            [
                'label' => 'Note 1',
                'format'=>'raw',
                'value' => nl2br($model->note1 ),
            ],    
   
            [
                'label' => 'Note 2',
                'format'=>'raw',
                'value' => nl2br($model->note2),
            ],  
         
        ],
    ]) ?>

</div>


Changing value of an attribute in DetailView widget

The above example call from function to display DetailsView
                'value'  => Groupitems::getGroupitems($model->course),       


<?= DetailView::widget([
    'model' => $model,
    'attributes' => [
        'name',
        'max_people_count',
        'type',
        [
             'attribute' => 'recurring',
             'format'=>'raw',
             'value'=> function ($model) {
                        if($model->recurring == 1)
                        {

                            return 'yes';

                        } 
                        else {
                        return 'no';
                        }
                      },
        ],
        'day',
        'time',
        ...

'value' => $model->recurring == 1 ? 'yes' : 'no'
The nl2br() function inserts HTML line breaks (<br> or <br />) in front of each newline (\n) in a string.


Add Button in DetailsView




<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use backend\modules\master\models\Masterfunctions;

/* @var $this yii\web\View */
/* @var $model backend\modules\tools\models\Centermessage */

$this->title = $model->ctm_id;
$this->params['breadcrumbs'][] = ['label' => 'Centermessages', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;

$model->ctm_centers = Masterfunctions::getCenters($model->ctm_centers);
?>
<div class="centermessage-view box box-body table-responsive">
 
 
<?php

$button1 = Html::a('<span class = "glyphicon glyphicon-download"></span> Download', ['docs-download', 'filename' => $model->ctm_filename,], ['class' => 'btn-primary', 'title' => '', 'data' => ['method' => 'post']]);
$model->ctm_filename=$button1;
?>
   
    <?= DetailView::widget([
        'model' => $model,
 
        'attributes' => [                      
            [
          'attribute' => 'ctm_date',
          'format' =>  ['date', 'php:d-m-Y'],    
   ],
            'ctm_heading',
            'ctm_message',
            [
                'attribute' =>'ctm_filename',                
                'format'=>'html',
            ],
           
            'ctm_centers',
            'ctm_status',
        ],
    ]) ?>

</div>







Related Links

DropDownList

Yii2 Dependent Drop Down Lists

CheckboxList Advanced Operations

Yii2 ListBox Field



Wednesday, 5 April 2017

Mysql composite primary key with set foreign key


Foreign key referencing only part of composite primary key


Primary Key = UNIQUE + NOT NULL + Automatic Indexed


Primary key can be defined for a combination of columns, When a primary key consist of multiple columns, then it is called a Composite Primary Key.


MySql Create Foreign Key

Create foreign key referencing to primary key


ALTER TABLE  `tb2` ADD FOREIGN KEY (  `tb1_ccid` ) REFERENCES  `test`.`tb1` (
`ccid`) ON DELETE RESTRICT ON UPDATE RESTRICT ;


Create foreign key referencing to composite primary key

ALTER TABLE  `tb2` ADD FOREIGN KEY (  `tb1_ccid` ,  `tb1_sid` ) REFERENCES  `test`.`tb1` ( `ccid` ,`sid`) ON DELETE RESTRICT ON UPDATE RESTRICT


Example

create table tb1
( A integer not null
, B char(2) not null
, C integer not null
, primary key (A,B,C)
, unique (A,B)
);
create table tb2
( M integer not null
, N char(2) not null
, Z datetime
, foreign key (M,N) references tbl1 (A,B)
)




Tuesday, 28 March 2017

Yii2 Dependent Drop Down Lists


Creating a Dependent Dropdown From in Yii2





Company drop down list change to display corresponding branches display on branches drop down  list box.

First create table companies, branches and department

companies
company_id
company_name

branches
branch_id
companies_company_id
branch_name

departments
department_id
branches_branch_id
companies_company_id
department_name
status

* companies_company_id  set relation to company_id
* branches_branch_id set relation to branch_id




Create companies ,branches and departments crud operations .

Department create view _form.php code


<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use backend\modules\test\models\Companies;
use backend\modules\test\models\Branches;

?>

<div class="departments-form">

    <?php $form = ActiveForm::begin(); ?>

 
    <?= $form->field($model, 'companies_company_id')->dropDownList(
 ArrayHelper::map(Companies::find()->all(), 'company_id', 'company_name'),
             ['prompt'=>'Select Company',
              'onchange'=>'
                $.post( "index.php?r=test/branches/lists&id="+$(this).val(), function( data ) {
                  $( "select#departments-branches_branch_id" ).html( data );
                });'
            ]); ?>
    
    
    <?= $form->field($model, 'branches_branch_id')->dropDownList(
 ArrayHelper::map(Branches::find()->all(), 'branch_id', 'branch_name'),
             ['prompt'=>'Select Baranch',              
            ]); ?>      

    <?= $form->field($model, 'department_name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'status')->dropDownList([ 'Active' => 'Active', 'Inactive' => 'Inactive', ], ['prompt' => '']) ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

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

</div>


Note :
test/branches/lists  - create action lists in branches controller.
departments-branches_branch_id - id of branch drop down list controller.
Send company id send to branches controller lists action

The BrachesController.php



<?php

namespace backend\modules\test\controllers;

use Yii;
use backend\modules\test\models\Branches;
use backend\modules\test\models\BranchesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;


/**
 * BranchesController implements the CRUD actions for Branches model.
 */
class BranchesController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

 
    public function actionLists($id)
    {
        
        $countBranches = Branches::find()
                ->where(['companies_company_id' => $id])
                ->count();

        $branches = Branches::find()
                ->where(['companies_company_id' => $id])
                ->orderBy('branch_id DESC')
                ->all();

        if($countBranches>0){
            foreach($branches as $branch){
                echo "<option value='".$branch->branch_id."'>".$branch->branch_name."</option>";
            }
        }
        else{
            echo "<option>-</option>";
        }
        
        //echo "<option>-</option>";

    }
 
 
.....
.....
.....

}





Yii 2.0: Creating a Dependent Dropdown From Scratch in Yii2


Related Links

YII2 CRUD Operations code with Gii
DropDownList

Yii2 Pjax Tutorial

Yii Tabular Input

Updating Gridview Using Pajax
Multiple submit button in Yii2 view forms