Creating Models, Views, and Controllers in Yii

November 7, 2009 — 178 Comments
The Yii Book If you like my writing on the Yii framework, you'll love "The Yii Book"!
This entry is part 5 of 8 in the series Learning the Yii Framework

This is the fifth post in my series on Yii, my favorite PHP framework. In the first, I show how to download and test the framework itself. In the second, I show how to create a basic Web application. In the third, I walk through some configuration options. In the fourth, I explain the database design to be used by the sample application that this and the subsequent posts discuss. In this post, I show how to use Yii’s Gii tool to create Models, Views, and Controllers in your Yii application. This post does assume you have an existing application to work with, most likely by following the steps in my previous posts.

(Note: In October 2010, I’ve updated this entire series to reflect changes in Yii since this series was written, and to take into account feedback provided through the comments. Some outdated material will be crossed out, but left in to reflect how things have changed since the series was begun in June 2009. This post had the heaviest revisions, as the command-line tools were replaced by the Web-based Gii.)

Yii, like Ruby on Rails and a few other frameworks, has tools that will generate code, files, and directories for you. As you can imagine, this is a tremendous time saver. Yii originally offered just the command-line yiic tool for this purpose (also used to create the Web application itself). As of Yii 1.1.2, there’s now the Web-based Gii, which runs in the browser. In this post, I’ll explain how to use Gii to create the fundamental Model, View, and Controller files required by the application (subsequent posts cover how to edit the auto-generated code to suit your needs).

Note: You can still use the command-line yiic, if you prefer that environment.

This post demonstrates Gii using an employees-departments example, with the two database tables already created (see the previous post). A couple notes up front:

  • Because Gii does so much of the work for you, you really want to have your design as complete as possible. If done properly, after creating your database tables following these next steps, you won’t use Gii again for the project.
  • You must enable Gii, using the instructions in the third post.
  • Because Gii is a powerful tool, it’s best not to enable it on a live server. Ideally you’ll enable Gii on a development server, use it, and disable it, and then later put the site online.
  • If you’ll be putting the completed application on a live server which you don’t have command-line access to, you can develop the whole thing on your local computer, then upload the generated and edited files. Again, the command-line tool is really for the initial setup.
  • The successful use of the command-line tool relies upon having a properly configured command-line version of PHP installed and used to execute the command-line script. See my notes in the second post for more.
  • Make sure that the two database tables exist.
  • Make sure that you’ve edited your main.php configuration file so that the Yii application can connect to the database. See the third post for more.

Tip: For extra security, Gii can be set to only work for a specific IP address (i.e., yours).

Assuming you understand all of the above and have taken the requisite steps, you should now load Gii in your browser. Assuming your site is to be found at www.example.com/index.php, the Gii tool is at www.example.com/index.php/gii/. This assumes you’re using the URL management component in Yii. If not, head to www.example.com/index.php?r=gii. You should be taken to the login screen, where you just enter the Gii password (established in the configuration file), and click Enter. Assuming you entered the correct password, you’ll see a splash page and a list of options (as links).

Gii Splash Page

Gii Splash Page

The first thing you’ll want to do is generate the Models. Click the “Model Generator” link. On the following page:

  1. Enter Employee as the Table Name.
  2. Enter Employee as the Model Class. You’ll notice that the form automatically copies the table name as the Model name.
  3. Click Preview. You’ll see a table appear at the bottom of the form, indicating the files to be generated (just one in this case).
  4. Click Generate.

Tip: To automatically model every database table, just enter * for the table name.

Generating a Model

Generating a Model

You should then see a message indicating that the code was created (you can check for the new file to confirm this). If you see an error about an inability to write the file, you’ll need to modify the permissions on the protected/models directory to allow the Web server to write there. Once this works for you, repeat the process for the Department table.

These steps generate the protected/models/Department.php and protected/models/Employee.php scripts, which you can now open and check out in your text editor or IDE. When using Yii version 1.0.10 1.1.4, the Model file had about 60 110 lines of code. I’ll get into the specific code in a subsequent post, but you’ll see methods that define validation rules for the Model, relations this Model has to others, and so forth.

Next, and this is big, create CRUD functionality. CRUD stands for Create, Retrieve, Update, and Delete. In other words, everything you’d do with database content. Click the “Crud Generator” link. On the following page:

  1. Enter Employee as the Model Class.
  2. Enter employee as the Controller ID. You’ll notice that the form automatically copies the Model Class, in lower camelcase as the controller ID. So Employee becomes employee, SomeThing would become someThing.
  3. Click Preview. You’ll see a table appear at the bottom of the form, indicating the files to be generated.
  4. Click Generate.

Tip: If you know you won’t need certain functionality, such as the ability to create or delete a Model type, deselect the corresponding checkboxes.

You should then see a message indicating that the code was created. Again, if you see an error about an inability to write the file, you’ll need to modify the permissions on the protected/controllers and protected/views directories to allow the Web server to write there. Once this works for you, repeat the process for the Department Model. The resulting page will also offer up a link to go test the generated files.

Crud Generator

Crud Generator

That one step will create the Controller file for each Model (DepartmentController.php and EmployeeController.php), plus a View directory for each, with eight View files per Model:

  • _form.php
  • _search.php
  • _view.php
  • admin.php
  • create.php
  • index.php
  • update.php
  • view.php

The form file is used to both create and update records. The search script is a custom search form. The _view.php file is a template for showing an individual record. The admin script creates a tabular listing of the Model, with links to CRUD functionality. The index script is really intended for a public listing of the records. The view script is used to show the specifics of an individual record. And the create and update files are wrappers to the form page, with appropriate headings and such.


Edit for Yii 1.0: In earlier versions of Yii, prior to 1.1, the view.php file was called show.php and index.php was called list.php. There were also fewer View files created.


Note: You will have situations where you’d have a Model for something but not want CRUD functionality, so don’t assume you always take both steps.

So that’s it! You can click “logout”, then click “webapp” to return to the home page. You can confirm that what you did worked by checking out the new directories and files or by going to a URL. Depending upon whether or not you added urlManager to the application’s configuration, the URL would be something like www.example.com/index.php/employee/ or www.example.com/index.php?r=employee. You will see that there are no employees or departments to list and also that you can’t add any new records without logging in (the default is admin/admin).

In my next post, I’ll discuss how to start editing the generated code to make the application behave more like you want it to in the real world. But thanks to Yii’s Gii tool, about 80% of the work has been done for you!

If you enjoyed this post, then please consider following me using your favorite social media, the RSS feed, and/or by subscribing to my newsletter. Or go crazy, and buy one or more of my books . Thanks!

178 responses to Creating Models, Views, and Controllers in Yii

  1. Larry,

    I’ve been wondering how to map class Dog and class Cat (which both are subclasses of class Animal) using Yii – since the models all use their one shot at inheritance to extend CActiveRecord.
    What can I do? Interfaces would really, really mean duplicating a LOT of code. All I can imagine is making the model an attribute of class Cat but it seems like that’d get pretty cumbersome.

    Thanks!

  2. Best Tutorial Yii!

    Thank’s!

  3. small typo: should be /models and instead of /model here-> search this text: “need to modify the permissions on the protected/model “.

  4. Helo Larry, i wanna ask
    can’t update my database, the error is
    Error 404
    The requested page does not exist.

    what i must do??thanks

    • What you should do is either post a message in my support forums or the Yii support forums. The comments area is just not a good place for debugging help. When you do post a message wherever, be certain to include MANY more details, such as the version of Yii in use, the OS, the Web server, the URL that gives that response, etc., etc.

    • I got the error 404 when I ran index.php/gii. I don’t know if that is the same error you’re getting.

      I fixed it by commenting out the line ”ipFilters’=>array(‘127.0.0.1′,'::1′),’, where the ip address is where my server resides.

  5. For those that are getting the error “CDbConnection failed to open the DB connection: could not find driver “, I fixed it by commenting out this line in php.ini ‘extension=php_pdo_mysql.dll’ (remember to restart your apache server after you make this change)

    You also probably want to make sure your requirements are met at http://localhost/yii/requirements/index.php. If you’re using MySQL, the PDO MySQL extension should pass.

  6. Hi Larry,

    I asked in a previous comment about mapping classes Cat and Dog to Yii.
    You had a great suggestion … extending Animal from CActiveRecord then having Cat and Dog extend from Animal. I did that; modifying the classes created by the gii/Model Generator then running the Crud Generator. When I create a Cat on the crud page though, it doesn’t save and though in config/main I have CWebLogRoute enabled, there’s no error message to help. CRUDing a Cat that inherits CActiveRecord directly works fine but all the class methods I need don’t exist then.

    Now Animal is not something I want to create a table for. It’s just a class that defines variables and functions that are common to its subtypes. I built and wrote the class/interface model before I found Yii and it works fine, perfectly in fact. Now though, I can’t figure how to get it in Yii.

    Maybe the non-table related classes shouldn’t be with the models but I .. just .. can’t .. figure .. where they should reside and etc.

    Another example … I need these but I don’t need them in the DB. They look like model entities to me but maybe, in Yii they are something else…

    abstract class NetworkAddress extends Object
    > get, set address string
    class IPAddress extends NetworkAddress
    > url string, port number, ensure string is in IP format
    class MACAddress extends NetworkAddress
    > ensure string is in MAC format

    Thank you very much Larry!

    • This is an interesting situation and one that I expect others must come across, although I haven’t personally yet. I guess there’s an argument to not creating Animal as a CActiveRecord and doing it as an abstract class/interface instead. I don’t have a concrete answer for you off the top of my head and the comments to a blog aren’t a good place for detailed debugging work. If you’d like my help in particular, post a message in my forums and we can try to work this out together. Alternatively you can post a message in the Yii support forums, and get the help of many people.

  7. Hi Larry,

    Just wanted to say thanks for your great tutorial, I recently developed a (as it turned out ) quite large web project for a friend of mine using codeigniter(versions 172 – 202) and finally had the time to look at Yii, it seems to be a great framework, albeit a steeper learning curve than CI, I am still trying to understand the relationships between the various parts of Yii, however do you think that Yii is mature enough for a large web application project?

    • Thank you very much, Jon. I’m glad you like the tutorial. I just posted a link to an article that compares Yii, Zend, and Code Igniter, and that writer (I think) said the same thing about Yii having a steeper learning curve. I definitely think Yii is mature enough for a large Web application and have used it on a couple complex, large sites myself.

      • Ok, thank you for your response Larry I’ll try using Yii to convert a couple of sites and see how it goes

  8. Mirza Fariad Ahmad June 22, 2011 at 8:13 pm

    Thanks very much, Larry, i appreciate your help, coz it helped me very well to learn this fw.

  9. In your note you mention it may not be necessary to use the CRUD generator if it isn’t wanted / needed. For example: Province table with province 2 letter abbreviation column and full province name column. It will be used for drop down selection list on a form, and may be used for retrieving the full province name when retrieving a member’s province, which is in a member table with a province column. That data in the province table will just be retrieved. Is this one of those situations?

    Excuse me if this is a very simple question, but I’m new to frameworks and I’m always wanting to follow best practices.

    • Yes, that’s exactly correct. You’d want a Model of that table, but you wouldn’t need to create CRUD functionality. Thanks for the question!

  10. Hi Larry,

    Excellent tutorials! Very easy read and great to follow. Got into some trouble and I was wondering if you can tell what would be potentially going on:

    I am trying to follow this tutorial on a WAMP Stack(Bitnami):

    – Apache 2.2.17
    – MySQL 5.1.56
    – PHP 5.3.6
    – PHPMyAdmin 3.4.2

    and Yii 1.1.8.

    I get a Table “Employee” does not exist everytime I try to create a model (as in the said tutorial). I followed the tutorial and encountered no problem so far. Things I have done so far:

    1. Created a database called myfirstyiiappdb, in phpMyAdmin
    2. I c/p’ed the SQL (from your Defining DB from your Yii app) for the Employee and Department Tutorials into phpMyAdmin and successfully created the tables.
    3. Updated the following entries in my main.php

    ‘db’=>array(
    ‘connectionString’ => ‘mysql:host=localhost;dbname=myfirstyiiappdb’,
    ‘emulatePrepare’ => true,
    ‘username’ => ‘root’,
    ‘password’ => ‘qwer1234′,
    ‘charset’ => ‘utf8′,
    ),

    4. Then I login to Gii and click models, enter Employee in table name field (other times i tried employee in all lower case, but that doesnt make a difference sadly), and hit Preview and tells me that Table ‘Employee’ (or ‘employee’) does not exist.

    5. I tried instead putting * in the table name field, and tried again, and this time I created the models/TblUser.php, and only that.

    I suspect that somehow it may not be able to successfully connect with my database (I haven’t gotten a PDO based connection error yet, so I figure it must be connecting with the db). I am new to this, and any help would be really awesome.

    THANKS

    • Thanks for the nice words on the writing. Thanks, too, for providing all the details. However, the comments section to a blog isn’t a good place to provide lengthy debugging help. If you need assistance, please either use the Yii support forums or my support forums.

  11. I really need an early version of your new book. I can not wait untill Sept 19th. What can you do for me.
    Just curious. Why is the ebook version more than the printed version?
    I have seen enough to know your book can only be helpful to me.
    If possible send me a protected copy. I have kindle ebook software for windows 7
    If possible can you confirm for me that models do not need property variables defined in an CActiveRecord class. It is my guess the Form controls provide the storage space used. Am I right?
    How would I take two models representing two tables and share or assign values to the php controls essentially or am I missing something here??

    • Hello Rob. Thanks for the interest in the book. To be absolutely clear, the book coming out on Sept 19th is the fourth edition of my “PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide”. I don’t really know anything about the pricing of it and I don’t have any electronic versions of it at all, to give away, to sell, or to read myself. In short, I have nothing to do with the actual selling. I sincerely thank you for the interest, though.

      As for your question regarding CActiveRecord property variables, if I understand your question correctly, you absolutely do need property variables. I’m not sure what you mean by “Form controls”, but there are no form controls that provide any storage at all. As for your question about taking two models and assign values to PHP controls, I’m not sure what you’re asking, but it sounds like you’re asking about what the Yii framework will do automatically, once the Model is defined.

  12. i wondered from create form in employee how YII recognized the field is required or not? (eg. email is required, Ext is not required)

    anyway, this lesson really good. You type looks like really a professional writer. Did you have write a book which describe develop application in YII in more details? Like creating a big application? (tried to see on summary, but cannot fin which one relevant to YII).

    • Thanks for your questions and feedback. The required status of a field in defined in the Model. You cannot save a Model that is missing a required field.

      I am a professional writer and I am hoping to write a book on Yii. Thanks for asking. I haven’t written anything about Yii in any of my existing books, though. I’m writing a JavaScript book now and hope to do one on Yii after that, if time allows.

  13. I got this error when i clicked on Model generator:

    YiiBase::include(PDO.php) [function.YiiBase-include]: failed to open stream: No such file or directory .

    Please help

    • You haven’t posted enough details for me to even begin to assist. If you need help, please use the Yii support forums or my support forums, and include more details when you do.

  14. Larry awesome work……thanx a lot for ur wonderful post… it helped a lot… Again thank you very much….

  15. I am having the same problem as clay is having. I have a database which supports multiple user types. I defined a super class User and inherited the attributes to two classes namely Student & Employee. To make matters more complicated I further extended employees to Staff and Faculty respectively.

    I intent to use the CRUD on the sub class level, that is when adding, updating, retrieving and deleting a student, a staff and a faculty. I am curious if a solution has already been found :)

    Thanks and awesome tutorial by the way. ^_^

  16. After following your steps (which I believe was exactly), I found that I was getting an 404 error when trying to view the /employee page for the first time. After much digging around, I’m finding that ../employee/index is what brings me to the correct page. I have the correct .htaccess and rules, have protected outside base dir of site with absolute directory listing in the index.php for the site. Don’t know if things have changed in the latest release or if I missed something, but just trying to access/employee show that the “list” is missing in the trace.

  17. Thanks I was struggling for a long time to understand MVC frameworks and today after months of reading and frustrated playing with several frameworks like CI and Zend .. it has for the first time started making sense to me. YII rocks and you are my hero :)

    One question:
    When doing a crud operation on the department table i see that its generating two versions of view.php
    a) views\department\view.php
    b)views\department\_view.php (one with an underscore)

    Why these two views ?
    Just cannot thankyou enough for helping me take the big leap to framework based programming

    • You’re quite welcome and thanks for the nice words. If you like at the files, I think you’ll see that _view.php is included by view.php and represents a more specific aspect of the viewing of an individual department.

  18. Any method to generate model and view files (CURD option) for every model at once?

  19. This is an excellent tutorial, kudos to you for putting it all together. I’ve been against what I call CMS style site where optimization is ignored for the sake of easy programming. I’ve always clustered frameworks in with CMS like programming. I run a few heavy traffic sites and am hesitant to use anything that will slow down the sites or require more hardware to run. however I’m being pushed hard to open my horizons and am being called an idiot for not using a framework. I see a lot of advantages but my number 1 goal is efficiency. running the crud creation code I see that to view the employees it runs 4 queries,

    SHOW COLUMNS FROM `Employee`
    SHOW CREATE TABLE `Employee`
    SELECT COUNT(*) FROM `Employee` `t`
    SELECT * FROM `Employee` `t` LIMIT 10

    Is this how all the generated stuff is? This is really bad and it most likely teaches people some pretty horrendous coding practice. I’m trying hard to embrace frameworks, but this type of thing scares me, anyone have any thoughts on this?

    • Thanks for the nice words. You bring up good points. I would start by suggesting something I learned from Ruby: it’s relatively easy to make software run faster, but it’s rather hard to find more time for developers to do everything they need to do. In other words: maybe making something easier to develop even if that means it’s slower to run is a perfectly reasonable argument. But if you don’t like that one, the solution in these situations is to cache, cache, cache. For example, schema caching alone in Yii will drop those first two queries. The other two are common on any paginated result set.

      I wouldn’t, however, say this “teaches” horrendous coding practices as I don’t think people would get to this point of seeing how a framework works without having first learned how to do it the manual way, as you have.

  20. This tutorial helps me a lot :-) I have planned to use Yii framework only after reading your tutorials. thanks once again, Sankar

  21. How to make a model?

    I am trying to make a model through gii. I have download the yii-1.1.12.b600af and it is different from sceenshot that you have shown.
    It has Database Connection * field that set as a defauld “db”. With this settings it gives me error “Table ‘Employee’ does not exist”.

    I have created database “testdrive” and table “Employee”.
    I have uncommented
    lines in console.php
    ‘db’=>array(
    ‘connectionString’ => ‘mysql:host=localhost;dbname=testdrive’,
    ‘emulatePrepare’ => true,
    ‘username’ => ‘root’,
    ‘password’ => ”,
    ‘charset’ => ‘utf8′,
    ),
    I tried to change “Database Connection” to testdrive or mysql:host=localhost;dbname=testdrive

    It still gave me error “A valid database connection is required to run this generator”

    Is it a problem with new yii-1.1.12.b600af?

  22. I have found my bug – error “Table ‘Employee’ does not exist
    I need to uncomment lines in both console.php and

    main.php
    ‘db’=>array(
    ‘connectionString’ => ‘mysql:host=localhost;dbname=testdrive’,
    ‘emulatePrepare’ => true,
    ‘username’ => ‘root’,
    ‘password’ => ”,
    ‘charset’ => ‘utf8′,
    ),

  23. when creating the models I had to chmod the models did to allow o+w. I also had to do this for controllers and views. I assume after I’m done with gii I should remove this world write priv?

  24. Hi Larry,

    Thank you very much for the tutorial. I am considering using Yii as the php framework to develop a social networking site like
    http://www.yotive.com

  25. sir i directly placed your files . but it gives an error while clicking on login

    Property “LoginForm.username” is not defined.

    /usr/share/nginx/www/yii1/framework/web/helpers/CHtml.php(2255)

    2243 $name=substr($attribute,0,$pos);
    2244 $value=$model->$name;
    2245 foreach(explode(‘][',rtrim(substr($attribute,$pos+1),']‘)) as $id)
    2246 {
    2247 if((is_array($value) || $value instanceof ArrayAccess) && isset($value[$id]))
    2248 $value=$value[$id];
    2249 else
    2250 return null;
    2251 }
    2252 return $value;
    2253 }
    2254 else
    2255 return $model->$attribute;
    2256 }
    2257

    i have configured database also.

    i am requesting you to please upload your yii login-authentication project folder . so i will try executing here. this is very important for me . kindly do favor

  26. I really want to say thank you for what you’ve done, it really helped me a lot!

    And now I want to record some problem I met when I learn, and also I will offer my solusion.
    When I created the database My_manage_01, and then went to the http://localhost/yiitestapp/index.php/gii to click the Model Generator, it turn to be wrong, and it says like this:

    CDbConnection failed to open the DB connection: SQLSTATE[HY000] [1045] Access denied for user ‘root’@’localhost’ (using password: NO)

    After suffering for one night, I finally find the answer. It’s in the C:\xampp\htdocs\yiitestapp\protected\config\main.php, line 55. You need to add the database you created manually and so as the code.

    Then everthing is OK.

  27. How to create Models, Views, and Controllers in Yii but not using gii? Please…

  28. Hi!!!!
    Thanks so much for great jobs !
    Loved this whole series & bought the book as a result.
    i have learnt a lot from you but i m facing a issue that how i can use a single controller to insert data in multiple table like child parent tables and same as how i can i use joins using Gii kindly help me with that it ll be very kind of you.

  29. Hi Larry!
    Great tutorial! Congratulations!

    I did have a problem in this chapter, but I found how to fix it:
    If it is used the MySQL installation without xammp, occurs a error because the field “leaveDate” don’t support zeros.
    To fix it, is necessary to remove the sql-mode “STRICT_TRANS_TABLES” in the file my.ini and restart the service.

    More information here:
    http://www.yiiframework.com/forum/index.php/topic/12125-problem-with-creating-a-new-project-in-chapter-5/

    Best regards!
    Fabio

    • Thanks for sharing your experience!

      • Hi Larry,

        I’m a beginner in Yii Framework, cause before i developped native PHP and didn’t use PHP FrameWork ! so to learn the FrameWork I started to read Yii.com documentations, i searched also for Boostrap and i found YiiBoilerPlate but when i started to use YiiBoilerPlat, i found it quite difficult cause it doesn’t have much documentation and tutorials ! so i decided to do teps back and learn the classic YiiFramework and i found your tutorials, I just finished your tutorials and i think they are really great and helpful !

        I ask you if you can help me with YiiBoilerPlate: https://github.com/clevertech/YiiBoilerplate , if you can of course !

        thank so much for your help Harry !

        Slim,

  30. You made me love Yii, thank you

  31. greart ………..

  32. Hello,

    I’ve been following your Yii series here. Great stuff. But i am trying to use sqlite. I keep getting “exception ‘CDbException’ with message ‘CDbConnection failed to open the DB connection: could not find driver’ in /opt/lampp/htdocs/yii/framework/db/CDbConnection.php:382″
    Any tips?

    Waiting for your reply

    Thanks & Regards,
    Rekha

  33. hi lary,
    I am using xampp.
    while doing model generator on code generator,
    I am getting exception like this:

    CDbConnection failed to open the DB connection: SQLSTATE[HY000] [1049] Unknown database ‘testdrive’

    C:\xampp\htdocs\yii\framework\gii\generators\model\ModelCode.php(60)

  34. CDbConnection failed to open the DB connection: SQLSTATE[HY000] [1045] Access denied for user ‘bgklss’@’localhost’ (using password: YES)
    sir, how to resolve the above error.

Trackbacks and Pingbacks:

  1. Creiamo le Model, le Viste ed i Controller in Yii | Programmando Facile - June 14, 2012

    [...] Fonte: Larry Ullman [...]

  2. After Creating CRUD with Gii | Scrap Notes - June 17, 2012

    [...] http://www.larryullman.com/2009/11/07/creating-models-views-and-controllers-in-yii-2/ This entry was posted in Uncategorized by lss. Bookmark the permalink. [...]

  3. Learning the Yii Framework 5 / 8 | 웁스교교주의 이야기 - July 15, 2013

    [...] Yii 프레임워크 배우기 시리즈의 8편중 다섯 번째 문서입니다. 원본 글은 http://www.larryullman.com/2009/11/07/creating-models-views-and-controllers-in-yii-2/ 에서 보실 수 [...]

Comments are great, but I'd strongly prefer any requests for assistance get made in the support forums. Thanks!