Use Has Many Relations with Yii2 GridView

In Yii2 it is very easy to display has many relations for an ActiveRecord with the GridView. This tutorial is aimed to explain how easy it is to display your has many relations with Yii2 GridView in your Yii2 application.

For this tutorial I uses two model classes, User and Post. Here is the table structure for my models.

Then I created the model class using the yii2 gii code generator. In the User model class I had defined relation to Post model as follows

This relation defines that User is having a has many relation to Post based on the userID attribute of Post and id attribute of User.

Now we have the relation defined in the model and we are good to use it in the GridView. To show the posts for a given User I have created a new action named ‘posts’ in the UserController with an argument ‘$userID‘.

First we are loading the ActiveRecord for the user with the given $userID. Then as usual we are passing that ActiveRecord to the view file ‘posts’.

Now add the following lines to the posts view file.

Here we can see we are generating an ActiveDataProvider with its ‘query’ argument populated with the relation. This is all what we have to do to get all the posts for the given User and generate the ActiveDataProvider to populate the GridView with the relation.

Here is the resulting GridView

Let me know if you are having any queries regarding the tutorial. Happy coding.

Install & Using Google API in Yii2 using Composer

Many of us are still going in the process of learning Yii2 and how to use composer with Yii2 to include packages. Today I am explaining about how to install and use Google API in Yii2 using Composer.

Using Composer may seems to be confusing in the beginning, but in reality its not. Composer really makes the library management and dependency checking not at all a headache for the developer.

Lets start with the Tutorial on installing Google API using Composer and using it in your Yii2 Application. First of all we have to install the Yii2 Application using composer. For those who are new you can see the tutorial on installing Yii2 using composer here.

Once your Yii2 Application is installed, you can install the Google API library for PHP using composer by editing the composer.json file in the root folder of your Yii2 application.

You have to modify the composer.json file and add “google/apiclient”: “1.0.*@beta” in the require block. Once you have saved the file you have to open your composer console and run the command composer update. This command will update all the exisiting libraries and also install the latest Google API library in your Yii2 project. You can verify by going into the vendor folder in your root folder and you will see a folder ‘google’ which consists all the library files for Google API.

Now you have the library files within your project and we can start using it in your Yii2 Project. All the libraries installed via Composer is automatically loaded in your Yii2 Application. So there is no need to include new library in your action.

You can simply create objects of your library classes as usual. Since Yii2 is using namespaces you have to added ‘’ before the class name. That is the only change in Yii2 while using a thrid party library.

On a special note I noticed most of the class names given in the Google API documentation is using old class names. Google havn’t updated the official documentation to use the new class name. So do not get panic if you see Class not found error while you use code from the Google API documentation. You can check the new class names in the source file inside vendorgoogleapiclientsrcGoogle folder. The new class names looks similar to the old name. but each words are now separated by underscore.

is now

Hope this article helps you in inegrating Google API in your Yii2 Application. If you are having any queries just let me know via comments.

Install Yii2 Application Tutorial

In my previous article I explain about some of the major changes in Yii2 Framework. In this article I will guide you to install and setup the configuration web application using Yii2 framework.

One of the new feature in Yii2 is the introduction of Composer.

Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries your project needs and it will install them in your project for you.

We can install Yii2 framework and application using composer. Using composer is very easy and I insist those who havn’t used composer should start using it. Though if you are not intending to use composer you can download Yii2 and install it the same way as in Yii1. I will first explain how to install Yii2 using composer and then the normal download.

Install Yii2 using composer

You need to install Composer inorder to user composer. If you are on Linux or Mac you can install it by executing the following code

In Windows you can download the executable installer here. Download and install it. When you install you can choose to add menu item to the right click menu.

With Composer installed, you can install Yii by running the following command under a Web-accessible folder:

The above command installs Yii in a directory named basic.

Tip: If you want to install the latest development version of Yii, you may use the following command, 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 two steps:

  1. Download the archive file from Yii 2 with basic application template or Yii 2 with advanced application template.
  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):


Verifying the Installation

After installation, you can use your browser to access the installed Yii application with the following URL:

Install Yii2 Application
Install Yii2 Application


You can check if the minimum requirements are met using one of the following approaches:

  • Use a browser to access the URL http://localhost/basic/requirements.php


Introduction to Yii2 Framework

What is Yii?

Yii is a high performance, component-based PHP framework for rapidly developing modern Web applications. The name Yii (pronounced Yee or [ji:]) means “simple and evolutionary” in Chinese. It can also be thought of as an acronym for Yes It Is! – Yii PHP Framework 

What is Yii2?

Yii currently has two major versions available: 1.1 and 2.0. Version 1.1 is the old generation and is now in maintenance mode. Version 2.0 is a complete rewrite of Yii, adopting the latest technologies and protocols, including Composer, PSR, namespaces, traits, and so forth.

Hoping you read the above questions and answers let say Welcome to Yii2 Framework. Yii2 was under development for more than a year. As it is mentioned in official documentation, Yii2 is a complete rewrite of Yii1.1. That’s a big change from the developer point of view.

What are the major changes in Yii2?

PHP Version

One of the basic and most important changes in Yii2 is Yii 2.0 requires PHP 5.4.0 or above. Yii2 is built using most of latest features provided in PHP release version 5.4.0.  Make sure your server is running PHP version 5.4.0 or above before choosing Yii2.

Introduction of Namespaces

From PHP version 5.3.0, Namespaces were introduced in PHP programming. Due to the large number of libraries for PHP, the chances of name collision in different libraries became a real problem. Namespaces will help us to remove such problems. Namespaces are just like a folder which groups the files for a library.

Yii2 and Namespaces

Yii2 is built completely using namespaces. So we have to be familiar with using namespace in PHP programming inorder work with Yii2. Here is good tutorial for how to use namespaces in PHP. Once you are ready to work with namespaces you are almost good to start development in Yii2 framework.

Integration with Bootstrap

Like the close integration with jQuery in Yii 1.1, Yii 2 is having a close integration with Bootstrap HTML Framework. Infact all the widgets are modified so that we can customize the html properties of those widgets inorder to match the bootstrap structure. This will be very useful for modern web application development because most of the designs are now based on bootstrap html framework.

Yii2 Basic and Yii2 Advance

Yii2 framework is available in two templates, first one is basic and the other is advanced. Usually most of the projects will require only the basic template unless you really want to use advanced template. Advanced template provide multiple tires of application with individual application files sharing some common configuration. Basically the advanced template will help to create multiple application with sharing some common config such as db configuration. This helps us to create and application for frontend and a separate application for the backend. This is not required for most of the projects.

Structure of Yii 2 Framwork Fles

Unlike with Yii 1, standard installations of Yii 2 results in both the framework and an application skeleton being downloaded and installed. The core framework files are stored in the vendors folder.

Thats all for now. I will be writing more article on how to install amd write hello world application in Yii2 framework soon. So stay followed via Facebook, Twitter and Google

Native Form Validation with Yii in Bootstrap Style

When you are working with Yii and Bootstrap you will see many hurdles in doing several things in Yii in the native way. One of the main such issue is the form validation. Bootstrap is having a different HTML markup from that of the default Yii form. But as always Yii can be customized to match Bootstrap’s structure. So I thought I will write up an article explaining how to easily work with native form validation in Yii with Bootstrap form.

Yii Form Validation in Bootstrap Style
Yii Form Validation in Bootstrap Style

First of all lets see the difference in the form markup of Yii and Bootsrap. Here is the Yii style.

Here is the Bootstap style

This change can be easily achieved by changing the view file of the form itself to match the Bootstrap markup structure.

But when the form is submitted and there are some validation error or success, the structure of the markup is a bit altered by Yii with its pre configured settings. Lets look at a field with a validation error.

You can see a CSS class error is attached to the label and the input field. If the validation is success then the class is success. And a new div with class errorMessage is displayed after the input field with the details of error.

Lets look at how a Bootstrap form field will look with a validation error message.

Here you can see a CSS class has-error is attached to the wrapper div with class form-group. If the validation is success then the class should be has-success. And the error message block is having CSS class help-block which is different from the native Yii class errorMessage. How can we generate such markup after the validation in Yii? Its very easy, just follow the instructions below.

The only thing we need to worry is about attaching a CSS class has-error to the wrapper div of the field. For this we just have add a one line of PHP code in the view file of the form.

You may have noticed the php code appended to the div class=”form-group” line,

This piece of code will check whether that particular field is having any validation error. If there is any error it will attach the has-error CSS class to that div. This piece of code should be given for all the fields in the form with the correct attribute name password to the hasErrors() function of the model instance. So the first part is done. Next is the error message section.

The CSS class attached with the error message section is a property of the CActiveForm widget. Inorder to change that we have to specify that property along with the CActiveForm widget. The name of the property associated with this is errorMessageCssClass. By specifying that property as help-block in the widget configuration will do the magic.

That’s all, your Bootstrap friendly Yii form validation is completed. Stay tuned for more Yii tips. Meanwhile I am writing about how to handle AJAX validation with Yii in Bootstrap style.

Using Filters in Yii CGridView with Relations

CGridView in Yii is having filters by default for easily searching the contents in the grid. This default filters will work only with the attributes in the model. Most of the time we need to show attributes from related models in the gird view. By default there wont be any filter text boxes for those columns. It is very easy to apply the inbuilt filtering technique to the related attributes in CGridView. This article will help you to use filters in Yii CGridView with Relations and related attributes.

I am explaining the process with an simple example and you can see the code genereated by Yii by deafult and the change I have made to apply the filters to the relations attributes.

In this example I am using Post and User table with the following structure. Post table is having a relation to User with name userID.

Once the model is generated with the gii tool, you need to define the relation in the Post model. This can be done with the following edit.

This edit will tell the Post model that there is a relation to User model with the attribute userID in post model and the primary key of User model. We have named  the relation as author, Now we can use author attribute for any object of the Post model to access the user details of the that particular post.

Now the view part, the following is the normal code for CGridView generated with the CRUD generator of Yii. I have just added to the columns array to show the email of the user of the post.



This view will render a CGridView as follows with a column showing the email of the user for each Posts. But there wont be any text box for filtering that column like other columns.


No Filters on Relation

We can add the filter for the related attribute on the model relation with some simple modification.  First of all we need to create a manual attribute in the Post model for using with the filter input text field. So I have declared a member variable $authorEmail in the Post model as given in the below snippet. After that we need to define the the rules for that attribute. Since this attribute is not having any other rules I have added the save rule to the attribute.

Then I have modified the search function in the Post model to define the logic needed for the filtering. For this I have modified the CDbCriteria object used in the search function. I have added the relation to the criteria with the with property. Then added a search condition for the with the authorEmail attributes value. That’s all needed in the Model. Now there is a small change required in the view file also.

In the view file , modify the columns array for the CGridView. Add an array for showing the author email and mention the filter as follows.

Here is the resulting CGridView with filtering on the related attribute.

Filters on CGridView with Relation

Hope this tutorial to implement filtering on CGridView with relations and related attributes in Yii. Please comment if you are having any doubts.

Yii Framework 2.0 Preview Rleased

Yii  development team has released the first preview of Yii Framework 2.0. The code is available at at GitHub. Development of version 2.0 has been started 2 year ago and the complete code has been rewritten.

Yii 2.0 is still under heavy development, so it is not yet able to use for production. Yii was the most popular framework on 2012.

You may keep an eye on the following Yii 2 resources: