Select2 library solution in Yii2 part 1 – introduction

For those of you who do not know the Select2 library is a Javascript / JQuery replacement for select boxes. Although there are a few options to choose from in terms of using the Select2 field the configuration I will be looking at will be the multi select configuration.

The multi select configuration is useful for allowing the user to select things that require multiple choices, a typical example of this could be Tags but at a deeper level the multi select configuration is useful for allowing the user to create many to many relationships between models on forms.

An example Select2 field is shown below, allowing the selection of countries on a form …

Select2 Library

The above Select2 field could be on a add / edit person form allowing the many to many relation between People and Countries.

The solution I am providing in this article is all about saving and retrieving the Select2 data in a way that will streamline the process so a Select2 field can be attached to any of your forms within your web software application and it will just work out of the box.

The front-end part of the Select2 field is solved already as you can use the following Yii2 plugin for that …

The above plugin displays the Select2 field on your Yii2 web forms. The above plugin passes the Select2 field data in the POST as an array. It is what to do with that data in a consistent and streamlined way that this article I am writing covers.

There are many ways the data could be handled for example the data could be JSON encoded and stored in a column in the database table then JSON decoded and displayed on the form when retrieving. Another way would be to have relationship tables for each relationship between models and store the data that way.

The way I have chosen is more like the later except that I do not have relationship tables for each relationship, I simply have 1 central Select2 relationship table that handles all Select2 relationships across the whole web software application.

What is the purpose of all this?

Most programmers would just use the Krajee Select2 plugin (link above) and leave it at that in terms of abstraction. The programmer would manually write the save / retrieve code specific to each instance of the Select2 plugin most likely in the Controller. The way I am using the Select2 plugin is to have methods that handle all of this.

If I want to use the Select2 plugin field in any of my forms, with just a few method calls the Select2 plugin field will be up and running, saving / retrieving data for any field / model. The way I am doing this also integrates better with Yii2 and makes use of the Yii2 relations to fetch associated Select2 data, so this way integrates deeper with Yii2.

Allowing the user to select items on a form and have the software application save those items as a many to many relationship is not always an easy task. This method takes away some of the complexity of that, so that I can have user defined many to many relationships between models / database tables.

Creating a Utility class in Yii2

A Utility class is a place to put all common methods that will often need to be re-used in a web software application. During a previous article it was demonstrated how to create a master Model and Controller …

Create a master Model and Controller in Yii2

The master Model and Controller are good places to store a lot of re-used methods that relate to Models and Controllers. Sometimes though methods may not relate to Models and Controllers and need to re-used elsewhere in the web software application. This is where the Utility is useful. It is important to note that the Utility class is not designed to be instantiated as an object and should contain “static” methods that can act independently.

To create a Utility class create a new file called “Utility.php” and place it inside your “components” folder. Inside the “Utility.php” file place the following code …

The above code shows a blank Utility class ready to be populated with re-usable methods. Below shows a Utility class with an example method …

Notice how the method is defined as “static”, this is because the Utility class will not be instantiated into an object when used in the web software application. The method within the Utlity class can be used in the web software application as follows …

Include the Utility class into the file the Utility class will be used in …

Now call the desired Utility class method …

I personally create a Utility class in all my web software applications and find it a useful place to store re-usable methods that do not relate to Models and Controllers. Re-usable methods that do relate to Models and Controllers I store in the master Model and Controller, re-usable methods that do not relate to Models and Controllers I store in the Utility class.

My new way and correct way of coding Controllers

I have been using frameworks for a number of years with the Yii2 framework being my framework of choice at the present time. When it comes to defining how an application should be structured in terms of Controllers and their methods i was always one to put methods wherever I felt it made sense to put one.

For example my UserController would consist of index, view, create, update, delete, login, logout, lostpassword methods. This made sense at the time. Any action methods that relate to user functionality could go in the UserController. However all the time I was doing this I was aware that some developers and articles on the internet point to the fact that Controllers should only have certain methods within them, namely the standard CRUD methods and nothing else.

So one day I decided to follow that train of thought and start writing my controllers to only have the following methods, index, view, create, update, delete. These methods serve the following purpose …

  1. Index – view all records in a grid view
  2. View – view single record in a detail view
  3. Create – create form and submission code for single record
  4. Update – update form and submission code for single record
  5. Delete – delete a single record

I am aware that I could even get rid of the index and just handle the “view all” and “view single record” through the single Controller method of “view” by checking to see whether an ID parameter has been provided to the method however I thought I would keep them separate.

I am quite pleased by how the new structure has turned out in that it makes my Controller less bulky with code and it gives a much more structured neat and clean feeling to my code and software application.

So you might be wondering what happened to my UserController and the extra methods that where described earlier i.e. login, logout, lostpassword etc. Well using the new system they can be broken down as follows …


  1. Index – view all users in the system
  2. View – view single users details
  3. Create – create a user
  4. Update – update a user
  5. Delete – delete a user


  1. Create – log the user in
  2. Delete – log the user out


  1. Create – send the user a link to change the users password
  2. Update – process the clicked link and change the users password

So it is possible to do this, basically the Controllers within the software application now take more definition by having the Controllers named after the type of event the user is wanting to make within the software application and placing less emphasis on the Controllers methods providing the definition. I really like my new way of coding my Controllers and I intent to stick to this method for the foreseeable future.

Yii 1 to Yii 2 differences and enhancements part 2

I wrote about Yii 1 to Yii 2 differences and enhancements some time ago and now I am going to carry on from that article to discuss more differences and enhancements I have found since moving to the Yii 2 framework from the Yii 1 framework …


In Yii 1 relationships where defined in the relations method. The relations methods is a method that returns an array of data specifying the relations the model has and data relevant to those relations.

The array is used to create the relations as model properties.

In Yii 2 relations are defined in “magic methods” as follows …

I prefer the Yii 2 way of using the magic methods because it allows you to write additional code in the method that defines the relation. This could come in handy in unique scenarios where custom code is needed to handle the relationship. I also think the Yii 2 method is more in line with the PHP language as a whole than the Yii 1 way of defining relations.


Yii 2 has more validation options than Yii 1 and has introduced further options the validations themselves which make creating these sorts of validations a lot more streamlined. Both Yii 1 and Yii 2 validations are defined as arrays. With the added bonus of the later version of PHP language in the Yii 2 framework the arrays in Yii 2 look more streamlined.

For example rather than this …

They are like this …

They look much better.

Yii 2 introduces the new “when” option and thanks to PHP callback functions we can now write a validation like so …

This will only require the “name” attribute when the “complete” attribute is true. In Yii 1 this validation would have had to have been written as a custom validation method which is a real pain.

That is it for now, another update to come soon.

Yii 1 to Yii 2 differences and enhancements part 1

A number of months ago I made the switch to the Yii 2 framework from the Yii 1 framework. My intent in this post is to outline some of the differences and enhancements I have found from switching to the latest Yii framework.

A framework is a set of code written to help in common programming tasks for example handling data, creating forms and data tables etc.

When I first started programming I did not use a framework as I did not understand the benefits properly of using a framework. The above tasks would have been written from scratch and would have essentially duplicated code that was already out there for solving these common tasks.

When I first started using a framework it made my life much easier and the end product was of a better quality to time ratio than not using a framework. The same quality could be achieved without the use of a framework but would take longer and the programmer would be essentially writing code for common problems that already have a solution.

I would also like to mention that frameworks provide a consistent structure to the code that a programmer writes so that one way of solving a problem at one end of the code would be the same way the problem was solved at another end of the code. This makes it easier for other programmers to understand the code base.

After using the Yii 2 framework here are some of the differences and enhancements that I have found …

User Identity

In Yii 1 a “User identity” is a class that extends “UserIdentity” and handles the authentication and identity of the logged in user. I would create a class that extends “UserIdentity” create some predefined methods and let Yii handle the authentication.

In Yii 2 a similar approach is used except I do not create an extended “UserIdentity” class but instead I “implement” “IdentityInterface” in my User class. In Yii 1 I would have a “UserIdentity” class and a “User” class, in Yii 2 I just have the “User” class. Similar to Yii 1 I create some predefined methods in my “User” class and let Yii handle the authentication.

Active Record

Active Record has some key differences going from the Yii 1 framework to the Yii 2 framework. In Yii 1 Active Record was used like so …

Or …

Or …

In Yii 2 Active Record is used as follows …

Or …

Or …

Basically in Yii 1 there where a lot of methods that where created for specific purposes “findAll”, “findByPK”, “findByAttributes”, “findAllByAttributes”, “deleteByPK”, “deleteAllByAttributes” etc.

Yii 2 can do all of the above purposes but the syntax is much more flexible in that it does not have methods for each purpose but flexible syntax that can be used for flexible purposes.

Also note how in Yii 1 I used array() and in Yii 2 I used []. That is because at the time of Yii 1 array() was the PHP syntax used for creating arrays and at the time of Yii 2 [] could also be used to create arrays. Not really a Yii issue but still the array syntax looks better in the more modern version of PHP.


Due to the Yii 2 framework being written at a time when the version of PHP was later and more modern the Yii 2 framework has made extensive use of the “Use” statement and “Namespaces”. Yii 1 did not make use of these at all probably because they where not implemented in PHP at the time the Yii 1 framework was written.

Nevertheless I feel the “Use” statement and “Namespaces” give the code a more professional feel and it means that the code is only made use of when the code is needed.

I will be updating the blog with more articles on Yii 1 to Yii 2 differences and enhancements as I go a long. I already have plenty of differences lined up but I will be saving them for the next article in this series.