Skip to content


Basic Model Edits in Yii

This entry is part 6 of 8 in the series Learning the Yii Framework

This is the sixth 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 my database design, and how you should define it with Yii in mind. In the fifth, I show how to use Yii’s Gii tool to create Models, Views, and Controllers in your Yii application. In this post, I walk through some of the basic edits you’ll likely make to a Model after it’s been created by Yii’s Gii tool. In doing so, you’ll also get a general introduction to the Yii Model as a whole. For some of the code, I’ll be using the employees-departments example I’ve been developing throughout these posts. You may want to reread earlier posts to get a handle on those.

(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.)

The Model represents the data used by an application. Normally the data comes from a database, but it could also be from a form submission (to be emailed, not stored, like the ContactForm Model in the base Yii application). In Yii, a Model based upon a database table is defined as a class that extends (i.e., inherits from) Active Record. Active Record is a common and popular design, also used by the Ruby on Rails framework. This means that most of the Model’s functionality isn’t defined in your Model, but rather in the parent Active Record class. So when looking at your Model code, don’t be surprised that you won’t find methods for creating and updating records (i.e., saving the Model) or whatever, and that’s all inherited. Since that functionality is defined already for you, the goal of your Model should be to extend and tweak that functionality as needed.

Within a Model, there are certain Yii-specific methods (class functions) that you’ll commonly use. Some of these will be created when you use Yii’s Gii tool to generate the Model, others can be added whenever. I want to focus on those Yii-specific methods here, as they’ll be common to most Models. (In later posts, I’ll write up examples of custom methods that might be added to Models.)

One of the most important methods is rules(), which lists the rules by which the Model data must abide. Much of your application’s security and reliability stems from this method. In fact, this one method represents one of the key benefits of using a framework: data validation. Whether a new record is being created or an existing one is updated, you won’t have to write, replicate, and test the data validation routines: Yii will do them for you. As a comment in the Model indicates, you only establish rules for fields (i.e., Model attributes) whose data may be provided by users. You wouldn’t, for example, declare a rule for the Employee id field, which is the MySQL-generated primary key.

The rules() method, like most of the Yii methods, returns an array of data:

public function rules()
{
    return array(/* actual rules */);
}

For the actual rules, the Yii documentation covers them in full (see this and this), but I’ll highlight the main ones. As you’ll see, each rule is written so that it returns an array.

The first, most obvious, restriction is to indicate that a field is required. Just use a comma-separated string of field names as the first returned value and the word required as the second:

array('name, email, subject, body', 'required'),

You can also specify that a value must be a number or, more specifically, an integer. This syntax is slightly different. Here, I indicate that the ext field must be an integer:

array('ext', 'numerical', 'integerOnly'=>true),

For strings, you can restrict the length to a maximum value:

array('name','length','max'=>40),

Or a minimum value:

array('name','length','min'=>6),

Or both:

array('name','length','min'=>6, 'max'=>40),

Another useful validation routine is to check that a string is an email address. I do that here, to a userEmail field:

array('userEmail', 'email'),

To indicate that a string needs to be a URL, use:

array('link', 'url'),

Another useful rule is for comparisons, like when a user registers and you have to make sure that the confirmed password matches the password:

array('password1', 'compare', 'compareAttribute'=>'password2', 'on'=>'register'),

There is also the “safe” rule. This rule is used to provide access to data that isn’t otherwise validated. For example, an email address is already considered to be “safe” because it must abide by the email rule, but the Employee Model has the leaveDate field which won’t have any rules applied to it (in part, because there are no date-specific rules and also because the field can be null). To be able to refer to that value, it must be declared as safe:

array('leaveDate', 'safe'),

If there are multiple fields to make safe, just separate them with commas.

There’s also a rule to indicate which fields should be safe to search on. By default, every rule is made safe in a search, but you may want to change that behavior by removing fields from the list:

array('id, departmentId, firstName, lastName, email, ext, hireDate, leaveDate', 'safe', 'on'=>'search'),

So, using this information, the complete rules() method for my Employee Model is:

public function rules()
{
    return array(
        array('departmentId, firstName, lastName, email, hireDate', 'required'),
        array('departmentId, ext', 'numerical', 'integerOnly'=>true),
        array('firstName', 'length', 'max'=>20),
        array('lastName', 'length', 'max'=>40),
        array('email', 'length', 'max'=>60),
        array('email', 'email'),
        array('leaveDate', 'safe'),
        array('id, departmentId, firstName, lastName, email, ext, hireDate, leaveDate', 'safe', 'on'=>'search'),
 );
}

Moving on, another key Model method is relations(), which indicates the relationship between Models. If your database is designed properly, this method will already be properly filled out, again thanks to Gii. Here’s how the relations() method in the Employee Model looks:

public function relations()
{
    return array('department' => array(self::BELONGS_TO, 'Department', 'departmentId') );
}

The relation is given a name, here department. The relation indicates that the departmentId column in the Employee Model (i.e., this one) belongs to the Department Model. Here’s how this will come into play: When loading the information for an employee, you can also load any of its relations. By doing so, references to department will equate to the Department Model record that is the employee’s department. So if the $model object represents the Employee being viewed, then $model->department->name would be the name of the department that the employee is associated with.

In the Department Model, this relation is defined:

public function relations()
{
    return array('employees' => array(self::HAS_MANY, 'Employee', 'departmentId') );
}

So if $model represents a specific Department being viewed, then $model->employees is an array of Employee objects, each of which representing one Employee in that department.

The relations between Models is a key player in complex MVC sites. Through properly defined relations, associated content can be retrieved. You’ll learn more about this in the next couple of posts.

Moving on, a more trivial, but still nice, method is attributeLabels(). This method returns an associative array of fields and the labels to use for those fields in forms, error messages, and so forth. The Yii framework does a great job of making these conversations automatically, like firstName becoming First Name and departmentId becoming just Department. But you may want to still customize these. For the Employee Model, here’s what I have:

public function attributeLabels()
{
    return array(
        'id' => 'Employee ID',
        'departmentId' => 'Department',
        'firstName' => 'First Name',
        'lastName' => 'Last Name',
        'email' => 'Email',
        'ext' => 'Ext',
        'hireDate' => 'Hire Date',
        'leaveDate' => 'Leave Date',
    );
}

So there’s a little bit of customizing you’ll want to do to your Models to start off. As I said, you’ll also add your own methods later on. And there’s some other Yii-specific methods that I do use often, like beforeSave(), which is code to be run before a Model is saved, and beforeValidate(), which is executed before validation takes place. This last method is useful if there’s some data manipulation you want to do behind the scenes before the Model is run through all the validation requirements. And there’s the search() method, which I’ll have to address in a separate post. But, the absolute most important Model functions are rules() and relations().

Series NavigationCreating Models, Views, and Controllers in YiiBasic View Edits in Yii

Posted in MySQL, PHP, Web Development.

Tagged with , , .


75 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Jose Reyes says

    Hi:

    This is a great tutorial, thank you. Regarding the relations() method, in my case Yii 1.0.10 generated an additional relationship from what you describe:

    Department model
    —————-
    ‘employees’=>array(self::HAS_MANY,’Employee’,'departmentId’)

    Employee model
    ————–
    ‘departments’=>array(self::HAS_MANY,’Department’,'deptHeadId’)

    Are these intended to establish the one-to-many/many-to-one relationships defined in the tables? Thanks.

    Jose

  2. Larry says

    Hello Jose. Thanks for your comments and my apologies for not replying sooner. Yes, those are to establish the relationships defined in the tables. The indication in the Department Model that each department has many employees is correct. However, the Employee relation is technically one-to-one, as each Employee might show up once in Department (as the department head) and each Department has only one Employee as a department head. This case, with these two Models, is a bit tricky as there are two relationships between the Models, which is less common (one relationship is the employees in a department, the other is the department head for the department). At the end of the day, though, how relations are defined in your Models really just impacts how you access related Models in Controllers and Views.

  3. Narinder says

    Thanks for great tutorials on yii. I have been mostly developing on java but want to try various rapid development platforms/languages and it looks like yii/php is one of them.

    One question I have on model editing is what if my model changes over time? Does that mean I will have to hand edit the model to add additional attributes? Because if I regenerated them, it will overwrite my changes? Or you think it is better to have an extended class that has the overridden behavior so that I can always regenerate my models when schema changes happen.

    Thanks.

    • Larry says

      Thanks for the feedback. This is a good question, by the way. When you’re absolutely new to PHP and YII, if you change the Model, you may want to use the command-line tools to have Yii auto-generate a new Model definition (like in a dummy version of the application). Over time, as you get comfortable with both PHP and Yii, you’ll have no problems just hand-editing the Model class file should/when you make Model changes later. I don’t think there’s a need to create a class to extend.

  4. Nima says

    Hi Larry,

    I would like to add a varchar field to my database

    Do you have any pointers on what I need to do when updating a model file to account for this addition?

    I don’t know if I can use the auto crud tool because the model file has already been updated.

    Best,
    Nima

    • Larry says

      If you haven’t modified the originally generated Model file, you can use the command-line tools to regenerate it. Otherwise you just need to make a couple of minor edits to the Model. You’ll also likely need to edit your Views, too.

  5. JustinJools says

    Wow, amazing tutorial. I had been putting off trying Yii after looking at other frameworks like Cake and CodeIgniter and having PHP nausea before starting, but I was so amazed and how easy this was to setup. I was convinced that Django was the most user friendly model but this seems at first try surprisingly easier. I think the days of hand coding whole PHP applications (and many headaches) will be a thing of the past :)

    Thanks for great tutorial!

    • Larry says

      Thanks for the nice words. I really appreciate it!

  6. Master says

    Hi Larry,
    again I am having one question. Is there any IDE which can integrate yii. I mean instead of going on command-prompt / terminal, it will be better if we can use some wizard type of thing where we will fill up some information and click next->next and everything will be done. And later on that IDE will allow a good text editor with intellisense to edit the code.
    Now I really like this framework. It’s time-saver and fast compare to code-ignitor that I was using from a long time. I am still reading your 8 post tutorial, now only 2 posts are remain to read .. I will soon finish both :)

    • Larry says

      Good question. Unfortunately I don’t know of an IDE with built-in support for Yii, but that doesn’t mean one doesn’t exist.

  7. walrus says

    I think you’re missing the first letter here mate… ;-)
    This is a really great tutorial, thanks again!!! =)

  8. Garry Freemyer says

    Ahh this is turning out to be a fine tutorial. In the above page, you show the final relationship given the above info but you leave out the line below …

    array(‘password1′, ‘compare’, ‘compareAttribute’=>’password2′, ‘on’=>’register’),

    I am not clear if this is an omission or do I need to put the above code somewhere else than the relations function?

    Also I note the poster asking if there is an IDE that supports Yii and I had just watched a video showing a fellow who used NetBeans ide to create a project from existing YII auto-generated code. Unless I’m missing something here, it appears that NetBeans was well up to the job as he used it throughout the video. I also remember reading recently that Netbeans has MVC support added in.

    • Larry says

      Thanks for the feedback and the comments. The password comparison would be a rule, not a relation, and it’s just an example. It wouldn’t be used in the employees-departments example I’m developing.

      Thanks for the heads-up on NetBeans. It’s a top-notch IDE (and it’s free!), so it wouldn’t surprise me if it supports Yii.

  9. prakash says

    Hi Larry,
    I have a table by name ‘Service Status’ in my database. How can i generate the necessary model and curd files from the command line.
    I am able to generate the model files using ‘model *’ but unable to generate the ‘CURD’ related files.

    Thanks & Regards,
    Prakash

  10. Jon says

    Enjoying your series of Yii posts.

    I’ve managed to do as instructed so far (apart from being able to add the correct comment to the employee table).

    I got to see the list pages for employee and department and I managed to add a department record but I get a CDbException when trying to add an employee record. Looking at the debug contents I see a warning:

    Failed to set unsafe attribute “hireDate”.
    in
    C:\Web\WebServer\Apache22\htdocs\yiitest\protected\controllers\EmployeeController.php
    (75)
    in C:\Web\WebServer\Apache22\htdocs\yiitest\index.php (13)

    Then some errors:

    exception ‘CDbException’ with message ‘CDbCommand failed to execute the SQL
    statement: SQLSTATE[HY000]: General error: 1292 Incorrect datetime value:
    ” for column ‘leaveDate’ at row 1′

    I’ve checked the table in phpMyAdmin and the leaveDate column is set to allow null values so I’m not sure what the problem is. Any pointers would be appreciated but I appreciate you probably didn’t write these articles with a view to holding everyone’s hand at each step :)

    p.s. I’m a bit confused as to why hireDate is set to be a required field – I thought the idea was that if it was left blank then the current timestamp would be used. I have tried making mine accept null values for that field also, otherwise is an admin expected to know and enter the current timestamp?

    • Larry says

      Thanks for the nice words. As for your dates, you need to make sure your Model definition doesn’t demand that they populated. That’s the hireDate issue. For the leaveDate, I expect you haven’t told MySQL to use the current timestamp for that field if the supplied value is NULL.

  11. Jon says

    Actually I have managed to get an employee record inserted now. I had to enter a leaving date!. Doesn’t seem quite right but at least it’s in. The question about the hireDate being a required field still applies though – what is the admin supposed to enter in here. In my successful record creation I typed in a random 11 digit number for hireDate to simulate some kind of timestamp but the created record actually used the current timestamp rather than mine anyway

  12. Jon says

    Thanks for your replies Larry. I’m gradually seeing the bigger picture with regards to yii and what we’re doing here :-) (It takes me some time!).

    One more question – where there is a relationship between tables (e.g. An employee belongs to a department) would you not expect the department field (when creating / editing an employee record) to be a drop down listing the available departments rather than an empty text field meaning you would have to manually enter the id of the department (which you wouldn’t know without going to the departments index and finding the id of the correct department there or some such)

    many thanks. I do like the way you explain things

  13. Jon says

    Sorted now. I found the answer in part 7 of your tutorial thanks :-)

    • Larry says

      You’re quite welcome. Thanks for the nice words.

  14. Jon says

    Gotta admit I’m still struggling with this hireDate field.

    Here is a screenshot of my employee table in PhpMyAdmin
    http://www.online-presence.com/yii_db.jpg

    and in my employee model these are the rules taht were auto-generated by the yii command line tools:

    public function rules()
    {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
    array(‘departmentId, firstName, lastName, email’, ‘required’),
    array(‘departmentId, ext’, ‘numerical’, ‘integerOnly’=>true),
    array(‘firstName’, ‘length’, ‘max’=>20),
    array(‘lastName’, ‘length’, ‘max’=>40),
    array(‘email’, ‘length’, ‘max’=>60),
    array(‘leaveDate’, ‘safe’),
    // The following rule is used by search().
    // Please remove those attributes that should not be searched.
    array(‘id, departmentId, firstName, lastName, email, ext, hireDate, leaveDate’, ‘safe’, ‘on’=>’search’),
    );
    }

    I noticed hireDate was not in there and tried adding a safe rule for hireDate but still get critical errors when trying to add a record.
    With your example should I be able to leave Hire date blank when adding an employee record?

    • Larry says

      That really depends upon how the database table is defined. I don’t know what version of MySQL you’re using, but you may have to add a secondary attribute to the hireDate column indicating that the CURRENT_TIMESTAMP should be used on INSERT. Or you can add code to your Model to automatically provide that information. I have that in this series somewhere, if not in this post.

  15. Tax says

    I like the good tutorial series. I have recently started learning Yii framework.

    With reference to User model and controller:

    array(‘password1′, ‘compare’, ‘compareAttribute’=>’password2′, ‘on’=>’register’)

    Yii’s CRUD generator generates one form for ‘create’. Do I need to manually generate the form for user registration? Where and how do I specify that Yii uses this ‘registration form’?

    • Larry says

      Thanks for the nice words. As for your question, you shouldn’t need to generate your own form: just take the CRUD-generated form and tweak it to your needs.

  16. William says

    Not sure if this comment belongs on this post or the database one, nevertheless…

    If I create a table, generate my models, but have neglected to include a comment defining a foreign key, and go back to do so, will re-generating the the model create the appropriate relations() function?

    And is this true of any such adjustment to a db table?

    My apologies if this question has been asked or covered in this or another post.

    • Larry says

      Thanks for your question. Unfortunately, I don’t have a good answer for you. I suspect that Yii will recreate the Model reflecting the changes, but that would mean any changes you made to the original Model would be wiped out. I think it’d be best to just define the relation yourself in the Model, rather than have Yii auto-generate it again.

  17. Fred says

    Many thanks for giving us this tutorial Larry, it’s very useful to a complete newbie like myself.

    Like other people I was getting MySQL errors relating to the date columns when I tried to enter a new employee. I had hireDate set in MySQL to not allow null but to default to CURRENT_TIMESTAMP. This is fine, but the app complains when you leave the form field blank. I was able to get around that by deleting hireDate from the list of required attributes in the Employee model. MySQL happily fills the column with the current timestamp when you give it a blank.

    Then MySQL complained the app was giving it the wrong kind of leaveDate, ”. Yii was passing it an empty string. The leaveDate column in the db allows nulls, but MySQL doesn’t accept ” as a null. After reading around I found you can get the model to pass a proper null whenever the form field’s blank by firstly adding this little function into the model..

    /**
    * @return null if value is empty string
    */
    public function empty2null($value)
    {
    return $value===” ? null : $value;
    }

    and then calling it by adding this line to the rules method..

    array(‘leaveDate’, ‘filter’, ‘filter’=>array($this, ‘empty2null’)),

    Hope this helps somebody else!

    Cheers
    Fred

    • Larry says

      Thanks for sharing what you learned, Fred. Much appreciated. And thanks for the nice words.

  18. alfian says

    Larry got alot of understanding after reading your tutorial keep writing about yii.

    thx alot for sharing

    • Larry says

      Thanks for the feedback and the nice words!

  19. Sinaru Gunawardena says

    I’m enjoying your articles.. :) ..
    Note: you have forget to use email rule for the employee email field…

    public function rules()
    {
    return array(
    ………
    array(‘email’, ‘length’, ‘max’=>60),
    array(‘email’,'email’), // <—————————-
    array('leaveDate', 'safe'),
    …..
    );
    }

    • Larry says

      Thanks for pointing that out and for the nice words. I fixed it.

  20. toki says

    Hi,

    I’m new to Yii and have followed this tutorial, which I found very helpful as a jump start.
    However, after CRUD creation I’m still able to add Employees of non-existing departments. For example I have one department (id=1 name=’DoD’), and add an employee with the Department = “2″.
    It passes without complaints.
    Does Yii rely solely on MySQL constraints, or can they be somehow added into the model class?

    thanks.

    • Larry says

      That doesn’t surprise me. Yii does not rely, at all, on MySQL constraints. In fact, MySQL doesn’t rely on constraints. Foreign key constraints are only supported in MySQL in more recent versions and when using specific storage engines (e.g., InnoDB).

      • toki says

        Thx 4 the quick reply.
        After I added the FK explicitly while creating the employee table, and specifying InnoDB, I managed to get a DB exception.

        My question was, however, does Yii implement the constraint checks at the model level automatically, while creating the CRUD. Does it in a way recognize the constraints and implements them in the code…

        But obviously, it is not.

  21. saikiran says

    i like your tutorial ,how to join two tables and retrieve records based on primary and foreign keys….

    • Larry says

      Thanks for the feedback. I gather there’s a question in there, but I’m not exactly sure what it is. It may be answered already, though, in this post.

  22. Subash says

    Hi Larry,

    Wonderful. I appreciate you writing this tutorial. As a token of appreciation and I purchased your php and mysql book and I am sure I will buy more and recommend your books. I have worked in large companies, where the documentation is non-existent or grossly outdated. I think the open source software is also working wonders for documentation and tutorials.

    A small typo on this page, I guess the word “conversation” should be “conversion”.

    Another item that could be very useful is a simple chart showing the directory structure and what each file is supposed to do. I understand it better now, but could be a very helpful aid for the new user/novice.

  23. yacine says

    Hi Larry !
    You have no idea how amazing those articles are for such a beginner like me , million thanks to you and Kudos for such nice work and effors . keep the good work !!!

    I have a question : When we have a many to many between 2 tables ( a and b ) relationship in a DB , we create a association table that has both primary keys of tabe a and b .
    Now my question is :
    Do we have to create a model for that part ( for the association table ) or is it automatically going to be handled by Yii ?

    Again many thanks!

    • Larry says

      You’re quite welcome and thanks for the nice words. I’m blushing. Good question about many-to-many relationships. I could be wrong on this, but I believe you do need to create the intermediary Model as there’d be no way to reference that underlying database table without it. (Well, not without using hand-coded SQL, which defeats the point.)

  24. ww says

    i get this error : Property “Department.name” is not defined.

    • Larry says

      That means your Department model doesn’t have a name attribute.

  25. Sohel says

    Thanks for your wonderful tutorial. I want to know the details about the search() method of the Employee Model. And how can i customized my search method??

    • Larry says

      You’re quite welcome. As for your question, just open the Employee model and take a look at what you see there. That’s actually a “scenario”, which I’ve posted about separately. But how you customize it depends upon what you’re trying to accomplish.

  26. Achim says

    Hi Larry,
    thanks a lot for this amazing tutorial, it really allows newbies like me to start working with this great framework.
    After reading up to this chapter (and browsing through the laters) I miss the definition of the attributes in the model classes. There are rules verifying them and i can access it from the views/controller but they are nowhere defined…
    I have even searched in the CActiveRecord base class, but it is generic and not depending from my database. So where do a Gii created active-record model class define the attributes????

    Thanks
    Achim

    • Larry says

      Hello Achim. The attributes are based upon the columns in the corresponding database table.

  27. Achim says

    Hi Larry again,
    so one more question I’m struggling at the moment. In one case you describe in the Employees model a relation BELONGS_TO, where the foreign-key (departmentId) is an attribute of the same model Employee. This works and seems to be logical.
    But on the other hand you describe in the Departments model a relation HAS_MANY, where the foreign-key (also departmentId) is now an attribute of the other model, Employee? To be symmetrical shouldn’t it be an attribute of the same model, so Department? or is this characteristic for the HAS_MANY relation?
    (I don’t found any documentation of the real meaning behind the foreign key attribute of relations())

    Thanks a lot
    Achim

    • Larry says

      Hello Achim. No, I believe it’s correct as is. Each Employee belongs to Department through the departmentId field. And each Department has many Employees through the departmentId field.

  28. Z says

    First I have to thank you for the great tutorial!! Then I’ll have to bother you with an issue that I have:

    I have a problem with the hireDate as well. I made it a required field and I added “date” validation. So whenever the user doesn’t enter a correct date it shows an error. In case that the date format is correct it adds the employee. The problem is that when I view the list of employees all of them have a hireDate of 0000. So for some reason it doesn’t save the hireDate. I know that it goes through the controller properly, because I can display the data that was submitted in the form. In my database I have the default value of the field as “CURRENT_TIMESTAMP”. I’m using a MySQL db.

    • Larry says

      Thanks for the nice words. As for your problem, I expect the data being submitted as the hireDate isn’t in the correct format for the column type.

      • Z says

        Sorry about the double posting there. A couple of times it said that I’ve already posted, when I haven’t then. It suddenly showed 2 posts.

        How can I specify a date format in the model file? I added a rule in the model file to check if the date is in the correct format, so I submit something like 04/19/2011 and it accepts it, but my database probably doesn’t like that (MySQL). What format is suitable? I have debugging on, how come it’s not showing any error or warning?

        thanks a lot!

        • Larry says

          It’s not showing any error or warning because there isn’t any error or warning. The Yii format check is working and MySQL is just not using the submitted value because it isn’t in the correct format (I presume). I forget offhand how you change the date format in the Model; it’s been a while since I’ve done that. You can, of course, search the Yii documentation or Google to find out for yourself.

          • Z says

            Yeah, I’ll figure it out. Thanks a lot!

  29. Boaz says

    small error in page: search for “after it’s been created by Yii’s command-line tools”. I guess you need to alter it to something along “after it’s been created by Gii (or the equivalent Yii command-line tools)”.

  30. Khairul says

    Hi Larry, I have a small issue with the relations method. I can’t seem to get it to automatically generate using my own tables. Here’s a simple breakdown:
    CREATE TABLE IF NOT EXISTS `jobdb` (
    `id` smallint(3) NOT NULL AUTO_INCREMENT,
    `name` varchar(100) NOT NULL,
    `desc` text,
    `classid` smallint(3) unsigned NOT NULL DEFAULT '0'
    COMMENT 'CONSTRAINT FOREIGN KEY (classid) REFERENCES jobdbclassification(id)',
    PRIMARY KEY (`id`)
    )

    CREATE TABLE IF NOT EXISTS `jobdbclassification` (
    `id` smallint(3) NOT NULL AUTO_INCREMENT,
    `name` varchar(50) NOT NULL,
    `classalpha` varchar(5) NOT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `classalpha` (`classalpha`)
    )

    I alter the comment as necessary but it does not work. I know I can just generate it on my own but when something does not work, I would like to know why and how to fix it. Plus it would be cumbersome to generate it on every table (I have 20+ tables with foreign keys).

    Is there something missing or something else I need to have/define?

    Thanks

  31. Prasanth says

    Thanks Larry .Great Yii Tutorial
    Thank you for sharing

    • Larry says

      You’re welcome, Prasanth. Thanks for the nice words.

  32. sohail says

    Hats off to you Larry, this is a great tutorial.
    Thank you so much for this.

  33. Vipin says

    I appreciate you for writing this tutorial. It was very helpfull.

  34. Jean-Pierre says

    Hi! this tutorial is great (and yii is great too). Many thanks Larry!

    However I have a problem with Date. I inserted this new rule in rules():

    array(‘hireDate, leaveDate’, ‘date’),

    and now I try to update an Employee record. I always get a date format error like ‘The format of Hire Date is invalid.’ for inputs like:
    2007/1/1
    9999-9-9
    9999-9-9 00:00:00

    what’s wrong?

    Also, you tell about the CLI command yiic which can be used instead of gii. Any help to that effect would be much appreciated because the tool built-in help is not very useful in that quest.

    • Larry says

      Thanks for the nice words. As for your first question, you need to use PHP and/or JavaScript to make sure that the user-provided date is of the right format. Or set the format in the rules. As for yiic, you haven’t really provided enough information here for me to answer the question, and the comments to a blog aren’t really a good spot for debugging help. If you need assistance, please use either my support forums or the Yii support forums.

    • Abdelaziz Bennouna says

      Hello
      To the risk of being redundant, thanks A LOT Larry for all your efforts in this tutorial and the rest of MVC/Yii-related posts. It made my day and I’ve elected Yii as the #1 PHP framework for my business needs.
      @Jean-Pierre, the default date type is ‘MM/dd/yyyy’ (http://www.yiiframework.com/wiki/56/). If you want a different format, e.g. without leading zeros, you use:
      array('hireDate, leaveDate', 'date', 'format'=>'M/d/yyyy'),
      Like many posters, I’ve noticed that MySQL doesn’t store anything with the default code. So we have to convert the date to the DB’s one. In my case, it’s yyyy-MM-dd HH:mm:ss.
      Check http://stackoverflow.com/questions/5137988/yii-date-hour-minute-datetime-string-mysql-datetime for an implementation.

      • Larry says

        Thanks, Abdelaziz, for the nice words and for helping out!

  35. B says

    Wow, this tutorial is exactly what I’ve been missing in the MVC framework world. I’ve struggled through CodeIgnitor and Zend and could barely understand what I was trying to do. You’ve made it very clear and I appreciate it! Thank you!

    B

  36. B Dutta says

    Each of the tutorials in the series, holds up to the promise of being clear, focussed and simple.

    Reading some of the comments here I understand that the following rule, is not required in the Emp-Dept example that this tutorial uses as a basis, but is it possible to elaborate the usage a bit more, especially because usage of fieldnames like ‘password1′ and ‘password2′ gives the impression that both come from Table, while, I believe one would come from table (stored during registration), and the other is from the Login validation form ?

    array(‘password1′, ‘compare’, ‘compareAttribute’=>’password2′, ‘on’=>’register’),

    Anyhow, I know that I am demanding without probably being sufficiently grateful. Maybe if you plan another update sometime.

    • Larry says

      Neither password1 nor password2 are part of the table, but by adding that line, you can virtually create those properties and apply a validation rule to them.

If you need quick assistance with a question or problem related to one of my books, please use the support forums instead.

Some HTML is OK

or, reply to this post via trackback.