Menus

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



Thursday, 16 March 2017

Reset auto increment after deleting a table row (Android-SQLite)


How to reset auto-increment int when deleting all data from database?

SQLite Reset Primary Key Field

Reseting SQLite autoincrement column




One method to set zero

UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='table_name';

Second method to set maximum of id in current table

There are two simple steps in resetting an auto increment field:

Find the highest number in the auto increment field

To find the highest number, run the following SQL command:
SELECT MAX( `column` ) FROM `table` ;

Replace 'column' with the name of the auto incrementing column. Replace table with the name of the table.
Example : SELECT max(id) as id FROM customerentries

Reset the auto increment field

The next step is to take the number that you get from the first command and auto increment from there. So add one to that number and run the following command:

UPDATE SQLITE_SEQUENCE SET SEQ=new_value WHERE NAME='table_name';

Replacing new_value with the result of the previous command plus one and replacing table with the table_name.

Example:
 /*autoincrement id reset max of id*/
    public void resetIdCustomerentries(){
        try {
        String selectQuery = "SELECT max(id) as id FROM customerentries";
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cursor = database.rawQuery(selectQuery, null);
        cursor.moveToFirst();
        int idc = cursor.getInt(cursor.getColumnIndex("id"))+1;
        //int idc = cursor.getInt(0)+1;
        String updateQuery = "UPDATE SQLITE_SEQUENCE SET SEQ= "+ idc + " WHERE NAME='customerentries'";
        database.execSQL(updateQuery);
        database.close();
    }
    catch (android.database.sqlite.SQLiteConstraintException e) {
        Log.e("TAG:", "SQLiteConstraintException:" + e.getMessage());
    }
    catch (android.database.sqlite.SQLiteException e) {
        Log.e("TAG:", "SQLiteException:" + e.getMessage());
    }
    catch (Exception e) {
        Log.e("TAG:", "Exception:" + e.getMessage());
    }
    }

This resetIdCustomerentries function reset next value of  autoincrement field id.

Click Here

Related Links



Saturday, 4 March 2017

Set icon for android application


How can I set an icon for my android application?

Solutions for using set icon my android studio project

Steps

1 Choose icon picture copy this pic
2 Paste it into your project's res/drawable folder
3 Open manifest file and set 
    <application
   android:allowBackup="true"
   android:icon="@drawable/calendar"
   android:label="@string/app_name"
   android:supportsRtl="true"
   android:theme="@style/AppTheme">
.....
</application>
4 Run program








Show menu items in action bar




Friday, 3 March 2017

Show menu items in action bar


Menu items are showing on action BAR




Android action bar was used to maintain a consistent navigation across the application. Menu list button show on action bar.

Screen shot



Android - Navigation




Overview of Action Bar

Action bar mainly contains four functional areas. They are app icon, view control, action buttons and action overflow.
App Icon – App branding logo or icon will be displayed here.
View Control – A dedicated space to display app title. Also provides option to switch between views by adding spinner or tabbed navigation.
Action Buttons – Some important actions of the app can be added here.
Action Overflow – All unimportant action will be shown as a menu.

Here the important xml attributes should be known are
android:icon – Defines the icon of the action item.
android:title – Title for the icon.
android:showAsAction – Defines the visibility of the action item. It accepts following values.
ifRoomDisplays the icon if there is space available on the screen
neverNever places this icon on the action bar
alwaysForces to display the icon always irrespective of space available. This way is not suggested.
withTextDisplays a text along with the icon. Normally the text value defined by android:title will be displayed
collapseActionViewDefines the action layout associated with it. This action view defined usingandroid:actionLayout or android:actionViewClass



Example

Add menu title set as res/values/strings.xml


<resources>

    ....
    <string name="entries">ENTRIES</string>
    <string name="entrieslist">ENTRIES LIST</string>
    <string name="salesreport">SALES REPORT</string>
    <string name="logout">LOGOUT</string>


</resources>




Create a new xml file under res ⇒ menu named main_actions.xml and add the following code. 
Here each <item> indicates each action item.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/entries"
        android:title="@string/entries"
        app:showAsAction="never"
        />

    <item
        android:id="@+id/entrieslist"
        android:title="@string/entrieslist"
        app:showAsAction="never"
        />

    <item
        android:id="@+id/salesreport"
        android:title="@string/salesreport"
        app:showAsAction="never"
        />

    <item
        android:id="@+id/logout"
        android:title="@string/logout"
        app:showAsAction="never"
        />
</menu>


Now open your main activity class and do the following in onCreateOptionsMenu() method.


public class RptsalesreportActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rptsalesreport);

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_actions, menu);

        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

         switch (item.getItemId()) {
        case R.id.entries:
            // code here
            return true;
        case R.id.entrieslist:
            //code here
            return true;
        case R.id.salesreport:
            //code here
            return true;
        case R.id.logout:
            //code here
            return true;      
        default:
            return super.onOptionsItemSelected(item);
        }
        
    }


}


Handling Action Bar Icon Click Events

Open your main activity and override onOptionsItemSelected() method. This method accepts menu item as a parameter. Selected action item can be identified by using it’s id.