How do I use built-in Yii widgets (e.g., GridView, ListView, ActiveForm)?
Jul 24, 2025 am 01:00 AMIn the Yii framework, GridView, ListView, and ActiveForm are important components for building page elements. 1. GridView is used to display table data, supports pagination, sorting and filtering, configure columns and render tables through dataProvider and columns; 2. ListView is suitable for flexible layout list display, use itemView to customize the display of each record, and control the overall structure through layout; 3. ActiveForm is used to create model binding forms, automatically handle verification and error prompts, and supports multiple input types and layout adjustments. Mastering these widgets can greatly improve development efficiency and enable personalized requirements through configuration.
In the Yii framework, built-in widgets (such as GridView, ListView, and ActiveForm) are very practical tools that can help you quickly build common page elements. They have been packaged with many commonly used functions and are relatively simple to use.
Use GridView to display data tables
GridView is one of the most commonly used components to display database query results. It supports pagination, sorting, filtering and other functions, and is very suitable for use in the background management interface.
The basic usage is as follows:
- Get the data provider in the controller (usually ActiveDataProvider)
- Render tables using
GridView::widget()
method in view
use yii\grid\GridView; echo GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], // Automatic numbering column 'id', 'name', 'email:email', ['class' => 'yii\grid\ActionColumn'], // Operation column (View/Edit/Delete) ], ]);
hint:
-
filterModel
can be omitted if you do not need search function - If you want to customize the display content of a column, you can use
value
attribute or closure function - The default style is Bootstrap style, you can modify the template or class name through configuration
Use ListView to display list content
ListView is suitable for situations where more flexible layout is required, such as blog post lists, product displays, etc. It is not fixed in table form like GridView, but rather prefers free typography.
The basic structure is as follows:
use yii\widgets\ListView; echo ListView::widget([ 'dataProvider' => $dataProvider, 'itemView' => '_item', // Point to a separate view file for rendering each record 'layout' => "{items}\n{pager}", 'pager' => [ 'firstPageLabel' => 'Home', 'lastPageLabel' => 'last page', ], ]);
Some points to note:
-
_item
view files usually receive a$model
and$key
parameters - You can use
viewParams
to add extra parameters to pass into item view -
{summary}
in the layout can display the data range of the current page, but sometimes it will appear redundant and can be removed according to your needs.
Build forms using ActiveForm
ActiveForm is the best choice for handling model-related forms. It automatically binds model properties, displays error messages, and integrates seamlessly with Yii's verification mechanism.
Basic writing method:
use yii\widgets\ActiveForm; $form = ActiveForm::begin(); echo $form->field($model, 'username'); echo $form->field($model, 'email')->input('email'); echo $form->field($model, 'password')->passwordInput(); echo \yii\helpers\Html::submitButton('Submit', ['class' => 'btn btn-primary']); ActiveForm::end();
Some practical tips:
- The form field will display label and error messages by default, which can be controlled through
label(false)
orerrorOptions
- If you want to put multiple fields in the same line, you can use
ActiveForm::field($model, 'xxx')->inline(true)
- Supports multiple input types, such as
dropDownList
,checkboxList
,fileInput
, etc.
Basically that's it. These widgets are very powerful, but they are also easy to ignore some details in actual development, such as field naming rules, data format conversion, and coordination with front-end JS. However, as long as you master the basic usage, the rest can be gradually improved by checking documents and debugging.
The above is the detailed content of How do I use built-in Yii widgets (e.g., GridView, ListView, ActiveForm)?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

YiiassetbundlesorganizeandmanagewebassetslikeCSS,JavaScript,andimagesinaYiiapplication.1.Theysimplifydependencymanagement,ensuringcorrectloadorder.2.Theypreventduplicateassetinclusion.3.Theyenableenvironment-specifichandlingsuchasminification.4.Theyp

In the MVC framework, the mechanism for the controller to render views is based on the naming convention and allows explicit overwriting. If redirection is not explicitly indicated, the controller will automatically find a view file with the same name as the action for rendering. 1. Make sure that the view file exists and is named correctly. For example, the view path corresponding to the action show of the controller PostsController should be views/posts/show.html.erb or Views/Posts/Show.cshtml; 2. Use explicit rendering to specify different templates, such as render'custom_template' in Rails and view('posts.custom_template') in Laravel

When saving data to the database in the Yii framework, it is mainly implemented through the ActiveRecord model. 1. Creating a new record requires instantiation of the model, loading the data and verifying it before saving; 2. Updating the record requires querying the existing data before assignment; 3. When using the load() method for batch assignment, security attributes must be marked in rules(); 4. When saving associated data, transactions should be used to ensure consistency. The specific steps include: instantiating the model and filling the data with load(), calling validate() verification, and finally performing save() persistence; when updating, first obtaining records and then assigning values; when sensitive fields are involved, massassignment should be restricted; when saving the associated model, beginTran should be combined

TocreateabasicrouteinYii,firstsetupacontrollerbyplacingitinthecontrollersdirectorywithpropernamingandclassdefinitionextendingyii\web\Controller.1)Createanactionwithinthecontrollerbydefiningapublicmethodstartingwith"action".2)ConfigureURLstr

The method of creating custom operations in Yii is to define a common method starting with an action in the controller, optionally accept parameters; then process data, render views, or return JSON as needed; and finally ensure security through access control. The specific steps include: 1. Create a method prefixed with action; 2. Set the method to public; 3. Can receive URL parameters; 4. Process data such as querying the model, processing POST requests, redirecting, etc.; 5. Use AccessControl or manually checking permissions to restrict access. For example, actionProfile($id) can be accessed via /site/profile?id=123 and renders the user profile page. The best practice is

AYiidevelopercraftswebapplicationsusingtheYiiframework,requiringskillsinPHP,Yii-specificknowledge,andwebdevelopmentlifecyclemanagement.Keyresponsibilitiesinclude:1)Writingefficientcodetooptimizeperformance,2)Prioritizingsecuritytoprotectapplications,

AYiideveloper'skeyresponsibilitiesincludedesigningandimplementingfeatures,ensuringapplicationsecurity,andoptimizingperformance.QualificationsneededareastronggraspofPHP,experiencewithfront-endtechnologies,databasemanagementskills,andproblem-solvingabi

TouseActiveRecordinYiieffectively,youcreateamodelclassforeachtableandinteractwiththedatabaseusingobject-orientedmethods.First,defineamodelclassextendingyii\db\ActiveRecordandspecifythecorrespondingtablenameviatableName().Youcangeneratemodelsautomatic
