How to store array values in Yii model property

In some scenarios, we require to store multiple values in your class attribute of your Yii model. We usually use this for showing check boxes or multiple select in your Yii form.

Add new Rule for your field “arrayField” in your model:

Overwrite your model’s “savemethod and change the array value as serialized string to store this in your database table.

How to add new action link column for Yii CGridView

It is very simple to create custom columns in CGridView. While defining the columns, you have to define an array with specific values for the custom column. To create a column which points to another controller with ID parameter, use following code:

To add header for the column, modify the same array with an additional parameter for the header.

The entire widget for CGridView in view file will look like this:


How to make Yii form fields mandatory manually

When you generate the model and CRUD files, usually all rules in the model is generated automatically and you are not bothered about the rules. But if you want to manually make fields in a form mandatory, you have to write a simple rule in the model rules function – array. Suppose I am having username, email and password in my form and I want all fields to be mandatory. The rules function will be similar to the below code:

Note the last array in the rule, where the first element has all fields (separated by comma) in the form which are required. The second element in the array is the validation class, which is “required” in our case.

Change your Yii view directory name for your controller

This article will assist you to use custom folder names rather than generating folder names for your controller. Suppose you have a model named: “MySample“, your generated controller name will be: “MySampleController”; your view folder name will be “views/mySample“. If you want to change your view name from views/mySample to views/sample, add the below function to your controller and change the folder name.

As simple as that 🙂