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
Step 2 Generate Model
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.
Look at the above snpashot, click on Generate button to generate the code.
You'll see a successfull message as shown above.
Step 2 Generate CRUD
Look at the above snapshot,
In Model class, file Employees with the path frontend\models\Employees is generated.
In Search Model class, file EmployeesSearch with the path frontend\controllers\EmployeesSearch is generated.
In Controller class, file EmployeesController with the path @frontend\views\Employees 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/
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.
Fill the details above, and click on Create button. Data will be inserted in the table employees.
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.
On clicking Update icon, following page containing John's information will appear where you can edit anything. Click on Update button after making changes.
On clicking Delete icon, following box will appear asking you to delete it or not.
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.