CRUD Generation Using the Gii Tool in Yii2
Gii is a powerful tool in Yii2 that helps you quickly generate models, CRUD (Create, Read, Update, Delete) operations, and other code. Here’s a detailed guide to using Gii for CRUD generation:
Step 1: Access the Gii Tool
To open the Gii tool, navigate to your Yii2 application's backend URL and append ?r=gii
to it. For example:
backend/web/index.php?r=gii
Step 2: Create a Model
Open the Gii Tool:
- Go to the Gii interface by using the URL mentioned above.
Select the "Model Generator":
- Click on "Model Generator" to start creating your model.
Enter Table Name:
- In the "Table Name" field, enter the name of your database table. For example,
companies
.
- In the "Table Name" field, enter the name of your database table. For example,
Enter Model Class Name:
- In the "Model Class" field, specify the name of the model class. For example,
Companies
.
- In the "Model Class" field, specify the name of the model class. For example,
Set the Namespace:
In the "Namespace" field, set the namespace for your model class. For example:
backend\models\Companies
Preview and Generate:
Click the "Preview" button to review the generated code.
If everything looks good, click the "Generate" button to create the model.
Step 3: Create CRUD for the Model
Select the "CRUD Generator":
- Go back to the Gii interface and select "CRUD Generator" to generate the CRUD operations for your model.
Enter the Model Class Namespace:
In the "Model Class" field, enter the namespace of your model class. For example:
backend\models\Companies
Enter the Search Model Class Namespace:
In the "Search Model Class" field, enter the namespace for the search model. This typically follows the pattern of appending
Search
to your model name. For example:backend\models\CompaniesSearch
Enter the Controller Class Namespace:
In the "Controller Class" field, specify the namespace for your controller class. For example:
backend\controllers\CompaniesController
Leave the View Path Empty:
- Leave the "View Path" field empty to let Gii automatically generate the view files in the default location.
Preview and Generate:
Click the "Preview" button to review the generated code.
If everything looks good, click the "Generate" button to create the CRUD operations.
Result:
After following these steps, Gii will generate the necessary files for your model, including the model itself, a search model, a controller, and the corresponding views for CRUD operations. This significantly speeds up the development process by providing a functional set of CRUD operations out of the box.
By using Gii, you can efficiently scaffold the basic structure of your Yii2 application, allowing you to focus on customizing and extending the generated code to fit your specific requirements.
Subscribe to my newsletter
Read articles from Dan Ongudi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by