Menus

Thursday 27 October 2016

Yii Tabular Input


Yii2 Insert multiple records of a same table




Collecting Tabular Input

           Sometimes we want to collect user input in a batch mode. That is, the user can enter the information for multiple model instances and submit them all at once. We call this tabular input because the input fields are often presented in an HTML table.
          To work with tabular input, we first need to create or populate an array of model instances, depending on whether we are inserting or updating the data. We then retrieve the user input data from the $_POST variable and assign it to each model. A slight difference from single model input is that we retrieve the input data using $_POST['ModelClass'][$i] instead of$_POST['ModelClass'].

In contrast to the single model forms explained before, we are working with an array of models now. This array is passed to the view to display the input fields for each model in a table like style and we will use helper methods of yii\base\Model that allow loading and validating multiple models at once:

This example for validate and save tabular data. Help to avoid insert many times the same table with ActiveForm.



Modify your controller code to use multiple models


<?php

namespace backend\modules\tools\controllers;

use Yii;
use backend\modules\tools\models\Products;
use backend\modules\tools\models\ProductsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\base\Model;

/**
 * ProductsController implements the CRUD actions for Products model.
 */
class ProductsController extends Controller
{

.................
................

public function actionCreate()
    {

        //Find out how many products have been submitted by the form
        //$count = count(Yii::$app->request->post('Product', []));
        $count=4;

        //Send at least one model to the form
        $prts = [new Products()];

        //Create an array of the products submitted
        for($i = 1; $i < $count; $i++) {
            $prts[] = new Products();
        }
        
        
        //Load and validate the multiple models
        if (Model::loadMultiple($prts, Yii::$app->request->post()) && Model::validateMultiple($prts)) {

            foreach ($prts as $product) {

                //Try to save the models. Validation is not needed as it's already been done.
                $product->save(false);

            }
            return $this->redirect('view');
        }

        return $this->render('create', ['prts' => $prts]);
                
    }

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


 The view file for the form needs to be altered like this, to use the multiple models;


<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\modules\tools\models\Products */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="products-form">

    <?php $form = ActiveForm::begin(); ?>
 
   <table>
        <tr>
            <td>Product Name</td>
            <td>Product Qty</td>
            <td>Product Price</td>
        </tr>
        <?php foreach ($prts as $index => $product) { ?>       
        <tr>            
            <td><?= $form->field($product, "[$index]product_name")->textInput(['maxlength' => true])->label(FALSE) ?></td>
            <td><?= $form->field($product, "[$index]product_quantity")->textInput()->label(FALSE) ?></td>
            <td><?= $form->field($product, "[$index]product_price")->textInput(['maxlength' => true])->label(FALSE) ?></td>        
        </tr> 
       <?php } ?>
    </table>
     
    <div class="form-group">
        <?= Html::submitButton($product->isNewRecord ? 'Create' : 'Update', ['class' => $product->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

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

</div>


View shows




Solutions:
I want to add multiple records from a form into a table.



Tuesday 27 September 2016

Yii2 grid with Editable column



How to save data in model using Yii2 grid with Editable column


Actually the solution is easy and need to the id of that specific row to update.
We are use ajax.


Explain how in Yii 2 Framework, we can setup the enhanced Krajee EditableColumn to work with theKrajee GridView widget. The objective is to achieve the following functionality using kartik\grid\GridView andkartik\grid\EditableColumn:
  1. configure a grid cell content to be editable
  2. use advanced input widgets to edit content
  3. capture the editable content POSTED via controller and update database via ajax
  4. trigger model validation and validation error messages if needed


Inputs

  • Editable::INPUT_HIDDEN or 'hiddenInput'
  • Editable::INPUT_TEXT or 'textInput'
  • Editable::INPUT_PASSWORD or 'passwordInput'
  • Editable::INPUT_TEXTAREA or 'textArea'
  • Editable::INPUT_CHECKBOX or 'checkbox'
  • Editable::INPUT_RADIO or 'radio'
  • Editable::INPUT_LIST_BOX or 'listBox'
  • Editable::INPUT_DROPDOWN_LIST or 'dropDownList'
  • Editable::INPUT_CHECKBOX_LIST or 'checkboxList'
  • Editable::INPUT_RADIO_LIST or 'radioList'
  • Editable::INPUT_HTML5_INPUT or 'input'
  • Editable::INPUT_FILE or 'fileInput'
  • Editable::INPUT_WIDGET or 'widget', use this for any custom widget class to be used

More Details


Yii2 Grid View add editable column









Most Popular Extension for Gridview Inline Edit is Kartik-v Yii2 Editable.
Few Reference Links and Demos:



Yii 2 Editable

Easily set any displayed content as editable in Yii Framework 2.0. This is an enhanced editable widget for Yii 2.0 that allows easy editing of displayed data, using inputs, widgets and more with numerous configuration possibilities.

More Details http://demos.krajee.com/editable

Date Control yii2-datecontrol


The Date Control module allows controlling date formats of attributes separately for View and Model for Yii Framework 2.0. 

More Details http://demos.krajee.com/datecontrol



Example


Editable Column type Editable::INPUT_DATE is not recognized as date by Formatter

Solution 1


[
    'class' => 'kartik\grid\EditableColumn',
    'attribute'=>'publish_date',
    'vAlign' => 'middle',
    'headerOptions' => ['class' => 'kv-sticky-column'],
    'contentOptions' => ['class' => 'kv-sticky-column'],
    'editableOptions' => [
        'header' => 'PublishDate', 
        'size' => 'md',
        'inputType'=>\kartik\editable\Editable::INPUT_WIDGET,
        'widgetClass'=> 'kartik\datecontrol\DateControl',
        'options'=>[
            'type'=>\kartik\datecontrol\DateControl::FORMAT_DATE,
            'options' => [
                'pluginOptions' => [
                    'autoclose' => true
                ]
            ]
        ]
    ],
],


Output as






Example

This example add editable column in kartik grid view.
This grid view contains three types of editable controls such as DATE, TEXTVIEW and DROP DOWN LIST.




***************************
Source code of above grid view.
***************************

Use packeges are
use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\editable\Editable;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;

 
$dataProvider->setPagination(false);
echo GridView::widget([
    'dataProvider' => $dataProvider,
    'formatter' => ['class' => 'yii\i18n\Formatter','nullDisplay' => ''],  
    'pjax'=>true,
    'export'=>false,
 
    'columns' => [
            ['class' => 'yii\grid\SerialColumn'],          

            [
                'attribute'=>'students_admission_number',
                'label'=>'ADD NO',
                'contentOptions' => ['style' => 'width:50px;'],                  
            ],
            [
                'attribute'=>'ccid',    
                'label'=>'Cid',
                'contentOptions' => ['style' => 'width:30px;'],
            ],
            [
                'attribute'=>'Name',              
                'value'=>'studentsAdmissionNumber.student_name',
            ],
            [
                'attribute'=>'semester_year',
                'label'=>'S/Y',
                'contentOptions' => ['style' => 'width:30px;'],
            ],  
            [
                'attribute' => 'requested_date',    
                'format' =>  ['date', 'php:d-m-Y'],              
            ],
         
            [
                'class' => 'kartik\grid\EditableColumn',
                'attribute'=>'issued_date',
                'vAlign' => 'middle',
                'headerOptions' => ['class' => 'kv-sticky-column'],
                'contentOptions' => ['class' => 'kv-sticky-column'],
                'format' =>  ['date', 'php:d-m-Y'],        
                'editableOptions' => [
                    'header' => 'Issued Date', 
                    'size' => 'md',
                    'inputType'=>\kartik\editable\Editable::INPUT_WIDGET,
                    'widgetClass'=> 'kartik\datecontrol\DateControl',
                    'options'=>[
                        'type'=>\kartik\datecontrol\DateControl::FORMAT_DATE,
                        'options' => [
                            'pluginOptions' => [
                                'autoclose' => true
                            ]
                        ]
                    ]
                ],
            ],
   
            [
                'class' => 'kartik\grid\EditableColumn',
                'header'=>'Remarks',
                'attribute' => 'remarks',
                'editableOptions'=> [
                    'format' => Editable::FORMAT_BUTTON,
                    'inputType' => Editable::INPUT_TEXTAREA,      
                ]
            ],

     
           [
                'class'=>'kartik\grid\BooleanColumn',
                'class' => 'kartik\grid\EditableColumn',

                'attribute'=>'status', 
                'vAlign'=>'middle',
                'editableOptions'=> [
                        //'format' => Editable::FORMAT_BUTTON,
                        'inputType' => Editable::INPUT_DROPDOWN_LIST,

                        'data' => [0 => 'No', 1 => 'Ok'],
                        'options' => ['class'=>'form-control'], //, 'prompt'=>'status...'],
                        'displayValueConfig'=> [
                            '0' => '<i class="glyphicon glyphicon-remove"></i>',
                            '1' => '<i class="glyphicon glyphicon-ok"></i>',                        
                        ],

                    ],
                ],
   
        ],
 
 
    'bordered' => true,
    'striped' => false,
    'condensed' => false,
    'responsive' => true,
    'hover' => true,
    'floatHeader' => true,
    'showFooter'=>TRUE,
    'panel' => [
        'type' => GridView::TYPE_PRIMARY,          
        'heading' => '<i class="fa fa-book"></i> <b>List of Study Materials for Despatch</b>',
    ],
 
    'toolbar' => [],

]);


**********************************
Controller called method includes codes 
**********************************

 public function actionDespatch(){
     
     
        $model = new StudentsstudymaterialsSearch();
     
        //codes for working editable columns
        if (Yii::$app->request->post('hasEditable')) 
        {

            $model =Yii::$app->request->post('editableKey');
              
            //my code 
            $data = json_decode($model, true); 
            
            $model  = $this->findModel($data['id'],$data['ccid']);
            $out    = Json::encode(['output'=>'', 'message'=>'']);
            
            $post = [];
            $posted = current($_POST['StudentsstudymaterialsSearch']);  //model
            $post['Studentsstudymaterials'] = $posted;
         
            if ($model->load($post)) {
            $model->save();
            $output = '';
            if (isset($posted['remarks'])) 
            {
              $output =  $model->remarks;
            }
            if (isset($posted['issued_date'])) 
            {
              $output =  date('d-m-Y',strtotime($model->issued_date));
            }
            
             $out = Json::encode(['output'=>$output, 'message'=>'']); 
          }
          
          $out = Json::encode(['output'=>$output, 'message'=>'']); 
          echo $out;
          return;
        }

         return $this->render('despatch',['model'=>$model]);
     
    }







Next Example


Easily set any displayed content as editable in Yii Framework 2.0


Ajax Usage Example for editable gridview


STEP 1: SETUP YOUR CONTROLLER ACTION
add this your header section

use yii\helpers\Json;



public function actionIndex()
    {

        $searchModel = new MastersettingsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        // Check if there is an Editable ajax request
        if (Yii::$app->request->post('hasEditable'))
        {

            $id =Yii::$app->request->post('editableKey');          
            $model  = $this->findModel($id);
           
            $out    = Json::encode(['output'=>'', 'message'=>'']);          
            $post = [];
            $posted = current($_POST['Mastersettings']);  //model
            $post['Mastersettings'] = $posted;
       
            if ($model->load($post)) {
                $model->save();              
           
            $output = '';
            if (isset($posted['status']))
            {
              $output =  $model->status;
              $out = Json::encode(['output'=>$output, 'message'=>'']);
            }                                              
          }
                 
         // return JSON encoded output in the below format
          echo $out;
          return;
        }
       
       
       
        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);

    }



STEP 2: SETUP WIDGET IN VIEW

<?php

use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\editable\Editable;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;

$this->title = 'Mastersettings';
$this->params['breadcrumbs'][] = $this->title;
?>

<div class="mastersettings-index">

    <?php
   
$dataProvider->setPagination(false);
echo GridView::widget([
    'dataProvider' => $dataProvider,
    'formatter' => ['class' => 'yii\i18n\Formatter','nullDisplay' => ''],
    'pjax'=>true,
    'export'=>false,
   
    'columns' => [
       
            [
                'class'=>'kartik\grid\BooleanColumn',
                'class' => 'kartik\grid\EditableColumn',
                'attribute'=>'status', 
                'vAlign'=>'middle',                
                'editableOptions'=> [
                        //'format' => Editable::FORMAT_BUTTON,
                        'inputType' => Editable::INPUT_DROPDOWN_LIST,
                    
                        'data' => [0 => 'Set', 1 => 'Not Set'],
                        'options' => ['class'=>'form-control'], //, 'prompt'=>'status...'],
                        'displayValueConfig'=> [
                            '0' => '<i class="glyphicon glyphicon-remove"></i>',                        
                            '1' => '<i class="glyphicon glyphicon-ok"></i>',                        
                        ],

                    ],                                
                ], 
       
            'description',      
        ],
       
    'bordered' => true,
    'striped' => false,
    'condensed' => false,
    'responsive' => true,
    'hover' => true,
    'floatHeader' => true,
           
    'panel' => [
        'type' => GridView::TYPE_PRIMARY,          
        'heading' => '<i class="fa fa-cog"></i> <b> DSMS online software master settings</b>',
    ],
         
    // set your toolbar
    'toolbar'=> [
    ],
   
]);


?>
   
   
</div>



More further details

http://demos.krajee.com/editable



Related Links

Yii2 Grid View Operations


Yii2 gridview widget filter


YII2 Grid View Advanced Options


Event Calendar in Yii


Note : Please add your valuable comments and add your tutorial links in comments column for helps to others..

Thursday 8 September 2016

Redirect to another action in YII2


REDIRECT TO ANOTHER ACTION IN YII2


yii2 redirect in controller action does not work?



$this->redirect()


While developing web application we need to redirect to different url in our application.

Redirect helps us to load different url from different location.

In Yii2 framework we can do it through redirect method of Controller class.


Redirect to action to same or different action in controller

$this->redirect(\Yii::$app->urlManager->createUrl("controllerName/actionName"));

$this->redirect(\Yii::$app->urlManager->createUrl("moduleName/controllerName/actionName"));

Send extra parameter then use redirect.


$this->redirect(\Yii::$app->urlManager->createUrl(array("master/studentsstudymaterials/despatch", 'id'=>10)));



public function actionName1($param1,$param2) {

    //your code...

}

public function actionName2() {

    $this->redirect(array('name1','param1'=>'param1','param2'=>'param2'));

}




Following example helps to implement redirection in Controller class.


namespace app\controllers

use Yii;

Class TestController extends Controller{


     public function actionIndex(){
          $this->redirect(\Yii::$app->urlManager->createUrl("test/show"));
    }

    public function actionShow(){
       //your action here
   }


}

In above example when we visit test/index then this action redirect to show method of the test class. 


More Details

Thursday 1 September 2016

YII2 CRUD Operations code with Gii

What is CRUD


CRUD stands for Create, Read, Update, and Delete, representing the four common tasks taken with data on most Web sites. CRUD Generator generates a controller and views that implement CRUD operations for the specified data model.

What is Gii?

Gii is web-based code generator. 
With Gii we can quickly generate models, forms, modules, CRUD, etc.. 

How to use Gii


In our environment we can use Gii web-based interface by going to this address:
http://localhost/project-folder/backend/web/index.php?r=gii
You should see:


Model Generator

This generator generates an ActiveRecord class for the specified database table.
CRUD Generator
This generator generates a controller and views that implement CRUD (Create, Read, Update, Delete) operations for the specified data model.

Controller Generator

This generator helps you to quickly generate a new controller class with one or several controller actions and their corresponding views.

Form Generator

This generator generates a view script file that displays a form to collect input for the specified model class.

Module Generator

This generator helps you to generate the skeleton code needed by a Yii module.

Extension Generator

This generator helps you to generate the files needed by a Yii extension.

How to use Gii and Generating CRUD code


We can generate CRUD code directly in the Gii code generator. To go to CRUD generator click on the “CRUD Generator” button or go to this address:
http://localhost/project-folder/backend/web/index.php?r=gii%2Fdefault%2Fview&id=crud

There are several form fields which we have to fill:

Model class - This is the ActiveRecord class associated with the table that CRUD will be built upon.
Search Model Class - This is the name of the search model class to be generated.
Controller Class - This is the name of the controller class to be generated.
View Path - Specify the directory for storing the view scripts for the controller.
Widget Used in Index Page - This is the widget type to be used in the index page to display list of the models.







Note : Please add your valuable comments and add your tutorial links in comments column for helps to others..

Thursday 18 August 2016

Android Programming Tips


INDEX
Converting a string to an integer on Android
Converting a int to an string on Android
Converting a string to an double on Android
Converting a long to an string on Android
Decimal Format
Android Date Format Change
Set the focus on EditText Programmatically
Check If EditText is empty
Preventing going back to the previous activity
Set max-length of EditText programmatically with other InputFilter
String comparison - Android




Converting a string to an integer on Android


int in = Integer.valueOf(et.getText().toString());
//or
int in2 = new Integer(et.getText().toString());


Converting a int to an string o android



int tmpInt = 10;
String tmpStr10 = String.valueOf(tmpInt);

int tmpInt = 10;
String tmpStr10 = Integer.toString(tmpInt);

Converting a string to an double on Android

try this:
double d= Double.parseDouble(yourString);



Converting a long to an string on Android


String strLong = Long.toString(longNumber);


Decimal Format


new DecimalFormat("##,##,##0").format(amount);

Displaying Currency in Indian Numbering Format


Examples:

amount.setText(new DecimalFormat("####0.00").format(amount_item).toString());

or

total.setText(new DecimalFormat("####0.00").format(Double.parseDouble(txtCount.getText().toString()) * amount_item));

Android Date Format Change


SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(new Date());

The date format in sqlite should be of following format:
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDDDDDDDD 

For more details, have a look: http://www.sqlite.org/lang_datefunc.html


set the focus on EditText Programmatically


editText = (EditText)findViewById(R.id.myTextViewId); 
editText.requestFocus();



Check If EditText is empty



if(txtNumber.getText().toString().trim().length() == 0){
    Toast.makeText(getApplicationContext(),"Number cannot be blank!" ,Toast.LENGTH_SHORT).show();
    txtNumber.requestFocus();
    return;
}

use the TextUtils class like this :
if(TextUtils.isEmpty(strUserName)) {
    Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
    return;
}


This example check If EditText is empty and value must be a graterthan zero


if(txtCount.getText().toString().trim().length() == 0 || Integer.parseInt(txtCount.getText().toString()) <1){
    Toast.makeText(getApplicationContext(),"Count cannot be blank!" ,Toast.LENGTH_SHORT).show();
    txtCount.setText("");
    txtCount.requestFocus();
    return;
}





Preventing going back to the previous activity


Following solution can be pretty useful in the usual login / main activity scenario or implementing a blocking screen.
To minimize the app rather than going back to previous activity, you can override onBackPressed() like this:

@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

Another Solutions
LoginActivity on successful login starts the Main activity and this time because the user is logged on, the Main activity will continue its normal course. LoginActivity is declared as following in the manifest file:
<activity android:name="LoginScreen" android:label="@string/app_name"
    android:noHistory="true" android:excludeFromRecents="true">
</activity>
Setting noHistory and excludeFromRecents to true for LoginActivity means that the user cant return to this activity using back button.


Set max-length of EditText programmatically with other InputFilter

Use InputFilter set text length
Limit the character input in an EditText , EditText in XML layout gives us android:maxLength
Try this
txtNumber.setFilters(new InputFilter[]{new InputFilter.LengthFilter(3)});
function
public void setEditTextMaxLength(int length) {
    InputFilter[] FilterArray = new InputFilter[1];
    FilterArray[0] = new InputFilter.LengthFilter(length);
    edt_text.setFilters(FilterArray);
}
EditText et = new EditText(this);
int maxLength = 3;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
et.setFilters(FilterArray);
public void setEditTextMaxLength(final EditText editText, int length) {
    InputFilter[] FilterArray = new InputFilter[1];
    FilterArray[0] = new InputFilter.LengthFilter(length);
    editText.setFilters(FilterArray);
}


String comparison - Android


Check equals

if(item=="ALL"){
    ..........
    ..........
}


Android string comparison for use equal() method to compare the value of the objects.

if(gender.equals("Male"))
 salutation ="Mr.";
if(gender.equals("Female"))
 salutation ="Ms.";

string1.equals(string2)
// returns true if both strings are equal

string1.compareTo(string2)
// returns 0 if both strings are equal