Yii2 Framework

Yii provides a set of widgets that can be used to display data.While the DetailView widget can be used to display data for a single record,ListView and GridView can be used to display a list or table of data recordsproviding features like pagination, sorting and filtering.

  1. Yii2 Framework Installation
  2. Yii2 Framework Download For Windows
  3. Yii Framework Download
  4. Yii2 Framework Tutorials
  5. Yii2 Tutorial

DetailView ¶

Yii2 GridView on steroids. A module with various enhancements to one of the most used Yii widget groups. Contains new additional Grid Columns with enhanced settings for Yii Framework 2.0. The widget also incorporates various Bootstrap 3.x styling options. Yii provides a highly customizable and extensible framework. With the help of this framework, you can easily log various types of messages. To log a message, you should call one of the following methods −. Standard installations of Yii result in both the framework and a project template being downloaded and installed. A project template is a working Yii project implementing some basic features, such as login, contact form, etc. Its code is organized in a recommended way. Therefore, it can serve as a good starting point for your projects.

The DetailView widget displays the details of a single data model.

It 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 or subclass of yiibaseModel such as an active record or an associative array.

DetailView uses the $attributes property to determine which model attributes should be displayed and how theyshould be formatted. See the formatter section for available formatting options.

A typical usage of DetailView is as follows:

Remember that unlike yiiwidgetsGridView which processes a set of models,DetailView processes just one. So most of the time there is no need for using closure since$model is the only one model for display and available in view as a variable.

Cmake glut. However some cases can make using of closure useful. For example when visible is specified and you want to preventvalue calculations in case it evaluates to false:


ListView ¶

The ListView widget is used to display data from a data provider.Each data model is rendered using the specified view file.Since it provides features such as pagination, sorting and filtering out of the box, it is handy both to displayinformation to end user and to create data managing UI.

A typical usage is as follows:

The _post view file could contain the following:

In the view file above, the current data model is available as $model. Additionally the following variables are available:

  • $key: mixed, the key value associated with the data item.
  • $index: integer, the zero-based index of the data item in the items array returned by the data provider.
  • $widget: ListView, this widget instance.

If you need to pass additional data to each view, you can use the $viewParams propertyto pass key value pairs like the following:

These are then also available as variables in the view.

GridView ¶

Data grid or GridView is one of the most powerful Yii widgets. It is extremely useful if you need to quickly build the adminsection of the system. It takes data from a data provider and renders each row using a set of columnspresenting data in the form of a table.

Each row of the table represents the data of a single data item, and a column usually represents an attribute ofthe item (some columns may correspond to complex expressions of attributes or static text).

The minimal code needed to use GridView is as follows:

The above code first creates a data provider and then uses GridView to display every attribute in every row taken fromthe data provider. The displayed table is equipped with sorting and pagination functionality out of the box.

Grid columns ¶

Yii2 Framework

The columns of the grid table are configured in terms of yiigridColumn classes, which areconfigured in the columns property of GridView configuration.Depending on column type and settings these are able to present data differently.The default class is yiigridDataColumn, which represents a model attribute and can be sorted and filtered by.

Note that if the columns part of the configuration isn't specified,Yii tries to show all possible columns of the data provider's model.

Column classes ¶

Grid columns could be customized by using different column classes:

In addition to column classes provided by Yii that we'll review below, you can create your own column classes.

Each column class extends from yiigridColumn so that there are some common options you can set while configuringgrid columns.

  • header allows to set content for header row.
  • footer allows to set content for footer row.
  • visible defines if the column should be visible.
  • content allows you to pass a valid PHP callback that will return data for a row. The format is the following:

You may specify various container HTML options by passing arrays to:

Data column ¶

Data column is used for displaying and sorting data. It is the default column type so the specifying class could be omitted whenusing it.

The main setting of the data column is its format property. Its valuescorrespond to methods in the formatterapplication component that is Formatter by default:

In the above, text corresponds to yiii18nFormatter::asText(). The value of the column is passed as the firstargument. In the second column definition, date corresponds to yiii18nFormatter::asDate(). The value of thecolumn is, again, passed as the first argument while 'php:Y-m-d' is used as the second argument value.

For a list of available formatters see the section about Data Formatting.

For configuring data columns there is also a shortcut format which is described in theAPI documentation for columns.

Use filter and filterInputOptions tocontrol HTML for the filter input.

By default, column headers are rendered by yiidataSort::link(). It could be adjusted using yiigridColumn::$header.To change header text you should set yiigridDataColumn::$label like in the example above. By default the label will be populated from data model. For more details see yiigridDataColumn::getHeaderCellLabel().

Action column ¶

Action column displays action buttons such as update or delete for each row.

Available properties you can configure are:

  • controller is the ID of the controller that should handle the actions. If not set, it will use the currently activecontroller.
  • template defines the template used for composing each cell in the action column. Tokens enclosed within curly brackets aretreated as controller action IDs (also called button names in the context of action column). They will be replacedby the corresponding button rendering callbacks specified in buttons. For example, the token {view} will bereplaced by the result of the callback buttons['view']. If a callback cannot be found, the token will be replacedwith an empty string. The default tokens are {view} {update} {delete}.
  • buttons is an array of button rendering callbacks. The array keys are the button names (without curly brackets),and the values are the corresponding button rendering callbacks. The callbacks should use the following signature:

    In the code above, $url is the URL that the column creates for the button, $model is the model object beingrendered for the current row, and $key is the key of the model in the data provider array.

  • urlCreator is a callback that creates a button URL using the specified model information. The signature ofthe callback should be the same as that of yiigridActionColumn::createUrl(). If this property is not set,button URLs will be created using yiigridActionColumn::createUrl().
  • visibleButtons is an array of visibility conditions for each button.The array keys are the button names (without curly brackets), and the values are the boolean true/false or theanonymous function. When the button name is not specified in this array it will be shown by default.The callbacks must use the following signature:

    Or you can pass a boolean value:

Yii2 Framework Installation

Checkbox column ¶

Checkbox column displays a column of checkboxes.

To add a CheckboxColumn to the GridView, add it to the columns configuration as follows:

Users may click on the checkboxes to select rows of the grid. The selected rows may be obtained by calling the followingJavaScript code:

Serial column ¶

Serial column renders row numbers starting with 1 and going forward.

Usage is as simple as the following:

Sorting data ¶

Note: This section is under development.

Filtering data ¶

For filtering data, the GridView needs a model that represents the search criteria which isusually taken from the filter fields in the GridView table.A common practice when using active records is to create a search Model classthat provides needed functionality (it can be generated for you by Gii). This class defines the validationrules to show filter controls on the GridView table and to provide a search() method that will return the data provider with an adjusted query that processes the search criteria.

To add the search capability for the Post model, we can create a PostSearch model like the following example:

Yii2 Framework Download For Windows

Tip: See Query Builder and especially Filter Conditionsto learn how to build filtering query.

You can use this function in the controller to get the dataProvider for the GridView:

And in the view you then assign the $dataProvider and $searchModel to the GridView:

Separate filter form ¶

Most of the time using GridView header filters is enough, but in case you need a separate filter form,you can easily add it as well. You can create partial view _search.php with the following contents:

and include it in index.php view like so:

Note: if you use Gii to generate CRUD code, the separate filter form (_search.php) is generated by default,but is commented in index.php view. Uncomment it and it's ready to use!

Separate filter form is useful when you need to filter by fields, that are not displayed in GridViewor for special filtering conditions, like date range. For filtering by date range we can add non DB attributescreatedFrom and createdTo to the search model:

Extend query conditions in the search() method like so:

And add the representative fields to the filter form:

Working with model relations ¶

When displaying active records in a GridView you might encounter the case where you display values of relatedcolumns such as the post author's name instead of just his id.You do this by defining the attribute name in yiigridGridView::$columns as author.name when the Post modelhas a relation named author and the author model has an attribute name.The GridView will then display the name of the author but sorting and filtering are not enabled by default.You have to adjust the PostSearch model that has been introduced in the last section to add this functionality.

To enable sorting on a related column you have to join the related table and add the sorting ruleto the Sort component of the data provider:

Filtering also needs the joinWith call as above. You also need to define the searchable column in attributes and rules like this:

In search() you then just add another filter condition with:

Info: In the above we use the same string for the relation name and the table alias; however, when your alias and relation namediffer, you have to pay attention to where you use the alias and where you use the relation name.A simple rule for this is to use the alias in every place that is used to build the database query and therelation name in all other definitions such as attributes() and rules() etc.

For example, if you use the alias au for the author relation table, the joinWith statement looks like the following:

It is also possible to just call $query->joinWith(['author']); when the alias is defined in the relation definition.

The alias has to be used in the filter condition but the attribute name stays the same:

The same is true for the sorting definition:

Also, when specifying the defaultOrder for sorting, you need to use the relation nameinstead of the alias:

Info: For more information on joinWith and the queries performed in the background, check theactive record docs on joining with relations.

Using SQL views for filtering, sorting and displaying data ¶

There is also another approach that can be faster and more useful - SQL views. For example, if we need to show the gridviewwith users and their profiles, we can do so in this way:

Then you need to create the ActiveRecord that will be representing this view:

After that you can use this UserView active record with search models, without additional specification of sorting and filtering attributes.All attributes will be working out of the box. Note that this approach has several pros and cons:

  • you don't need to specify different sorting and filtering conditions. Everything works out of the box;
  • it can be much faster because of the data size, count of sql queries performed (for each relation you will not need any additional query);
  • since this is just a simple mapping UI on the sql view it lacks some domain logic that is in your entities, so if you have some methods like isActive,isDeleted or others that will influence the UI, you will need to duplicate them in this class too.

Multiple GridViews on one page ¶

You can use more than one GridView on a single page but some additional configuration is needed so thatthey do not interfere with each other.When using multiple instances of GridView you have to configure different parameter names forthe generated sort and pagination links so that each GridView has its own individual sorting and pagination.You do so by setting the sortParam and pageParamof the dataProvider's sort and paginationinstances.

Assume we want to list the Post and User models for which we have already prepared two data providersin $userProvider and $postProvider:

Using GridView with Pjax ¶

The Pjax widget allows you to update a certain section of apage instead of reloading the entire page. You can use it to update only theGridView content when using filters.

Pjax also works for the links inside the Pjax widget andfor the links specified by Pjax::$linkSelector.But this might be a problem for the links of an ActionColumn.To prevent this, add the HTML attribute data-pjax='0' to the links when you editthe ActionColumn::$buttons property.

GridView/ListView with Pjax in Gii ¶

Since 2.0.5, the CRUD generator of Gii has an option called$enablePjax that can be used via either web interface or command line.

Which generates a Pjax widget wrapping theGridView or ListView widgets.

Further reading ¶

  • Rendering Data in Yii 2 with GridView and ListView by Arno Slatius.

Found a typo or you think this page needs improvement?
Edit it on github !

Yii framework documentation

You can install Yii in two ways, using the Composer package manager or by downloading an archive file.The former is the preferred way, as it allows you to install new extensions or update Yii by simply running a single command.

Standard installations of Yii result in both the framework and a project template being downloaded and installed.A project template is a working Yii project implementing some basic features, such as login, contact form, etc.Its code is organized in a recommended way. Therefore, it can serve as a good starting point for your projects.

In this and the next few sections, we will describe how to install Yii with the so-called Basic Project Template andhow to implement new features on top of this template. Yii also provides another template calledthe Advanced Project Template which is better used in a team development environmentto develop applications with multiple tiers.

Info: The Basic Project Template is suitable for developing 90 percent of Web applications. It differs from the Advanced Project Template mainly in how their code is organized. If you are new to Yii, we strongly recommend you stick to the Basic Project Template for its simplicity yet sufficient functionalities.

Installing via Composer ¶

Installing Composer ¶

If you do not already have Composer installed, you may do so by following the instructions atgetcomposer.org. On Linux and Mac OS X, you'll run the following commands:


On Windows, you'll download and run Composer-Setup.exe.

Please refer to the Troubleshooting section of the Composer Documentationif you encounter any problems.If you are new to Composer, we also recommend to read at least the Basic usage sectionof the Composer documentation.

In this guide all composer commands assume you have installed composer globallyso that it is available as the composer command. If you are using the composer.phar in the local directory instead,you have to adjust the example commands accordingly.

If you had Composer already installed before, make sure you use an up to date version. You can update Composerby running composer self-update.

Note: During the installation of Yii, Composer will need to request a lot of information from the Github API.The number of requests depends on the number of dependencies your application has and may be bigger than theGithub API rate limit. If you hit this limit, Composer may ask for your Github login credentials to obtaina Github API access token. On fast connections you may hit this limit earlier than Composer can handle so werecommend to configure the access token before installing Yii.Please refer to the Composer documentation about Github API tokensfor instructions on how to do this.

Yii Framework Download

Installing Yii ¶

With Composer installed, you can install Yii application template by running the following commandunder a Web-accessible folder:

This will install the latest stable version of Yii application template in a directory named basic.You can choose a different directory name if you want.

Info: If the composer create-project command fails you may also refer to the Troubleshooting section of the Composer Documentationfor common errors. When you have fixed the error, you can resume the aborted installationby running composer update inside of the basic directory.

Tip: If you want to install the latest development version of Yii, you may use the following command instead,which adds a stability option:

Note that the development version of Yii should not be used for production as it may break your running code.

Installing from an Archive File ¶

Installing Yii from an archive file involves three steps:

  1. Download the archive file from yiiframework.com.
  2. Unpack the downloaded file to a Web-accessible folder.
  3. Modify the config/web.php file by entering a secret key for the cookieValidationKey configuration item(this is done automatically if you are installing Yii using Composer):

Other Installation Options ¶

Yii2 Framework Tutorials

The above installation instructions show how to install Yii, which also creates a basic Web application that works out of the box.This approach is a good starting point for most projects, either small or big. It is especially suitable if you juststart learning Yii.

But there are other installation options available:

  • If you only want to install the core framework and would like to build an entire application from scratch,you may follow the instructions as explained in Building Application from Scratch.
  • If you want to start with a more sophisticated application, better suited to team development environments,you may consider installing the Advanced Project Template.

Installing Assets ¶

Yii relies on Bower and/or NPM packages for the asset (CSS and JavaScript) libraries installation.It uses Composer to obtain these libraries, allowing PHP and CSS/JavaScript package versions to resolve at the same time.This can be achieved either by usage of asset-packagist.org or composer asset plugin.Please refer to Assets documentation for more details.

You may want to either manage your assets via native Bower/NPM client, use CDN or avoid assets installation entirely.In order to prevent assets installation via Composer, add the following lines to your 'composer.json':

Note: in case of bypassing asset installation via Composer, you are responsible for the assets installation and resolvingversion collisions. Be prepared for possible inconsistencies among asset files from different extensions.


Verifying the Installation ¶

After installation is done, either configure your web server (see next section) or use thebuilt-in PHP web server by running the followingconsole command while in the project root directory:

Note: By default the HTTP-server will listen to port 8080. However if that port is already in use or you wish to serve multiple applications this way, you might want to specify what port to use. Just add the --port argument:

You can use your browser to access the installed Yii application with the following URL:

You should see the above 'Congratulations!' page in your browser. If not, please check if your PHP installation satisfiesYii's requirements. You can check if the minimum requirements are met using one of the following approaches:

Yii2 Tutorial

  • Copy /requirements.php to /web/requirements.php and then use a browser to access it via http://localhost/requirements.php
  • Run the following commands:

You should configure your PHP installation so that it meets the minimum requirements of Yii. Most importantly, youshould have PHP 5.4 or above. Ideally latest PHP 7. You should also install the PDO PHP Extensionand a corresponding database driver (such as pdo_mysql for MySQL databases), if your application needs a database.

Configuring Web Servers ¶

Info: You may skip this subsection for now if you are just test driving Yii with no intention of deploying it to a production server.

The application installed according to the above instructions should work out of box with eitheran Apache HTTP server or an Nginx HTTP server, onWindows, Mac OS X, or Linux running PHP 5.4 or higher. Yii 2.0 is also compatible with facebook'sHHVM. However, there are some edge cases where HHVM behaves different than nativePHP, so you have to take some extra care when using HHVM.

On a production server, you may want to configure your Web server so that the application can be accessedvia the URL http://www.example.com/index.php instead of http://www.example.com/basic/web/index.php. Such configurationrequires pointing the document root of your Web server to the basic/web folder. You may alsowant to hide index.php from the URL, as described in the Routing and URL Creation section.In this subsection, you'll learn how to configure your Apache or Nginx server to achieve these goals.

Info: By setting basic/web as the document root, you also prevent end users from accessingyour private application code and sensitive data files that are stored in the sibling directoriesof basic/web. Denying access to those other folders is a security improvement.

Info: If your application will run in a shared hosting environment where you do not have permissionto modify its Web server configuration, you may still adjust the structure of your application for better security. Please refer tothe Shared Hosting Environment section for more details.

Info: If you are running your Yii application behind a reverse proxy, you might need to configureTrusted proxies and headers in the request component.

Recommended Apache Configuration ¶

Use the following configuration in Apache's httpd.conf file or within a virtual host configuration. Note that youshould replace path/to/basic/web with the actual path for basic/web.

Recommended Nginx Configuration ¶

To use Nginx, you should install PHP as an FPM SAPI.You may use the following Nginx configuration, replacing path/to/basic/web with the actual path for basic/web and mysite.test with the actual hostname to serve.

When using this configuration, you should also set cgi.fix_pathinfo=0 in the php.ini filein order to avoid many unnecessary system stat() calls.

Also note that when running an HTTPS server, you need to add fastcgi_param HTTPS on; so that Yiican properly detect if a connection is secure.

Recommended NGINX Unit Configuration ¶

You can run Yii-based apps using NGINX Unit with a PHP language module.Here is a sample configuration.

You can also set up your PHP environment or supply a custom php.ini in the same configuration.

IIS Configuration ¶

It's recommended to host the application in a virtual host (Web site) where document root points to path/to/app/web folder and that Web site is configured to run PHP. In that web folder you have to place a file named web.config i.e. path/to/app/web/web.config. Content of the file should be the following:

Also the following list of Microsoft's official resources could be useful in order to configure PHP on IIS:

Found a typo or you think this page needs improvement?
Edit it on github !