Creating Models, Views, and Controllers in Yii

November 7, 2009 — 181 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, the Gii tool is at This assumes you’re using the URL management component in Yii. If not, head to 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 or 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!

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

  1. I’m getting the following error; what can I do? I’m very new to yii….

    Yii Interactive Tool v1.0 (based on Yii v1.0.10)
    Please type ‘help’ for help. Type ‘exit’ to quit.
    >> model Department
    exception ‘CDbException’ with message ‘CDbConnection failed to open the DB conne
    ction: could not find driver’ in C:\Program Files\EasyPHP 3.0\www\frameworks\yii\framework\db\CDbConnection.php:255

  2. I am also getting the same error as the above user, event though my server setup passed the requirements test (I run other websites with PDO MySql with no problems)

    Could there be a bug?

    • Most likely it’s not a bug. As I talk about in the second post in this series, and I reference above, it’s possible that your Web PHP is configured differently than your command line PHP.

  3. On a mac there can be many versions of php, ie you have xampp or mamp installed. Per command line the default mac version is used (which is php4). By adding the xampp bin to the .profile file and realoading it you can make sure that all PHP commands are excuted by your preferred php version. Have a look at my post in the yii forum

  4. In the top of the page it says: “This entry is part 4 of 8 in the series”, but actually this is part 5.

  5. To avoid many problems with DB and the tutorial first try to:
    – edit DB connection in yourAppRoot/config/main.php (remove sqlite and uncoment edt mysql section)
    – create db structure
    – run yiic with proper privileges (for ex. sudo protected/yiic shell)
    – run model and crud commands
    – for me proper links to the app models were:
    I think it is obvious for the ones familiar with yii, but for me it was not :)
    Good tutorial anyway.

    • Thanks for your feedback. I talk about pretty much everything you describe earlier in this series, which is why it’s important to read them in order.

  6. Yes, I believe in the newest version of Yii (1.1.0), the actions have changed to the following URLs:

  7. Yiic didn’t generate list views for me (department/list and employee/list). Has that now changed to index? I’m using yii-1.1.0.r1700

  8. Robert, I just tested this myself. As noted in the above edit, show.php is now view.php and list.php is now index.php.

  9. Larry,
    Its working properly, but i have one doubt regarding this please help me..

    You are using reference key to connect your tables, but if you are delete the content (one department) from the depart ment table it shud delete all the employees connected via the the department. But its not happening here.. Cud you please tell me how it does become possible????

    • Excellent point. Most table types in MySQL don’t have true foreign key constraints, so the database will not automatically cascade changes like what you suggest. What you would do to make this happen is add code to the Department model so that when a given Department record is deleted, all employees of that department are also deleted. This is a theoretical change to implement, as you wouldn’t want to do that exact thing in a real-world application, of course. Personally, I’d be inclined to create a system for editing un-associated records instead.

  10. This blog acts weirdly to me, though I changed the computer, but post number 20 is written because I was thinking somehow I didn’t submit 18. and 19. (but I saw them online at previous computer). Now I seem them here too.. Sorry for the whole mess :(

  11. Seems like I was having some problems with http caching. It’s ok now, actually I haven’t touched anything… Please delete all my posts here because they don’t make sense. Thanks!

  12. at the end of this topic you wrote “You will see that there are no employees or department to list and also that you can’t add any new records without logging in (the default is admin/admin).”
    the problem is, i still can’t add new member(yes, i
    login to admin page), i have create the table employee and department, i tried to add new data, but nothing happen (event there’s no error message or something), i’m using yii Version 1.1.0, PHP Version 5.3.1, disable the sqlite on protected/config/main.php.i realy a newbie using yii, did i miss something?

    • Okay, so just to be clear, you login and click a button to add a new department and get the form for adding new departments. You enter that information and click the submit button and nothing happens? What screen appears next?

  13. first of all thanks of your kind respon.
    yup, i do those steps, i tried to add both employee and department data but nothing seems work correctly, for example, i tried to add employee data ( submit, nothing happen, the page is directed as if i want to add another data (the url is redirected to, at the list employee page show me “No results found.”
    i tried add the data through mysql, the data does appear at list employee page, but still i can’t update the data, the only works correctly was the “delete” button, and i still can’t add another data…what’s wrong?
    thanks for your answer.

    • You’re quite welcome. There’s no obvious answer here, to me at least. Since adding records manually does update the listing, that means that the database or database connection is not at fault. My guess would be that something is wrong with a model definition, which is why they’re not being added. But the fact that you’re not seeing error messages is strange. I would add messages to the Controller to see what is or is not happening, things like echo “Now about to process the submitted form.”

  14. Hi..larry, i’ve solved my problem…
    i think i’ve had make mistake on configuring-yii, on index.php file is written “$yii=dirname(__FILE__).’/../../framework/framework/yii.php';” yet i changed this to “$yii=dirname(__FILE__).’/../framework/yii.php';” without move the framework folder…i’ve just make new web page from beginning, and it’s just work fine…thanks larry

  15. Garry Freemyer March 30, 2010 at 1:11 pm

    I am stuck on the command model Department. I have followed the instructions as best as I can but I get an error about unrecognized charset. I get this error no matter what I put in this config item in main.php below ..

    The tutorial has been great and I’m sure it works for OS-X but I am on WampServer which I installed a few days ago so it should be the latest.

    ‘connectionString’ => ‘mysql:host=localhost;dbname=testexample’,
    ‘emulatePrepare’ => true,
    ‘username’ => ‘root’,
    ‘password’ => ‘Slogger1′,
    ‘charset’ => ‘utf8_general_ci’,

    • This really isn’t OS-specific, it’s just a matter of finding the right terms for your particular setup. Have you tried removing the charset association line entirely?

  16. Hi, great tutorial! anyway I hope this helps anyway out there. The MVC part (model Depart..etc) does not work out of the box with EasyPHP 5.3.2. It does with XAMPP. I havent looked at the detail but with XAMPP I dont get the “cannot find driver” error

  17. Re. #29 & #30: EasyPHP does have the possibility to install those drivers, but even after installing them it didnt work. The same code worked straight away with XAMPP (actually XAMPP lite). It more people have this problem, then it might be worth looking at it. I am fine with XAMPP now.

  18. I got an issue about CLI when i tried to create the model. This is it: “CLI has encountered a problem and needs to close. We are sorry for the inconvenience.”

    Error signature:
    AppName: php.exe AppVer: ModName: php_pdo_mysql.dll
    ModVer: Offset: 0000250a

    So i cannot create the model. Anyone can help me? Thx.

    • Without knowing more information, I would assume magic gnomes are causing the problem. What operating system are you using? How did you install PHP? Have you tried upgrading to the latest version of PHP?

  19. More information:
    I’m using winXP professional SP3 and XAMPP 1.7.0 is running for my web development. I was just tried to upgrade only php_pdo_mysql.dll, but i dont get it works.

    Thank you for your reply, Larry.

  20. Hi Larry,
    I’ve resolve my problem by upgrading my XAMPP to version 1.7.2
    Sorry for bothering you.

    Thank you.

  21. Hi and thanks for a great tutorial!

    I’m just wondering, haven’t we made ourself a circular dependency in the table setup? To create an employee, I have to tell which department the employee should belong to… but I can’t since there is no department yet. And to create a department, I have to tell which employee is the head of the department… which I can’t do either because there is not yet an employee… So i wont be able to create anything because of the foreign key configuration.

    To solve this, I would suggest to remove the not null contraint on the departmentHead column.

    • Thanks, Daniel, for your input. I address this specific issue in this comment. The short answer is that this design is somewhat theoretical and I put in the FK comments to help create the relations in the Models, but in a real world example there are many ways you might change the specifics.

  22. hi,

    i am new to php and framekworks, though not so much to MVC (i have dirtied my hands on ruby on rails earlier, but this one has to be on php).

    yiic crud creation is giving me errors. it says that the table doesnt have a primary key, whereas the table does have one.

    any clues ? I am running yii 1.1.1

  23. To anyone still scratching their heads about this message:

    “exception ‘CDbException’ with message ‘CDbConnection failed to open the DB connection: could not find driver’”

    Make sure you didn’t negelect to UNCOMMENT your connection information in config/main.php. Otherwise, you will get the above message.

  24. Hey Larry,

    I’ve been following your Yii series here. Great stuff. However, I am trying to use MSSQL with this and cannot find a way to properly configure Yii with MSSQL. I keep getting “CDbConnection failed to open the DB connection: SQLSTATE[01002] Unable to connect: SQL Server is unavailable or does not exist. Unable to connect: SQL Server does not exist or network access denied. (severity 9)”

    Any tips?


    • Unfortunately I’ve never used Yii (or even PHP) with MSSQL, so I don’t have any advice short of searching and using the Yii support forums. Sorry!

  25. Hi, I’m a newbee to yii.
    I have tested it on mysql and i want to create an application on oracle 11g..
    I installed php_pdo_oci and php_oci8_11g drivers
    and i can connect and query using php with
    both PDO and oci_connect.
    But when i try to create models with yiic i get the exception below and the model is not created.

    exception ‘CDbException’ with message ‘CDbCommand failed to execute the SQL stat
    ement: SQLSTATE[01002]: Disconnect error: 3113 OCIStmtExecute: ORA-03113: end-of
    -file on communication channel

    i searched oracle and yii forums, but couldn’t find a solution. i hope you can help me

    • Unfortunately I cannot help you. I haven’t used Oracle in a couple of years, don’t currently have it installed, and haven’t tested Yii with it. For me to answer your question, I’d search and look around, which you’ve already done. Sorry!

  26. Any info on the _view page?? I have been trying to make custom views so the user logged in can only see thier data based on thier user id…. and I am having all kinds of issues making any kind of custom view with relations using the _view file calling a $data variable from the view.php file with a widget…

    I can even delete the view.php file entirely and it doesnt change the functionality of the application, _view still renders and I am not sure where its calling that $data variable from at that point….

    I cannon figure out how to make custom views and controllers with Yii been slamming my head on the desk for days trying to figure it out..

    • Sorry for the delay; been kind of offline this week. This is a hard thing to debug in comments to a blog, but from what you describe, the Controller should be ensuring that the logged-in user is only viewing their data. I’m not sure customizing the view is what you want here. If you’re still having a problem with this, I would post a more detailed message in the Yii support forums or my support forums.

  27. Hi, Larry
    I really like your blogs and read most of your published books. The way you explain is fantastic.
    I’ve gain enough Advanced knowledge on php using your books. Before reading this blog on yii, i was using php and smarty. Smarty infact is good, but really wanted to try some good framework. I read books on cakephp, codeignitor, symfony etc…. but you won’t believe me reading yii for the first time, i got enough knowledge on using this framework… till this post .. everything is working fine to me using yii… i will read next post to know more deep in this framework.

    However, i want your suggestion, as i create portals and wanted to keep my codes safe… do you think yii is good for me…is there any way to combine yii with smarty…

    Thanks again…

    • Thanks for all the nice words. I’m not very comfortable with the “do you think XXX is good for me” question, as I don’t really know you, what you like, what you’re comfortable with, etc. But I like Yii and think it’s a very approachable framework, so I would recommend that you consider it. I believe that Yii supports Smarty. I’ve never really used Smarty much (or really seen the need for it) but I think Yii supports it. Thanks!

  28. In trying to create the crud operation for a table with a composite key made of three fields (one of the fields auto-increments within the group, I get the following error:
    Table “{$table->name}” has a composite primary key which is not supported by crud generator.
    From what I’ve found online it seems yii doesn’t support composite key or did I misunderstand?

    Macbook Pro – Snow Leopard – MAMP
    Apache 2.0.63
    MySQL 5.1.44
    Yii 1.1.2
    PHP 5.2.13 & 5.3.2

    • Thanks for your question and for providing all the relevant details. Honestly, I don’t know as I haven’t used Yii with a composite key myself. But that error message seems to suggest that Yii can’t auto-generate the CRUD code in this case, not that Yii does or does not support composite keys entirely (which would surprise me).

  29. Shaked Klein Orbach June 22, 2010 at 3:59 pm

    hey Larry

    Yii 1.1.2 offers new web tool called gii

    its exactly web-script that replace the cmd-shell.

    can be found on:

    good day,

    • Hello Shaked. Yes, Gii is pretty cool. I’ve mentioned it in a couple of other posts, I just haven’t updated this series for that change yet.

  30. Firstly thanks Larry for taking so much time on this tutorial – it is such a great help for me and I’m sure a lot of other people too.
    In answer to Oscar’s question re composite keys – yes Yii does support this, see
    It’s probably just the crud generator which doesn’t.

    • Thanks, Steve. Yes, Yii supports composite keys but the CRUD generator, command line or Gii, does not. That being said, I’ve just worked on a project with composite keys on intermediary tables and I didn’t see a need for CRUD functionality in those cases. Maybe just my experience.

      • Thanks for your Yii starters guide. I keep dropping solutions like Drupal or Joomla ‘cos they seem too bloated to me, and even though i like writing code (it should be easy for the user, but not necessarily so for the programmer), i’m trying to use a slim framework. Of CodeIgniter, Cake and others, Yii seemed the most attractive and it’s cool it uses MVC, AR and other patterns.

        I’m having the same problem with the CRUD generator one year later, though, and am pretty fresh at Yii.

        table questions has id, question;
        table answers has id, answer;
        table questions_answers has id_question, id_answer, right_answer (this last a bool). Both id fields are primary keys of their respective tables, while both id_ fields comprise a composite primary key, made of two foreign keys.

        The CRUD generator allows me to create questions and answers, but i won’t be able to associate them (mainly ‘cos there are a lot of Yes and No answers and i like to normalize) nor define which is the correct answer.

        How could i get around this?

        • First, I would question your database design. It implies that multiple answers might be usable for multiple questions. Even if that is appropriate, it would also imply that the same answer might be the right answer for multiple questions, which is dubious. In any case, if you add a comment indicating relationships, the CRUD generator should create the relationships for you in the Models. If not, you can easily add them yourself.

          • I’m trying to implement a simple Quiz kind of application. In this context, both “Yes” and “No” are very common answers which can be correct for many questions. Nothing dubious here, just me trying to avoid a whole bunch of “Yes” and “No” in the answers table.

            From the Yii forums, it’s obvious this issue is a hot topic. For some reason, the main developer(s) refuse to implement CRUD generation for composite primary keys.

            Some workarounds i’ve seen include adding another field to be used as the primary key while replacing the composite primary key constraint with just a unique constraint on both fields. This is rather cumbersome and pretty much against ER logic.
            Another approach seems to be dropping the primary key constraint, generating CRUD, and reapplying the constraint again in the DB while at the same time altering the now-generated code to reflect that. This also seems cumbersome, as it goes against the whole purpose of using a framework in the first place.

            Does adding a comment as you suggested create the primary key constraint at the framework level? How does it balance with the other two approaches?

          • I see. CRUD auto-generation on composite primary keys has indeed been a question/issue for some time. I don’t think a comment in the table definition works around this. My inclination would be to go the second route (drop the constraint, apply CRUD, etc.).

  31. Hi Larry, how can I change the administrator username and password on an auto-generated yii site?

  32. Hi, I am trying to create models using yiic shell command and I getting the below display –

    PHP Error


    date(): It is not safe to rely on the system's timezone settings. You are *
    required* to use the date.timezone setting or the date_default_timezone_set() fu
    nction. In case you used any of those methods and you are still getting this war
    ning, you most likely misspelled the timezone identifier. We selected 'Amer
    ica/Chicago' for '-5.0/DST' instead

    I’d appreciate any help in this regard


  33. PHP 5.3 issue, got solved…thanks

  34. I had some issues with getting this to work on a MacBook Pro running Leopard 10.5, I was seeing the “‘CDbConnection failed to open the DB connection: could not find driver” error message. I had to adjust a few things:

    1. “which php” revealed I was using the system PHP instead of hte PHP I installed myself. I added the installation location (~/pkg/php-5.3.0/bin) to my PATH in my .profile file, which used the correct php.
    2. I had to re-configure PHP to include PDO drivers (to see if you need to do this, you can check the output of phpinfo() and search for a PDO section). I originally added –enable-pdo, but this does not add support for mysql, so I had to also add –with-pdo-mysql=/usr/local/mysql. This makes my PHP configure line:

    ./configure \
    –prefix=$HOME/pkg/php-5.3.0 \
    –with-mysql=/usr/local/mysql \
    –with-apxs2=$HOME/pkg/apache-2.2.11/bin/apxs \
    –disable-cgi \
    –with-zlib \
    –with-mcrypt=$HOME/pkg/libmcrypt-2.5.8 \
    –enable-mbstring \
    –enable-pdo \

    After those two fixes, running “model Department” from the yiic shell worked fine.

    • Yes, the difference between the version of PHP used through the browser and that used through the command line can be confusing. Thanks for your posts. I need to update this series to discuss Gii, because it allows you to create Models et al. through the Web.

  35. Hi Larry, i have the following questions:

    ¿In Yii there any command to remove or undo the model was created using the command model?

    ¿And there is something to undo what was done by the command crud?

    Take this opportunity to congratulate you for the tutorial, I’m new in Yii, and the truth is that it has made me very easy start in this framework thanks to you.


    • Hello Daniel,

      Good questions. As far as I know there’s no Yii command to remove or undo a created model. But you can just delete the PHP script. Or you can re-call the model command, which will overwrite that script. I don’t think there’s an undo command for CRUD, but again, you can just delete and edit the PHP scripts.

      Thanks for the nice words on the posts!

  36. NICE Job,
    i found a small mistake{
    you write this link:
    for gii configuration instead of
    Thank you

  37. Another PHP Error using Gii and creating model:
    PDO::__construct() [pdo.–construct]: [2002] Invalid argument (trying to connect via unix://)

  38. I posted this earlier today, but perhaps it was while you were doing a site update and it got ‘lost’??

    I’ve gone through your really excellent tutorial (nice job!) and had no problems whatsoever. Now I’m trying to use Yii for a ‘real life’ project on the same MySQL db server as I used for the tutorial. The difference is this db uses InnoDB engine whereas tutorial used MyISAM. Anyway, when I try to use gii to generate models of my tables I get the following error message:


    Trying to get property of non-object

    Source File


    00226: return $lb.substr($tableName,strlen($prefix)).$rb;
    00227: }
    00228: return $tableName;
    00229: }
    00231: protected function generateRelations()
    00232: {
    00233: $relations=array();
    00234: foreach(Yii::app()->db->schema->getTables() as $table)
    00235: {
    00236: if($this->tablePrefix!=” && strpos($table->name,$this->tablePrefix)!==0)
    00237: continue;
    00238: $tableName=$table->name;
    00240: if ($this->isRelationTable($table))
    00241: {
    00242: $pks=$table->primaryKey;
    00243: $fks=$table->foreignKeys;
    00245: $table0=$fks[$pks[0]][0];
    00246: $table1=$fks[$pks[1]][0];
    00247: $className0=$this->generateClassName($table0);
    00248: $className1=$this->generateClassName($table1);
    00250: $unprefixedTableName=$this->removePrefix($tableName);
    Stack Trace

    #0 C:\wamp\yii\framework\gii\generators\model\ModelCode.php(87): ModelCode->generateRelations()
    #1 C:\wamp\yii\framework\gii\CCodeGenerator.php(158): ModelCode->prepare()
    #2 C:\wamp\yii\framework\gii\CCodeGenerator.php(61): ModelGenerator->prepare()
    #3 C:\wamp\yii\framework\web\actions\CInlineAction.php(50): ModelGenerator->actionIndex()
    #4 C:\wamp\yii\framework\web\CController.php(300): CInlineAction->run()
    #5 C:\wamp\yii\framework\web\CController.php(278): ModelGenerator->runAction()
    #6 C:\wamp\yii\framework\web\CController.php(257): ModelGenerator->runActionWithFilters()
    #7 C:\wamp\yii\framework\web\CWebApplication.php(324): ModelGenerator->run()
    #8 C:\wamp\yii\framework\web\CWebApplication.php(121): CWebApplication->runController()
    #9 C:\wamp\yii\framework\base\CApplication.php(135): CWebApplication->processRequest()
    #10 C:\wamp\www\maxdb\index.php(13): CWebApplication->run()

    I’m connecting ok to db and tables are all there. I’ve tried with ‘*’ for all tables and I’ve tried individual tables. always the same error message. Any clues?

    • Hello Bruce,

      Sorry for the delay and the mishap with the comment between the two sites. It’s been a hectic couple of days! Thanks for the nice words on the tutorial. As for this issue, I’ve not seen that before. If you’re positive that it’s due to the table type (or if that’s your hunch), you could create the table as MyISAM, then have Yii do its thing, then convert the tables to InnoDB. It’s an inelegant approach but would prove your theory. Apologies again for the delay!

  39. All the images are missing for this document.

    Thank You for the great work

  40. Hi Larry,
    I was allowed to create an employee without having created the department first. Is it not supposed to validate the department and reject it since this department has not yet been created? Thanks for your answer.

    • It’ll only do what you tell it to do. With the auto-generated code, there’s probably a restriction that the departmentId is an integer, but that’s about it. Subsequent posts in this series will explain more about validation.

  41. I forgot also to ask you about the difference in the type of fields of department in employee (smallint 5) and tinyint(3) in department. Thanks for your reply

    • That was a mistake. As this is a foreign key relationship, both columns should have the same data type (TINYINT). Thanks for pointing that out!

  42. I get the error

    Class ‘Employee’ does not exist or has syntax error.

    and the Crud Generator fails when using Employee as the Model Class.

    Any ideas??

    • Most likely, you made a mistake in a previous step.

      • Hi, I’ve managed to get the same error twice now. I’m sure it’s something simple but I have no idea where its gone wrong.
        Using wamp and vista, followed the instructions, mysql enabled and tables created in the database. pdo extensions enabled in php but can’t get past the crud generator and the model class.
        Any help much appreciated.

        Larry, you have really natural flowing tutorial style btw. Thankyou for putting this up here.

        • Thanks for the nice words. So…am I supposed to guess at what the error is that you’ve seen twice now?

          • Ahh sorry, schoolboy error.
            For some reason I skipped creating the models first in the model generator and went straight to the crud generator, did it in the testdrive tutorial then confidently repeated the mistake in this one. Must’ve been frazzled to the same degree on both occasions. Rather embarassing

    • I found your error reason.

      Crud Generator -> Model Class should be mach with Model Generator -> Model Class.

      So I am sure you may did one of following error,

      1. You may wrongly entered Model Class name which doest not match with on Model Generator.

      2. You may even not created Model Generator.

  43. On linux machine, those who faced this error while generating models,

    There was some error when generating the code. Please check the following message

    Generating code using template “/var/www/yii/framework/gii/generators/model/templates/default”…
    generating models/Employee.php
    Unable to write the file ‘/var/www/testapp/protected/models/Employee.php’.

    Navigate to the protected folder, right click, go to prmissions and make sure that the folder access is ‘create/delete files’.

    Just incase, this might help few if get stuck.
    I did it and it worked :)

    • I just noticed that you mentioned the permissions thing right below the four points of creation of the model.
      After reading 4 points, I started working on it, got errors and worked on the solution :P

    • Thanks for chipping in! I don’t regularly use Linux (as a desktop machine), so it’s great to have the extra perspective.

  44. I am getting this: Error 403 You are not allowed to access this page.

    It does not forward me to a login page. What is the login url for GII? I have followed all instructions to a T and have had no problems up untill now. Can you push me in the right direction???

  45. If you have enabled urlManager, and you added a rule to use the list action as the default action
    i.e. ‘=>’/list’, as described in the yii cookbook page at
    then gii will not load it’s login screen, because Gii doesn’t have a list action to be called.

    in that case, you can get to the login screen of Gii by using the path:

    but it will be much easier to use Gii, if you comment out the controller list rule while you are using Gii, and then re-enabled it when Gii is done.

  46. Hi, Larry,

    I’m having a problem: After using the CRUD generator for each of the tables, when I try to access either of the files from my browser (http://localhost/test/index.php/department/) I get a 404 error that says, Unable to resolve the request “department”. I went back through your configuration section and didn’t see anything that appears to be the culprit.

    Not sure if that’s enough info, but I’ve followed your tutorial to the letter up to now…

    • Clarification: I enabled urlManager, and entering “http://localhost/test/index.php?r=department” only results in the page refreshing, which is, I believe, what should happen with urlManager enabled…

      • No, if you’re using urlManager, then you should use http://localhost/test/index.php/department.

        • Thank for the reply, Larry.

          I think my “clarification” may have muddied the waters a bit! What I was trying to say (and I see, after reading over what I wrote before, that I didn’t say it very clearly!) was that regardless of what form of address I typed for either the department or employee I get the 404 error “Unable to resolve the request “department” (or “employee”).

          Thanks again,

          • I see. Well, it depends upon how your application is configured. How about using either my forums or the Yii forums to get further debugging help on this one?

  47. Larry,
    I am testing yii.
    After generate models and CRUDs for your example, the CREATE from for employees are not fully functional, because the Department field is not a list box with the departments name got from department table. How do I do this?

    For me, a really good framework is that one witch it create a fully functional CRUD system from the data model specified.

  48. Hi Larry As I am using the Yii Framework and i am stucking some where
    * My Query is how to delete the Data by the deleteAll() method of CActiveRecord i have one condition i want to delete the data by name field i have tried a lot by i couldn’t succeed.

  49. I want want the syntax with small examples of all Yii framework method and properties if it is available so that i can understand it and utilize it easily. The material provided you is awesome but the problem is that the syntax are not define very precisely even though in the book.

  50. Hi Larry, great series of tutorials. Really appreciate the effort.
    I do however have a problem when I configure the urlmanager to hide the entry-scriptname (aka the index.php in the url-path) my sites (other than the landing page: somehow stop working.


    I do not have any heavy rules either and I alos changed the corresponding .htaccess file accorndingly but I still cannot get the the default page to work without the entryscript reference in the url. Do you have any idea?

    Kind regards, best wisches and keep up the great work,

    • Hello Bruce. Thanks for the nice words. As for your problem, I don’t have any idea offhand. If you need help, please use my forums or the Yii forums.

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

    […] This entry was posted in Uncategorized by lss. Bookmark the permalink. […]

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

    […] Yii 프레임워크 배우기 시리즈의 8편중 다섯 번째 문서입니다. 원본 글은 에서 보실 수 […]

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