Yii2 GridView table usage

Posted by Franko126 on Tue, 23 Nov 2021 07:11:02 +0100

The display of list data under Yii2 framework is usually realized by Gridview. Here are some common tips for future query

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'layout' => "{items}\n{summary}\n{pager}",
    'tableOptions' => ['class' => 'table table-striped table-bordered table-hover'],
    'columns' => [
        
    ],
]); ?>

Table overall configuration

Custom line style

Odd numbers represent a green background, and even numbers represent a red background

<?= GridView::widget([
    // ......
    "dataProvider" => $dataProvider,
    "rowOptions" => function($model, $key, $index, $grid) {
        return ["class" => $index % 2 == 0 ? "red" : "green"];
    },
    // ......
]); ?>

red and green need to have corresponding style implementations

Prohibit header sorting

Setting of ActiveDataProvider is required

$dataProvider = new ActiveDataProvider([ "query" => $query, ]); 
$dataProvider->setSort(false);

Table header

<?= GridView::widget([
    // ......
    "dataProvider" => $dataProvider,
    'caption' => 'Order management',
    'captionOptions' => ['style' => 'font-size: 18px; font-weight: bold; color: #000; text-align: center;'],
    
    "rowOptions" => function($model, $key, $index, $grid) {
        return ["class" => $index % 2 == 0 ? "red" : "green"];
    },
    // ......
]); ?>

Table column configuration

The columns are displayed in the columns array

Set width

Set the width of the title column to 100 by configuring the item headerOptions

[
    "attribute" => "title",
    "value" => "title",
    "headerOptions" => ["width" => "100"],
],

html rendering

The output string also has html tags, such as < p > Hello World < / P. if we want to display Hello world in the form of P tag, we need to specify the format as raw

[
    "attribute" => "title",
    "value" => function ($model) { 
        return Html::encode($model->title); 
    },
    "format" => "raw",
],

Title Content style

Content centered

[
    'attribute' => 'replay_url',
    'headerOptions' => ['style' => 'text-align:center;', 'width' => '200'],
],

Field content style

Content wrap

[
    'attribute' => 'replay_url',
    'contentOptions' => ['style' => 'white-space: normal;', 'width' => '200'],
],

The field cannot be sorted by clicking

[
    'attribute' => 'id',
    'enableSorting' => false,
],

Show specified column

When the value of type is equal to 1, the name column is displayed; otherwise, the column is not displayed

[
    "attribute" => "name",
    "value" => $model->name,
    "visible" => intval(Yii::$app->request->get("type")) == 1,
],

Click the link to jump

[
    "attribute" => "order_id",
    "value" => function ($model) {
        return Html::a($model->order_id, "/order/detail?id={$model->order_id}", ["target" => "_blank"]);
    },
    "format" => "raw",
],

display picture

[
    "label" => "Product picture",
    "format" => [
        "image", 
        [
            "width"=>"200",
            "height"=>"200"
        ]
    ],
    "value" => function ($model) { 
        return $model->image; 
    }
],

Custom action button

By setting the ActionColumn class, modify the configuration item template, and add the log added in the template in the buttons item

[
    "class" => "yii\grid\ActionColumn",
    "template" => "{log} {view} {update}",
    "header" => "operation",
    "buttons" => [
        "log" => function ($url, $model, $key) { 
            return Html::a("journal", $url, ["title" => "view log"] ); 
        },
    ],
],

Operation button calls JS

[
    "class" => "yii\grid\ActionColumn",
    "header" => "operation",
    "template" => "{view} {update} {update-status}",
    "buttons" => [
        "update-status" => function ($url, $model, $key) {
            return Html::a("Update status", "javascript:;", ["onclick"=>"update_status(this, ".$model->id.");"]); },
    ],
],

You need to write js on the page to implement update_status method

Custom field

Add a column in the table and there is no corresponding column in the database

[
    "attribute" => "Consumption amount",
    "value" => function ($model) {
        // Here, you can perform association acquisition according to other fields in the table
        return ;
    }
],

Realize batch deletion

  1. Add an id when setting options for GridView. Here we name grid
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    "options" => [
        // ... other settings
        "id" => "grid"
    ],
]); ?>
  1. Check boxes are required for batch deletion. Add an option check box in columns, and set the name value to id to facilitate data operation
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    "options" => [
        "id" => "grid"
    ],
    "columns" => [
        // ......
        [
            "class" => "yii\grid\CheckboxColumn",
            "name" => "id",
        ],
        // ......
    ],
]); ?>
  1. A batch delete button is added on the page, and a classbatch del is added here to facilitate the click effect of the following js
<?= Html::a("Batch delete", "javascript:;", ["class" => "btn btn-success batch-del"]) ?>
  1. js to implement button operation
<?php
$this->registerJs('
$(".batch-del").on("click", function () {
    //Note that the $("#grid") here should be consistent with the options id set in the first step
    var keys = $("#grid").yiiGridView("getSelectedRows");
    console.log(keys);
});
');
?>

Format format

In view

  • Processing html tags
'format' => 'raw'
  • processing time
'format' => ['date', 'php:Y-m-d H:i']
  • Processing pictures
"format" => [
    "image", 
    [
        "width"=>"200",
        "height"=>"200"
    ]
],

In controller

yii\i18n\Formatter

Common properties

  1. $dateFormat
    Date format: yyyy MM DD, or "short", "medium", "long", or "full"
  2. $datetimeFormat
    Specific time format: yyyy MM DD HH: mm: SS
  3. $locale
    If the region location is not set, yii\base\Application::$language will be used to display the format according to the custom of this region
  4. $defaultTimeZone
    Time zone, default UTC
  5. To use formatter, you need the configuration in config
'formatter' => [
    'dateFormat' => 'yyyy-MM-dd',
    'datetimeFormat' => 'yyyy-MM-dd HH:mm:ss',
    'decimalSeparator' => ',',
    'thousandSeparator' => ' ',
    'currencyCode' => 'CNY',
],

format

echo Yii::$app->formatter->asRelativeTime(1463632983).'<br/>'; // A few days ago, a few hours ago
echo Yii::$app->formatter->asDatetime(1463606983).'<br>';  // 2015-6-16 11:51:43
echo Yii::$app->formatter->asDatetime('now').'<br>';
// You can also handle the output display of null values:
echo Yii::$app->formatter->asDate(null).'<br>'; // Output: (not set)  
echo Yii::$app->formatter->asPercent(0.125, 2).'<br>'; // Output: 12.50%
echo Yii::$app->formatter->asTimestamp('now').'<br>';//Output timestamp
echo Yii::$app->formatter->asTime(1412599260).'<br>'; // 14:41:00
echo Yii::$app->formatter->asTime('2014-10-06 12:41:00').'<br>'; // 14:41:00
echo Yii::$app->formatter->asTime('2014-10-06 14:41:00 CEST').'<br>'; // 14:41:00

echo Yii::$app->formatter->asRaw(1463606983).'<br>';//Simple output input value
echo Yii::$app->formatter->asText('<h3>hello</h3>').'<br>';//The html tag in the string is output as a string
echo Yii::$app->formatter->asHtml('<h3>hello</h3>').'<br>';//Output as Html document
echo Yii::$app->formatter->asNtext("<h3>hello.\nword</h3>").'<br>';//Encountered in string \ nyou can implement it as a newline character
echo Yii::$app->formatter->asEmail('cebe@example.com').'<br>';// Output: < a href = "mailto: cebe@example.com "> cebe@example.com </a>
echo Yii::$app->formatter->asParagraphs('hello').'<br>';// The value will be converted into HTML encoded text paragraphs and wrapped with < p > tags;
echo Yii::$app->formatter->asUrl('www.baidu.com').'<br>';//The value is formatted as a url for the connection
echo Yii::$app->formatter->asImage('my2.jpeg',['alt'=>'The picture cannot be displayed']).'<br>';//The link to the picture will be converted to < img SRC ='My. JPG '/ >
echo Yii::$app->formatter->asBoolean(true).'<br>';//Output yes

Topics: yii Yii2