Table of Contents
Yii2的相关学习记录,Gridview小部件使用及kartik-v/yii2-grid扩展(五),yii2gridview
Home Backend Development PHP Tutorial Yii2的相关学习记录,Gridview小部件使用及kartik-v/yii2-grid扩展(五),yii2gridview_PHP教程

Yii2的相关学习记录,Gridview小部件使用及kartik-v/yii2-grid扩展(五),yii2gridview_PHP教程

Jul 12, 2016 am 08:55 AM
y yii2 use study Small Expand of Related Record part

Yii2的相关学习记录,Gridview小部件使用及kartik-v/yii2-grid扩展(五),yii2gridview

现在记录下Gridview的相关内容,也是强迫症犯了,Yii2自带的Gridview虽然不错,但是过滤栏如果一些字段用不着,不会自动合并成一行,当然也可以过滤栏不用,而是在最上方自己写一些需要检索的数据,但是这样很麻烦,还要自己去规划样式,写检索什么的。正好在搜索将检索栏和标题合并时,看到了kartik-v/yii2-grid可以实现这些功能,而且还自带导出excel、csv等数据,所以也顺便试了下它的功能,调出了自己喜欢的样式。在用kartik-v的Gridview之前我们还是要了解Yii2自带的Gridview的功能的,大体常用的一些方法如下:

1、Yii默认有四种样式的列,分别为Data column(默认)、Action column(操作)、Checkbox column(可选中)、Serial column(带序列号)

2、标题名字会根据Model中的attributeLabels()方法,来自动替换成对应的中文。当然也可以通过‘label’来自己定义,而‘attribute’则是指定根据哪个字段排序。其它的像是'visible'来隐藏显示,'header'显示头部内容,'headerOptions'来定义css或style样式等等。

<span>[
    </span>'label'=>'你想要的名称',
    'attribute'=>'id',<span>//</span><span>可以排序的字段</span>
<span>]
</span>
Copy after login

3、自定义显示页数和排序字段,如果用到了searchModel,则需要在searchModel的search方法中定义,否则,需要在Controller中定义:

<span>$dataProvider</span> = <span>new</span><span> ActiveDataProvider([
    </span>'query' => <span>$query</span>,
    'pagination' =><span> [
        </span>'pageSize' => 15,<span>//</span><span>如果不定义,默认为20</span>
    ],
    'sort' => ['attributes' => ['id']],<span>//</span><span>如果定义,则只能按照id来排序,否则所有字段都可以</span>
]);
Copy after login

4、下拉菜单检索,好比根据下拉菜单检索用户状态,则需要先在model中定义相关的方法,然后在Gridview中再做处理:

<span>//</span><span>Model中,定义一个静态方法</span>
<span>const</span> STATUS_DELETED = 0<span>;
</span><span>const</span> STATUS_ACTIVE = 10<span>;
</span><span>public</span> <span>static</span> <span>function</span> getZhStatus(<span>$status</span>=<span>false</span><span>){
    </span><span>$status_array</span>=<span> [
        </span>''=>'请选择',<span>
        self</span>::STATUS_DELETED=>'禁止',<span>
        self</span>::STATUS_ACTIVE=>'正常'<span>
    ];
    </span><span>return</span> <span>$status</span>==<span>false</span>?<span>$status_array</span>:ArrayHelper::getValue(<span>$status_array</span>,<span>$status</span>,'未知'<span>);
} 
</span><span>//</span><span>Gridview中</span>
<span>[ 
    </span>'attribute' => 'status',
    'filter'=>Html::activeDropDownList(<span>$searchModel</span>,'status',User::getZhStatus(),['class' => 'form-control ']),
    'value'=><span>function</span>(<span>$data</span><span>){
        </span><span>return</span> User::getZhStatus(<span>$data</span>-><span>status);
    }</span>,<span>
]</span>,   
Copy after login

5、格式化时间,有好几种方法:

方法一:类似上面的定义回调函数

<span>[
    </span>'attribute'=>'created_at',
    'value'=><span>function</span>(<span>$data</span><span>){
        </span><span>return</span> <span>date</span>('Y-m-d',<span>$data</span>-><span>created_at);   
   }</span>,<span>
]</span>
Copy after login

方法二:用Gridview自带的format配置

<span>[
    </span>'attribute'=>'created_at',
    'format'=>['date','php:Y-m-d'],
    'value'=>'created_at',<span>
]</span>,
Copy after login

方法三:首先在config中配置好你的时间格式,否则会是英文格式的,然后再在Gridview中处理。

<span>//</span><span>在common/config/main.php中定义自己的时间、金钱等的格式</span>
'components' =><span> [
    </span>'formatter' =><span> [
        </span>'dateFormat' => 'yyyy-MM-dd',
        'datetimeFormat' => 'yyyy-MM-dd HH:mm:ss',
        'decimalSeparator' => ',',
        'thousandSeparator' => ' ',
        'currencyCode' => 'CNY',<span>
    ]</span>,<span>
]</span>,
Copy after login

这里用到了快速写的一种方式:“attribute:format:label”(属性:格式:标签)这种格式,详情点击这里的api文档。所以我们这样就可以了:(如果定义了上方,则方法二可以直接'format'=>'date'即可以正确显示)

'created_at:date',
Copy after login

6、显示超链接或图片,都是用的回调函数的方法,这里以超链接为例,注意format需要为'raw’,不对结果做任何格式化处理,具体的格式化方面可以点这里看看。

<span>[ 
    </span>'attribute'=>'id',
    'value'=><span>function</span>(<span>$model</span>, <span>$key</span>, <span>$index</span>, <span>$column</span><span>){
        </span><span>return</span> Html::a(<span>$model</span>->id,['user/view','id'=><span>$model</span>->id],['class' => 'profile-link','target'=>'_blank'<span>]);
    }</span>,
    'format' => 'raw',<span>
]</span>,
Copy after login

7、关联表单显示,这个地方直接看指南吧,点这里看,总之就是如果管理表单设置好后,直接用类似order.name这种就可以直接显示使用,如果想要检索排序,则需要在searchModel的rulers规则方法和attributes属性方法中将此字段写入,在search方法中添加andFilterWhere的检索,以及用$query->joinWith关联字段,$dataProvider->sort->attributes[]添加排序等。

8、自定义Action Column按钮,

<span>[
    </span>'class' => 'yii\grid\ActionColumn',
    'header'=>'操作',
    'headerOptions'=>['width'=>'120'],
    'template' => '{view} {update} {delete} {forbid} ',
    'buttons'=><span>[
        </span>'forbid'=><span>function</span>(<span>$url</span>,<span>$model</span><span>){
            </span><span>return</span> Html::<span>a('<i class="glyphicon glyphicon-remove-circle"></i>',['user/forbid','id'=>$model->id]);     
        }
    ]</span>,<span>
]</span>
Copy after login

 以上是Yii2自带的Gridview的用法。再说下kartik-v/yii2-grid,官方文档及demo讲的比较全了,它比原生的多了几个列的形式,例如Editable Column(可编辑)、Radio Column(单选框)等,还多了一些其它功能,例如滚动时可以固定标题栏方便查看、可以总计、导出svn,excel等格式。这里稍微说下:

一开始安装完成后可能会报错pdf错误,因为这些关联的还没有安装,可以按照提示安装也可以先配置'export'=>false来取消导出功能,下面导出时会详细配置。

1、整体结构如下图:Yii2的相关学习记录,Gridview小部件使用及kartik-v/yii2-grid扩展(五),yii2gridview_PHP教程

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Where can I view the records of things I have purchased on Pinduoduo? How to view the records of purchased products? Where can I view the records of things I have purchased on Pinduoduo? How to view the records of purchased products? Mar 12, 2024 pm 07:20 PM

Pinduoduo software provides a lot of good products, you can buy them anytime and anywhere, and the quality of each product is strictly controlled, every product is genuine, and there are many preferential shopping discounts, allowing everyone to shop online Simply can not stop. Enter your mobile phone number to log in online, add multiple delivery addresses and contact information online, and check the latest logistics trends at any time. Product sections of different categories are open, search and swipe up and down to purchase and place orders, and experience convenience without leaving home. With the online shopping service, you can also view all purchase records, including the goods you have purchased, and receive dozens of shopping red envelopes and coupons for free. Now the editor has provided Pinduoduo users with a detailed online way to view purchased product records. method. 1. Open your phone and click on the Pinduoduo icon.

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Extensions and third-party modules for PHP functions Extensions and third-party modules for PHP functions Apr 13, 2024 pm 02:12 PM

To extend PHP function functionality, you can use extensions and third-party modules. Extensions provide additional functions and classes that can be installed and enabled through the pecl package manager. Third-party modules provide specific functionality and can be installed through the Composer package manager. Practical examples include using extensions to parse complex JSON data and using modules to validate data.

Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Mar 10, 2024 pm 04:34 PM

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

See all articles