Home » YII CRUD

Yii CRUD

Yii provides a gii tool which is a code generator tool. It gives you the generated code for CRUD. We’ll learn how to generate CRUD with gii.

A simple example is shown here to generate a crud. We have named the Yii2 folder as crud. And our table name is employees.

Step 1 Open Gii

In the browser, type the following, http://localhost/crud/frontend/web/index.php?r=gii

YII 2 Curd 1

Step 2 Generate Model

YII 2 Curd 2

Look at the above snapshot, enter the table name which is employees in our case. Employees model class will be generated. Scroll down the page and click on Preview button.

YII 2 Curd 3

Look at the above snpashot, click on Generate button to generate the code.

YII 2 Curd 4

You’ll see a successfull message as shown above.


Step 2 Generate CRUD

YII 2 Curd 5

Look at the above snapshot,

In Model class, file Employees with the path frontendmodelsEmployees is generated.

In Search Model class, file EmployeesSearch with the path frontendcontrollersEmployeesSearch is generated.

In Controller class, file EmployeesController with the path @frontendviewsEmployees is generated.

Click on Preview button to check for error. If no error is there, click on Generate button to generaate the code. Again you’ll get a succesfull message for code generation.

Now our CRUD has been succesfully generated. To check it, run it on browser with the URL http://localhost/crud/frontend/web/index.php?r=employees/

YII 2 Curd 6

Look at the above snapshot, Employees is our table name and you can search an entry from this table.

To insert values in the table click on Create Employees button. Following page will appear.

YII 2 Curd 7

Fill the details above, and click on Create button. Data will be inserted in the table employees.

YII 2 Curd 8

Look at the above snapshot, we have filled some entries in the table. Here you can see the icons to View, Update and Delete.

On clicking View icon, following page containing John’s information will appear.

YII 2 Curd 9

On clicking Update icon, following page containing John’s information will appear where you can edit anything. Click on Update button after making changes.

YII 2 Curd 10

On clicking Delete icon, following box will appear asking you to delete it or not.

YII 2 Curd 11


Generated Code

In controllers, file EmployeesController.php will have the following code.

In models, file Employees.php will have the following code.

In models, file EmployeesSearch.php will have the following code.

In views, file view.php will have the following code.

In views, file form.php will have the following code.

In views, file search.php will have the following code.

In views, file create.php will have the following code.

In views, file index.php will have the following code.

In views, file update.php will have the following code.

Next TopicYii Structure

You may also like