Menus

Monday, 19 December 2016

Mannually set a where condion for dataprovider in specific controller method



This code queryParams take from user index form.

public function actionIndex()
    {
        
            $searchModel = new StudentsSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);

    }


To add additional where condition for data provider.


public function actionIndex()
    {            
            $ccid = Yii::$app->user->identity->ccid;
            $searchModel = new StudentsSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
            $dataProvider->query->andWhere('center_ccid = '.$ccid);         
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

Usages:



$dataProvider = $searchModel->search([$searchModel->formName()=>['result_type'=>$result->result_type,'date'=>$result->date]]);
$query->andFilterWhere(['<>', 'role', $this->role]);
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $role = 'regular');
$searchModel = new ModelSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->andWhere(['lang'=>'ENG']);
$dataProvider = $searchModel->search(Yii::$app->request->queryParams+['EmployeeSearch' => ['<>', 'role' =>'regular']]);



Yii2 How to pass a range to search model


You can also use BETWEEN construction:
$query->andFilterWhere(['between', 'price', $this->min_price, $this->max_price]);

yii2 data provider default sorting


defaultOrder contain a array where key is a column name and value is a SORT_DESC orSORT_ASC 


$dataProvider->setSort([
'defaultOrder' => ['date'=>SORT_DESC,'result_type'=>SORT_ASC,'chance'=>SORT_ASC],
]);


$dataProvider = new ActiveDataProvider([
            'query'=> $query,
            'sort'=> [
                   'defaultOrder'=> ['your_column'=>SORT_ASC]]
       ]);





Tuesday, 6 December 2016

Getting value form a table using Ajax

Yii2 Ajax Operations

Value selected from a database table using ajax in yii2

Example explains to get amount of Rate and Ta from  staffdetails table with depend on staff  drop down list changed in staff log book view.




First create tow tables staffdetails and stafflogbook and do CRUD operations of these tables.

Table staffdetails
Fields
id
staff_name
.
.
rate
ta
.
.

Table stafflogbook
Fields
id
staffdetails_id
.
.
.
.

Open staff log book view and add to javascript change event of staff dropdown list controller.

<?php

$script = <<< JS
    $('#stafflogbook-staffdetails_id').change(function(){
      var id = $(this).val();
        $.get("index.php?r=master/staffdetails/get-rate-ta", {staff_id : id}, function(data) {
        
        var data = $.parseJSON(data);  
        
        $('#stafflogbook-rate').attr('value',data.rate);
        $('#stafflogbook-ta').attr('value',data.ta);
        
        });
   });        
JS;
$this->registerJs($script);

?>


* Get some value form staffdetails for write a function in StaffdetailsController

     public function actionGetRateTa($staff_id){
        //Find the staff_id from the Staffdetails table
        $rate = Staffdetails::findOne(['id'=>$staff_id]);
        echo json::encode($rate);      
    }


So json need to add json helper class

use yii\helpers\Json;



Video  - Getting value form a table using Ajax





Error in Javascript Function Call On Yii2 Dropdown Active Form


HOW to Use onChange on DropDownList

onchange function in dropDownList yii2


Use

$this->registerJs($script, \yii\web\View::POS_END);

The last part means - add this script straightforward at the end of page.


Code add in header area on view form

<?php

...

$script = <<< JS
    $('#students-course_applied').change(function(){
      var id = $(this).val();
       
       
        alert(id);
       
        test();
       
   });  
     
        function test()
        {
        alert("Test Function");
        }
JS;
$this->registerJs($script, \yii\web\View::POS_END);

?>



Yii dropdown call javascript function


<?= $form->field($model, 'admission_mode')->dropDownList(
                    ArrayHelper::map(Groupitems::find()->andwhere(['category'=>13])->orderBy('description')->all(),'slid','description'),
                    ['prompt'=>'Select One' , 'onchange'=>'test();']
                    )   ?>








Thank you for visiting


Tuesday, 29 November 2016

Multiple submit button in Yii2 view forms


Posting multiple submit button value to controller

check a specific submit button value in controller (Yii2)


Solution

First create view form with multiple submit button.


<?= Html::submitButton('Submit 1', ['name' => 'submit', 'value' => 'submit_1']) ?>
<?= Html::submitButton('Submit 2', ['name' => 'submit', 'value' => 'submit_2']) ?>

Controller action

If (\Yii::$app->request->isPost) {
   switch (\Yii::$app->request->post('submit')) {
      case 'submit_1':

      case 'submit_2':

   }
}
When you submit form by pressing enter (without click any submit button), submit_1 will be default value.

or other methord

if (Yii::$app->request->post()) {

  if (Yii::$app->request->post('submit') == 'submit_1') {
     //Code for submit button 1
  }

  if (Yii::$app->request->post('submit') == 'submit_2') {
    //Code for submit button 2
  }

}

or other methord

public function actionYourControllerName()
{
    if(isset($_POST['submit') && $_POST['submit']=='next') 
    {
      // your code
    } 
    else if(isset($_POST['submit']) && $_POST['submit']=='previous') 
    {
       // your code
    }
}





Tuesday, 22 November 2016

MySQL Tutorials



mysql “Where not in” using two columns


Use this

SELECT *
FROM CompletedTasks
WHERE (userID, taskID) NOT IN
      ( SELECT userID, taskID
        FROM PlannedTasks
      ) ;

Saturday, 12 November 2016

Dynamic Forms in Yii2 Operations


yii2-dynamicform

It is widget to yii2 framework to clone form elements in a nested manner, maintaining accessibility. 


Installation

The preferred way to install this extension is through composer.
Either run
php composer.phar require --prefer-dist wbraganca/yii2-dynamicform "*"
or add
"wbraganca/yii2-dynamicform": "*"
to the require section of your composer.json file.

Videos



Project Starting 


Step 1

First create table of po and po_item and relationship

Po table Structure


      * Set id as primary and auto increment

Po_item table Structure

     * Set id as primary and auto increment
     * po_id set INDEX

Now the next thing we have to create a relationship po_item.




Step 2

Using gii to create model, controller and view (CRUD Operations)






Step 3

Create operations

Edit view file _form.php under views/po
Edit controller file PoController.php under controllers
Add new file Model.php in models
Edit model PoItem.php, po_id property removed required 



Output View



The View   _form.php


<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;

?>

<div class="po-form">

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

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

    <?= $form->field($model, 'description')->textInput(['rows' => 6]) ?>

    
    <!--poitems-->    
    <div class="row">
        <div class="panel panel-default">
        <div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Po Items </h4></div>
        <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' => $modelsPoItem[0],
                'formId' => 'dynamic-form',
                'formFields' => [
                    'po_item_no',
                    'quantity',                
                ],
            ]); ?>

            <div class="container-items"><!-- widgetContainer -->
            <?php foreach ($modelsPoItem as $i => $modelPoItem): ?>
                <div class="item panel panel-default"><!-- widgetBody -->
                    <div class="panel-heading">
                        <h3 class="panel-title pull-left">Po Item</h3>
                        <div class="pull-right">
                            <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>
                        </div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="panel-body">
                        <?php
                            // necessary for update action.
                            if (! $modelPoItem->isNewRecord) {
                                echo Html::activeHiddenInput($modelPoItem, "[{$i}]id");
                            }
                        ?>
                        
                        <div class="row">
                            <div class="col-sm-6">
                                <?= $form->field($modelPoItem, "[{$i}]po_item_no")->textInput(['maxlength' => true]) ?>
                            </div>
                            <div class="col-sm-6">
                                <?= $form->field($modelPoItem, "[{$i}]quantity")->textInput(['maxlength' => true]) ?>
                            </div>
                        </div><!-- .row -->
                        
                    </div>
                </div>
            <?php endforeach; ?>
            </div>
            <?php DynamicFormWidget::end(); ?>
        </div>
    </div>
    </div>
    
    <!--poitems-->    
    
    
    
    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

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

</div>

Javascript Events


$(".dynamicform_wrapper").on("beforeInsert", function(e, item) {
    console.log("beforeInsert");
});

$(".dynamicform_wrapper").on("afterInsert", function(e, item) {
    console.log("afterInsert");
});

$(".dynamicform_wrapper").on("beforeDelete", function(e, item) {
    if (! confirm("Are you sure you want to delete this item?")) {
        return false;
    }
    return true;
});

$(".dynamicform_wrapper").on("afterDelete", function(e) {
    console.log("Deleted item!");
});

$(".dynamicform_wrapper").on("limitReached", function(e, item) {
    alert("Limit reached");
});


The Controller (sample code)

<?php

namespace backend\modules\dynamicform\controllers;

use Yii;
use backend\modules\dynamicform\models\Po;
use backend\modules\dynamicform\models\PoSearch;
use backend\modules\dynamicform\models\PoItem;
use backend\modules\dynamicform\models\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;

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

    /**
     * Lists all Po models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PoSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Po model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Po model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    
    public function actionCreate()
    {
        $model = new Po();
        $modelsPoItem = [new PoItem];

        if ($model->load(Yii::$app->request->post())) {

            
            $modelsPoItem = Model::createMultiple(PoItem::classname());
            Model::loadMultiple($modelsPoItem, Yii::$app->request->post());

            // validate all models
            $valid = $model->validate();
            $valid = Model::validateMultiple($modelsPoItem) && $valid;

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    if ($flag = $model->save(false)) {
                        foreach ($modelsPoItem as $modelPoItem) 
                            {                            
                            $modelPoItem->po_id = $model->id;
                            if (! ($flag = $modelPoItem->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                    }
                    if ($flag) {
                        $transaction->commit();
                        return $this->redirect(['view', 'id' => $model->id]);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
        
            
        }
        
        else {
            return $this->render('create', [
                'model' => $model,
                'modelsPoItem' => (empty($modelsPoItem)) ? [new PoItem] : $modelsPoItem
            ]);
        }
    }
    


    /**
     * Updates an existing model.     
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $modelsPoItem = $model->poItems;

        if ($model->load(Yii::$app->request->post())) {
            
            $oldIDs = ArrayHelper::map($modelsPoItem, 'id', 'id');
            $modelsPoItem = Model::createMultiple(PoItem::classname(), $modelsPoItem);
            Model::loadMultiple($modelsPoItem, Yii::$app->request->post());
            $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsPoItem, 'id', 'id')));

            // validate all models
            $valid = $model->validate();
            $valid = Model::validateMultiple($modelsPoItem) && $valid;

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    if ($flag = $model->save(false)) {
                        if (! empty($deletedIDs)) {
                            PoItem::deleteAll(['id' => $deletedIDs]);
                        }
                        foreach ($modelsPoItem as $modelPoItem) {
                            $modelPoItem->po_id = $model->id;
                            if (! ($flag = $modelPoItem->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                    }
                    if ($flag) {
                        $transaction->commit();
                        return $this->redirect(['view', 'id' => $model->id]);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }
            
        
        } 
        else {
             return $this->render('update', [
            'model' => $model,
            'modelsPoItem' => (empty($modelsPoItem)) ? [new Address] : $modelsPoItem
            ]);
    
        }
    }

    /**
     * Deletes an existing Po model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        PoItem::deleteAll(['po_id'=>$id]);
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Po model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Po the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Po::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


Model Class  Model.php


<?php
//add your name space
namespace backend\modules\dynamicform\models;

use Yii;
use yii\helpers\ArrayHelper;

class Model extends \yii\base\Model
{
    /**
     * Creates and populates a set of models.
     *
     * @param string $modelClass
     * @param array $multipleModels
     * @return array
     */
    public static function createMultiple($modelClass, $multipleModels = [])
    {
        $model    = new $modelClass;
        $formName = $model->formName();
        $post     = Yii::$app->request->post($formName);
        $models   = [];

        if (! empty($multipleModels)) {
            $keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
            $multipleModels = array_combine($keys, $multipleModels);
        }

        if ($post && is_array($post)) {
            foreach ($post as $i => $item) {
                if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']])) {
                    $models[] = $multipleModels[$item['id']];
                } else {
                    $models[] = new $modelClass;
                }
            }
        }

        unset($model, $formName, $post);

        return $models;
    }
}



Links
https://github.com/wbraganca/yii2-dynamicform#the-controller-sample-code


Please write your valuable comments