Scaffolding

Create, read, update and delete (CRUD) are the four basic operations of data objects in an application. Because the task of implementing the CRUD operations is so common when developing Web applications, Yii provides some code generation tools under the name of Gii that can automate this process (also known as scaffolding) for us.

Note: Gii has been available since version 1.1.2. Before that, you would have to use the yiic shell tool to achieve the same task.

In the following, we will describe how to use this tool to implement CRUD operations for posts and comments in our blog application.

1. Installing Gii

We first need to install Gii. Open the file /wwwroot/blog/protected/config/main.php and add the following code:

return array(
    ......
    'import'=>array(
        'application.models.*',
        'application.components.*',
    ),
 
    'modules'=>array(
        'gii'=>array(
            'class'=>'system.gii.GiiModule',
            'password'=>'pick up a password here',
        ),
    ),
);

The above code installs the a module named gii, which enables us to access the Gii module by visiting the following URL in browser:

http://www.example.com/blog/index.php?r=gii

We will be prompted to enter a password. Enter the password that we set in /wwwroot/blog/protected/config/main.php previously, and we should see a page listing all available code generation tools.

Note: The above code should be removed when running on the production machine. Code generation tools should only be used on development machines.

2. Creating Models

We first need to create a model class for each of our database tables. The model classes will allow us to access the database in an intuitive object-oriented fashion, as we will see later in this tutorial.

Click on the Model Generator link to start using the model generation tool.

On the Model Generator page, enter tbl_user (the user table name) in the Table Name field, tbl_ in the Table Prefix field and then press the Preview button. A preview table will show up. We can click on the link in the table to preview the code to be generated. If everything is ok, we can press the Generate button to generate the code and save it into a file.

Info: Because the code generator needs to save the generated code into files, it is required that the Web process have the permission to create and modify the corresponding files. For simplicity, we may give the Web process the write permission to the whole /wwwroot/blog directory. Note that this is only needed on development machines when using Gii.

Repeat the same procedure for the rest of the database tables, including tbl_post, tbl_comment, tbl_tag and tbl_lookup.

Tip: We can also enter an asterisk character * in the Table Name field. This will generate a model class for every database table in a single shot.

At this stage, we will have the following newly created files:

  • models/User.php contains the User class that extends from CActiveRecord and can be used to access the tbl_user database table;
  • models/Post.php contains the Post class that extends from CActiveRecord and can be used to access the tbl_post database table;
  • models/Tag.php contains the Tag class that extends from CActiveRecord and can be used to access the tbl_tag database table;
  • models/Comment.php contains the Comment class that extends from CActiveRecord and can be used to access the tbl_comment database table;
  • models/Lookup.php contains the Lookup class that extends from CActiveRecord and can be used to access the tbl_lookup database table.

3. Implementing CRUD Operations

After the model classes are created, we can use the Crud Generator to generate the code implementing the CRUD operations for these models. We will do this for the Post and Comment models.

On the Crud Generator page, enter Post (the name of the post model class we just created) in the Model Class field, and then press the Preview button. We will see a lot more files will be generated. Press the Generate button to generate them.

Repeat the same procedure for the Comment model.

Let's take a look at the files generated by the CRUD generator. All the files are generated under /wwwroot/blog/protected. For convenience, we group them into controller files and view files:

  • controller files:

    • controllers/PostController.php contains the PostController class which is the controller in charge of all CRUD operations about posts;
    • controllers/CommentController.php contains the CommentController class which is the controller in charge of all CRUD operations about comments;
  • view files:

    • views/post/create.php is the view file that shows an HTML form to create a new post;
    • views/post/update.php is the view file that shows an HTML form to update an existing post;
    • views/post/view.php is the view file that displays the detailed information of a post;
    • views/post/index.php is the view file that displays a list of posts;
    • views/post/admin.php is the view file that displays posts in a table with administrative commands.
    • views/post/_form.php is the partial view file embedded in views/post/create.php and views/post/update.php. It displays the HTML form for collecting post information.
    • views/post/_view.php is the partial view file used by views/post/index.php. It displays the brief view of a single post.
    • views/post/_search.php is the partial view file used by views/post/admin.php. It displays a search form.
    • a similar set of view files are also generated for comment.

4. Testing

We can test the features implemented by the code we just generated by accessing the following URLs:

http://www.example.com/blog/index.php?r=post
http://www.example.com/blog/index.php?r=comment

Notice that the post and comment features implemented by the generated code are completely independent of each other. Also, when creating a new post or comment, we are required to enter information, such as author_id and create_time, which in real application should be set by the program. Don't worry. We will fix these problems in the next milestones. For now, we should be fairly satisfied as this prototype already contains most features that we need to implement for the blog application.

In order to understand better how the above files are used, we show in the following the workflow that occurs in the blog application when displaying a list of posts:

  1. The user requests the URL http://www.example.com/blog/index.php?r=post;
  2. The entry script is executed by the Web server which creates and initializes an application instance to handle the request;
  3. The application creates an instance of PostController and executes it;
  4. The PostController instance executes the index action by calling its actionIndex() method. Note that index is the default action if the user does not specify an action to execute in the URL;
  5. The actionIndex() method queries database to bring back the list of recent posts;
  6. The actionIndex() method renders the index view with the post data.
$Id$

Total 3 comments

#672 report it
flyingturtle at 2010/03/22 11:58pm
For those who can't crud Post and Comment

I got stuck on the scaffolding part when executing "crud Post" and "crud Comment".

I realized that I had "tblPost" and tlbComment" in my model folder and not "Post" and "Comment". I had forgotten to add the 'tablePrefix'=>'tbl_', in my config/main.php file, in the components db array section, as mentioned in the previous chapter of this blog tutorial: http://www.yiiframework.com/doc/blog/prototype.database

If you have that 'tablePrefix'=>'tbl_' line, then it will remove the "tbl_" prefix from the table names when generating the models via the "model *" command.

You can also read this point in a reply by Qiang to another person who forgot to add the tablePrefix line in their config/main.php file. http://www.yiiframework.com/forum/index.php?/topic/7545-help-yii-configuration-on-mac/page__view__findpost__p__38330

Maybe a reminder about this could be added to this chapter in the blog tutorial, as maybe others might run into this issue if they forgot to edit their main.php file.

#1323 report it
mirrorps at 2009/09/11 09:10pm
webapp on yii-1.0.6.r1102 issue

I'm trying to run the shell and to create model. There is an error under cmd: Fatal error: Cannot redeclare class Yii in path-to-app\lib\yii-1.0.6.r1102\framework\yii.php on line 29 What am I doing wrong?

#1714 report it
tim at 2009/04/29 04:02pm
How YII determines the REQUIRED fields to flag in a form

In case you're curious how those little "REQUIRED" asterisks (*) appear next to certain fields on the Web form for Posts or Comments it's determined by the data structure in the SQL file you imported to create the blog database. In the case of MySQL, any field in the database that's defined with the NOT NULL keywords is turned into a REQUIRED field in the form.

Leave a comment

Please to leave your comment.