The Gii code generator
Gii is the built-in code generator. It reads the structure of a table and creates a model class from it, as well as a controller and views for listing, viewing, creating and updating records. Such a set of pages is called CRUD, from the words create, read, update, delete.
Where Gii is
Gii is a module attached at the end of config/web.php inside the condition if (YII_ENV_DEV). It works only in development mode and only when accessed from the same computer. Open http://localhost:8080/gii (without pretty URLs, index.php?r=gii). A page with the list of generators appears.
| Generator | What it creates |
|---|---|
| Model Generator | A model class from a table |
| CRUD Generator | A controller and views for managing records |
| Controller Generator | An empty controller with actions |
| Form Generator | A form view for a model |
Generating a model
Choose Model Generator and fill in two fields:
- Table Name:
post; - Model Class Name:
Post.
Press Preview: Gii shows the file models/Post.php it is going to create. You already have this file, so it is marked as changed; tick the overwrite checkbox and press Generate.
The new model has three kinds of methods: rules() with validation rules derived from column types, attributeLabels() with field labels, and relation methods if the table has foreign keys. Relations and your own code written by hand are lost on overwrite, so add them again.
Generating CRUD
Choose CRUD Generator and fill in the fields:
- Model Class:
app\models\Post; - Search Model Class:
app\models\PostSearch; - Controller Class:
app\controllers\PostController.
After Preview and Generate these files appear:
controllers/PostController.php
models/PostSearch.php
views/post/index.php
views/post/view.php
views/post/create.php
views/post/update.php
views/post/_form.php
views/post/_search.phpOpen /post/index: there is a table of posts with sorting, search by columns and buttons for viewing, updating and deleting, and a button for creating a post above it. All this code is ordinary; you can read and change it.
Gii in the console
The same generators are started with a command:
php yii gii/model --tableName=post --modelClass=PostThe command creates models/Post.php and asks whether to overwrite the existing file.
How to use the result
Generated code is a starting point, not a finished section of the site. Usually service fields such as created_at are removed from the form, only the needed columns are kept in the table, and the actions are closed to outsiders. The next lessons cover everything Gii created (rules, forms, tables) one by one, so that this code becomes clear.
Common mistake
The overwrite checkbox replaces the whole file. If you have already written your own PostController and tick the checkbox without looking, your code is gone. Before Generate press the diff button next to the file: Gii shows exactly what will change.