Basic View Edits in Yii

November 12, 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 7 of 8 in the series Learning the Yii Framework

This is the seventh post in my series on Yii, my favorite PHP framework. In this post, I walk through some basic View edits you’ll make to the code auto-generated by the Yii framework. 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.)

When you use the command-line and Gii tools to create a new Web application, the Yii framework generates a series of files and folders for you, from configuration files to controllers to Views. The Views are a series of PHP scripts, organized by folder. The first one you’ll want to edit is protected/views/layouts/main.php (where protected is the root application directory). This is the template for every page within the application. You’ll likely want to change most of the file to create your own look, but I want to highlight a few key points.

To start in the HEAD, you’ll see that external files are linked using

<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/main.css" />

Whenever you see Yii::app(), that refers to the Web application as a whole. You can access information about the user viewing a page, about the current or previously-viewed page, etc., there. Yii::app()->request specifically references the current page being accessed (or requested). The ->baseUrl part refers to the root URL for the application, like You should use Yii::app()->request->baseUrl for references to external files—CSS, JavaScript, images, and so forth—as the relative path to them can become muddled with the changed Yii URLs (like

Next, you’ll see the page’s title set dynamically:

<title><?php echo CHtml::encode($this->pageTitle); ?></title>

By default, the pageTitle value will be the application’s name (defined in the config file) plus something about the current page. Later on, I’ll show you how to change this. The CHtml::encode() method is just used to protect against Cross-Site Scripting (XSS) attacks. You’ll see it used liberally (and appropriately) in the View files.

You’ll also see in the main layout file:

<div id="logo"><?php echo CHtml::encode(Yii::app()->name); ?></div>

Yii::app()->name is the name of the Web application, as established in the config/main.php file. You may or may not want to use it in your Views, but that’s where the value comes from.

Next up, the default layout uses a widget:

<?php $this->widget('zii.widgets.CMenu',array(...

Widgets are a way to include a nugget of PHP code in a View using an external file. They’re best for things that aren’t tied to specific Views and that you may want to drop in anywhere. Plus it allows you to further separate out chunks of code for easier management and portability. The above code says that the CMenu widget should be dropped in here. That widget is part of the Zii extension (to the Yii framework). For more on widgets, see the Yii documentation.

Edit for Yii 1.1: Yii 1.1 took a bunch of the best extensions and placed them in their own namespace, zii. Whereas earlier versions of Yii created a MainMenu component, Yii 1.1 uses the CMenu widget. The default layout also makes use of the CBreadcrumbs widget, include in the Zii extensions.

Finally, the layout script has this line, which is the most important:

<?php echo $content; ?>

Now you won’t find a reference to the $content variable anywhere in your code and do note that it’s just $content, not $this->content or $model->content. This is where the page-specific content gets inserted into the layout. All the other HTML and PHP is the template for the entire site; the value of $content is what makes pageX different from pageY. So where does it come from?

Tip: The exact structure of the URLs will depend upon whether you’ve enabled urlManager or not and, if so, how it’s configured. See the post on configuring Yii for more.

If you’re viewing a page like, which is intended to show the employee with an ID of 1, the actionView() method of the EmployeeController class is called. That method loads the Employee Model with a primary key of 1, then renders the view View, passing along the Model in the process. That code is (this is from protected/controllers/EmployeeController.php):

public function actionView($id)

The loadModel() method of this Controller class does the actual Model retrieval, and I won’t worry about that right now, but the $this->render() part says to render the View to be named, in this case, view. That means that Yii will execute the PHP script protected/views/employee/view.php. That script uses a $model variable (passed in the above code) to display information about the employee within some context (specifically, view.php script uses zii.widgets.CDetailView to list the details) . The result of this executed View script is, behind the scenes, assigned to $content, and therefore dropped into the appropriate place in the layout. That’s how the system works.

One last thing about the layout scripts is that you can easily have different layouts for different sections of the application. To do so, in the Controller method, change the layout value before rendering the view. Provide the name of the layout file, minus the extension. So this line says to use protected/views/layouts/home.php for the index action:

class SiteController extends CController
    public function actionIndex()
        $this->layout = 'home';

In fact, as of Y 1.1.?, the framework creates both one column and two column layouts, each of which use the main.php template file. The Controller then indicates which layout to use for the entire Controller:

class EmployeeController extends Controller
    public $layout='//layouts/column2';

Note: $this->layout within a class method is equivalent to just public $layout outside of any method (as in the above code). The first example changes the layout for a specific action; the second for the Controller as a whole.

Moving on to the View scripts, one of the first things I normally do is change the basic formatting to whatever you’re looking for. For example, the default appearance of a show View is a table of information about the Model: labels and values. Normally you don’t want to show all of the Model data, and you’ll display it in DIVs or paragraphs. These are simple edits. As the above code shows, the Model information will be passed under the name model, so you can use $model->whatever to access the values of the different fields.

Edits for Yii 1.1: There are a number of View file changes, although none that are dramatic: What was previously the list (list.php) View file is now index (index.php). The index page makes use of a CListView widget to list the records. The admin page makes use of a CGridView widget to display all the records. The show file (show.php) is now called view (view.php). It makes use of the CDetailView widget to show the information for a specific record. Multiple View files can make use of the _view.php script, which is a template for showing an individual record. Every view file identifies breadcrumb information at the top, which will tie into the CBreadcrumbs widget referenced in the main layout file.

Tip: If you log into the site (using admin/admin if you haven’t changed the login system) and then go to, you can already create a few department records to make better sense of what I write below.

The index and admin Views both show multiple Model records, using Zii widgets. index.php uses the CListView widget, using the _view.php script as the template. If you edit either _view.php or how CListView is configured (in index.php), you’ll change the listings. The admin page, accessed by clicking on “Manage XXX”, uses the CGridView widget. This widget creates a table of data, with links to view, edit, or delete specific records. The table can be paginated and searched, using Ajax. It’s really sharp and a great demonstration of how much Yii will do for you. This figure shows the departments listing, without having made any changes to what Yii created:

Department Admin Page

Department Admin Page

The create and update Views have some page header stuff, then include the form View, using this code:

<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>

That code renders a partial View in that place, passing along the Model information to _form.php.

Looking at the generated code, the Department form is fine, as it just provides an input for the department’s name. For the Employee Model, however, there’s some customization you’ll need to do there. You can check it out by heading to

By default, the forms generated by Gii includes elements for every Model attribute, save for the primary key. But some fields, like the dates created or modified, may be automatically populated with timestamps, and therefore aren’t inputted by the users. And, with related Models, like Employee and Department, you’ll end up needing a drop-down menu in the one to select a value from the other, like choosing what department an employee is in. The Yii-generated code won’t do this for you; the form will just have a text field created by this code:

<?php echo $form->textField($model,'departmentId'); ?>

The $form variable is an object of CActiveForm type. The textField() method creates a text input. The first argument says that the input should be for the $model object (which is the current Model instance, coming from the Controller). The second argument identifies the property in the Model that this element is for.

To create a drop-down associated with another Model, you’d replace that code with:

<?php echo $form->dropDownList($model,'departmentId', CHtml::listData(Department::model()->findAll(), 'id', 'name')); ?>

First, the dropDownList() method of the $form object creates a drop-down list. You need to tie it to the form-associated Model, so the first argument is just $model, the same variable passed to this View when it’s rendered. The second argument is the name of the form field/Model field: here, the departmentId field in the Employee Model. Next, you need to provide the method with the list of values to use for the drop-down menu, which is achieved by calling CHtml::listData(). That method returns a list of values that are usable in drop down menus. Its data source should be the list of Departments. To retrieve those, use Yii’s approach for retrieving all the records in a Model: ModelName::model()->findAll(). So to fetch every department, use Department::model()->findAll(). The final two arguments (to the CHtml::listData() method) are the fields to use for the drop-down menu’s value and displayed text. Those should be id (the department’s ID) and name.

Another thing you’ll want to do in all your View files is remove or edit the links to the different admin features.

Finally, you may decide you want to change the page’s title. To do that, use code like:

<?php $this->pageTitle = $model->something; ?>

Note that you’re assigning a value to $this->pageTitle here, not $model->pageTitle, but you’ll likely use the contents of $model, like a title or name field, as the page title value. You can also still add in the application name, if you want, by concatenating in Yii::app()->name.

Whew! So that’s my whirlwind tour of basic View edits you’ll want to make to a fresh Yii application. In my next post, I’ll discuss basic Controller edits, of which there are surprisingly few, I find. As always, thanks for reading what I have to say and do let me know if you have any questions or comments.

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 Basic View Edits in Yii

  1. Hi,

    This is the first time I am writing you. I was a silent follower. I want to thank you for all your efforts spent for simplifying even the most complicated topics. I am new and my biggest guide is your books and your blog.

    My question is where to copy dropdownlist code. I tried in view, controller and form. Maybe I did something wrong.

    Best Regards,

    • Thanks for your post and for the nice words. That code goes into the _form.php file, in the place of the existing code (that creates a simple text input).

      • Hello sir. i am new to yii framework. you tutorial is excellent in guiding me. thank you for that.
        basiclly i want to get data from a database into a dropdownlist. i cant uderstand how to do it. kinldy helpme

        • Thanks for the nice words. I write about this very idea in this post. If you need more help than that, please either use my support forums or Yii’s support forums.

          • Thank you for your reply sir I have 1 question
            I have Society as parent table and Block as Child table.
            Society had “id” as primary key with autoincrement.
            Block has Society_id as a normal field with not null constraint.
            I have associated “Society_id” as referencial key with “id” feild of Society table.
            the following i worte but its not wirking sir.
            dropDownList($model, ‘Society’, CHtml::listData(Society::model()->findAll(), ‘id’, ‘society_id’));?>

            kindly help me sir

          • If you need help debugging this problem, please use my support forum or the Yii support forum. The comments to a blog posting isn’t really a good place for debugging help.

  2. Hey, these are really good walkthroughs!

  3. Keep up the good work! Your tutorials show the light in the end of tunnel! :-)

  4. I have a question: How do you make listData use two or more columns for the text field, for example when you need to display both firstName and lastName from the related table?

    • Interesting question and I’m not certain of the answer off the top of my head. My inclination would be to use, instead of just ‘name’ for the third argument to listData(), you would use either ‘lastName, firstName’ or ‘lastName’ . ‘, ‘ . ‘firstName’. Please let me know if either of those works for you.

      • hello larry i am a developer in i have two tables country and state where i have given three columns id,sname and cid and cid will refer to id of country table which consists of id and cname as its i have to create a dropdown list saying if i select a country i should get states under can you please help me with the code or just guide me through that.

        • Okay, what you want to do, if I understand you correctly, is create a dependent drop-down. There are tutorials for doing this on the Yii site.

  5. This works:
    findAll(), ‘id’, ‘first_name’))); ?>

    This does not work, throws an exception:
    findAll(), ‘id’, ‘first_name, last_name’))); ?>

    This doesn’t work either, the contents inside the generated OPTION tag is empty. However the value for the option reflects the custimer_id as it should.
    findAll(), ‘id’, ‘first_name.last_name’))); ?>

    I actually DID read the docs, but listData doesn’t seem to support this. The “dot” notation in the last example seems to be something else than field concatenation, but I don’t really understand what the API is saying about it.

    I’m thinking there’s another recommended way to do this. Would it be maybe to just add a property/attribute full_name to the Customer model, and make a getter for it that concatenates first_name and last_name, and use full_name with listData instead of first_name? :)

    • Yeah, the idea of making a getter that returns what you want was what I was also going to recommend if that didn’t work.

    • from the exception that was thrown when fed findAll(), ‘id’, ‘first_name, last_name’)));
      It is using that argument parameter as a property of the Model object, and since that property doesn’t exist, it throws an error.

      I don’t see how you would be able to modify the customer model, because it is getting all it’s data from the Active Record model. I’ll have to read more about this & check the Yii forums.

      • I was able to fudge it by using
        findAllBySql(‘select *, concat(last_name,”, “, first_name) as last_name from customer’), ‘id’,’last_name’)

        by using an SQL statement to join the two together and assign it an existing model property.

        It’s probably not the best way to do it…

  6. Thanx for such a good and thorough tutorial!

  7. Hi, and thanks for taking the time to write this tutorial.

    Most of it is very well constructed and thoroughly explained, but I feel that, towards the end of it, you begin to “forget” that most of your readers are not really familiarized with Yii’s methods, and they might get lost in some of your samples.

    For example, you lost me at

    pageTitle=$model->something; ?>

    I do want to be able to change the page’s titles (into something more search-engine friendly / customized), but I can’t seem to understand where (and how) should I use this particular piece of code.

    The rest of it, so far, was pretty much well explained, and I had no real problems following your tutorial… :)

    Thanks again!

    • Thanks for your feedback. Sorry about the confusion. To start, as this is a post on Views, that code goes in a View file. In fact, just above that I say “another thing you’ll want to do in your View files…”. So that code, for changing the page’s title, can go anywhere in a View file. As I say just after that line, you’ll likely use the contents of $model to set this value, at least in part. $model is a variable that a View often has that stores some information in object form. As an example, the View file that shows an individual employee record can access that employee information in $model (this is passed to the View and assigned as $model in the Controller). If the Model has a ‘name’ attribute, you might then use $model->name as the value for the page title. I hope that’s a bit more clear.

  8. Yup, you’ve made it clear, now :)
    Thanks, and sorry for missing those “hints” (it was quite late when I was reading your tutorial…).

    So another example would be
    $this->pageTitle = ‘View details on ‘ . $model->firstName . ‘ ‘ . $model->lastName;
    (placed in the show.php employee view file).

  9. Can you explain how to extend the model in the way you mentioned above to be able to get a dropdown for employee in the departmenthead that includes fullname… I tried declaring a new private var fullname and assigning it to the concat of the other properties in the instantiation, but that did not work.

    • Sure, in Employee.php, you’d define this function:
      public function getFullName() {
      return $this->firstName . ‘ ‘ . $this->lastName;
      Then, any time you have an Employee model, you can use $model->getFullName().

  10. Hi,

    Your activeDropDownList is an excellent work that help me a lot.Now I am in a deep trouble to show a chained dropdown list. I need a dropdown list to select a country, while click on that next dropdown list must show only the states of selected country. I tried some examples but I didn’t get the solution can you please help me?

    • Thanks for the nice words. The comments section of a blog isn’t really a good place to post tons of code and do debugging, so I’ve edited your comment. If you need help, I would recommend the Yii forums or my own forums. However, I would consider using one of the extensions that exist for dynamically adjusting one dropdown menu based upon the selection in another. Or I think there are cookbook recipes for how to do this.

  11. Garry Freemyer April 29, 2010 at 6:44 pm

    This tutorial is really looking good. Some confusion towards the end, but I would not have learned to look for _form.php in the proper directory had I not put the dropdown in the employee/_form.php … Couple things to note…

    The label “Dept Head” seems a bit vague unless you made the text box a check box to make it clear what it’s purpose is.

    I note that I was able to enter dates in the wrong format “MM/DD/YYYY” instead of “YYYY/MM/DD” and the data entered was not accepted and stored, and I did not receive an error message. Did I miss something? Is the framework leaving error checking of this to the user, and if so, where might we handle this and how? Thanks again for the outstanding tutorial

    • Hello Garry. Thanks for the nice words. I’m glad the tutorial was helpful. I’m not exactly sure what you mean about the “Dept Head” label, as it doesn’t seem to be in this post at all. As for dates, I suspect the issue is that there’s no PHP or HTML date type, so you have to use a string value for it, and the string can be anything (resulting in an empty value in the database). The fix, to have the framework validate that, would be to add a rule to the Model. I don’t remember if there’s a date-specific rule available. If not, I would create a beforeSave() method in the Model. Then, in that beforeSave() method, create the PHP code that confirms that the date is in the right format (and is maybe even a proper date). So the beforeSave() method would perform the validation on the date, if it doesn’t pass the test, then set the date value to an empty string, in which case the data would no longer pass the rule. Let me know if that doesn’t make sense.

  12. Hello Larry,

    this is really a nice tutorial for amateurs. I have a question for you can you please tell me how can I add “select a Department” option with empty value so if any of the person is adding employee system will enforce them to select the Department otherwise what happens if by mistake user don’t pay attention on the department and by default first selected department will be added. somehow this is not a big deal user can update that employee too but this will be good if system will prompt that you have to select the Department. also there is another thing that how can I sort List Items order by name? thanks

    • Thanks for the nice words. As for adding a “Select a Department” option to the drop-down menu, I’m not sure if this is the best solution, but what I did (in a similar case) was add a method to a Model that returned an array of all the items from the database, plus the added one:
      public function getDepartments() {
      $list[0] = 'Select a Department';
      $departments = Departments::model()->findAll();
      foreach ($departments as $dept) {
      $list[$dept->id] = $dept->name;
      return $list;

      Then you would use $employees->getDepartments() as the source for the activeDropDownList. Note that this method would be defined in the Employees Model, as it’d be used in the add/update Employees form.

      To sort list items in a given order, you can either add criteria to the selection query in the Controller or you can add a defaultScope() method to the Model that defines the default order.

  13. Very good info with these Yii posts. Thanks!

    About dropdown ‘default’ select, here is the solution:

    $form->dropDownList($model,’Category’,Cats::items(), array(‘prompt’=>’Select Category’));

    Of course, the string can be accessed from the model via:
    $form->labelEx($model,’select_cat’); //for example


    • Thanks for the nice words and thanks for sharing. Your solution is much better than mine. Had I only check the documentation myself! So the fourth argument to dropDownList() is an array of HTML options, one of which can be a prompt, which will be displayed as the first item in the list. Thanks again for the note.

  14. Hi Larry,

    How do i insert for 3 graphic picture into the CMenu
    based on the following code.

    widget(‘zii.widgets.CMenu’,array( ‘items’=>array(
    array(‘label’=>’Home’, ‘url’=>array(‘/index/index’)),
    array(‘label’=>’Company’, ‘url’=>array(‘/company/index’), ‘visible’=>!Yii::app()->user->isGuest),
    array(‘label’=>’Package’, ‘url’=>array(‘/package/index’), ‘visible’=>!Yii::app()->user->isGuest),
    array(‘label’=>’Supervisor’, ‘url’=>array(‘/supervisor/index’), ‘visible’=>!Yii::app()->user->isGuest),
    array(‘label’=>’Group’, ‘url’=>array(‘/group/index’), ‘visible’=>!Yii::app()->user->isGuest),
    array(‘label’=>’SIM’, ‘url’=>array(‘/customer/index’), ‘visible’=>!Yii::app()->user->isGuest),
    array(‘label’=>’Fence’, ‘url’=>array(‘/fence/index’), ‘visible’=>!Yii::app()->user->isGuest),
    // array(‘label’=>’FenceCell’, ‘url’=>array(‘/fenceCell/index’), ‘visible’=>!Yii::app()->user->isGuest),
    array(‘label’=>’Job’, ‘url’=>array(‘/job/index’), ‘visible’=>!Yii::app()->user->isGuest),
    array(‘label’=>’Login’, ‘url’=>array(‘/auth/login’), ‘visible’=>Yii::app()->user->isGuest),
    array(‘label’=>’Logout (‘.Yii::app()->user->name.’)’, ‘url’=>array(‘/auth/logout’), ‘visible’=>!Yii::app()->user->isGuest)
    )); ?>

    Can I add 3 graphic picture into this CMenu?

  15. Hi Larry,

    This 3 picture will be the image that I wanted to put into each of the menu option bar from the CMenu.

    Thanks you.

  16. Larry,

    I want to have a dashboard on my main page (webapp/protected/views/site/index.php) and access snapshot of data from various models. for example ..

    partial view 1

    partial view 2

    Can you explain me how to do that. This page does not have any controller (other than the siteController). The purpose of this page is to be a jumping point to other interesting views.


    • Offhand, I would think that the best route would be to create a widget that will do this for you. You can then add the logic to the widget to display the partial views accordingly.

  17. Larry,

    Thanks. Will try to do it and publish here.

  18. I must say that i have read almost all the documentation of cakephp and almost half of the documentation of symfony! I m a very experienced developer in many platforms and languages BUT for different reasons i wanted to scream reading the tutorials of those two.

    For example: symfony tutorial starts an application and all the time keeps coming back testing and correcting things! DISASTER!!!!! This is a crime for an educational text. Cakephp almost made me feel stupid as the level was getting higher and higher!

    I do like the tutorial that you write because you stay simple and you touch in a simple way all the things that someone needs! I hope that i will manage to use Yii at the end and that i will get disappointed. So far i m very positive!

    • Thanks for your feedback and I hope Yii works for you. I haven’t personally used either of those, so I don’t have experience with their documentation. But I can say that I found the documentation for the Zend Framework to be fairly comprehensive, but still not that easy to use! So it’s tough to find that middle ground for any piece of software.

  19. I am trying to move from CodeIgniter to Yii, now I am regretting my decision, since I have lost hours on learning Yii. It is not easy to manage some entry level features, in my opinion.

    My test drive project on Yii is simple, a Google map based image file distribution to nearby chain stores. It has some simple requirements:

    1) JavaScript Google API v2
    2) BlueCSS
    3) jQuery plugins.

    Above features can be implemented in CI in hours. So easy, so simple. However I found I can not find my way to design such service with Yii as easy as I did in CI. I believe it can be done, however document is not enough, I read enough tutorial, guide, code snippet. I still confused.

    1) JS code is not installed in a separate folder, Yii use publish method to copy the JS to the unprotected web folder, and I can not find any code to register and copy JS code to this folder in the demo projects. I know putting JS in source folder, then copy them have many extra features. However it just confuses me. As a beginner, I prefer to place them together. (default behavior is registerScript)

    2) Layout and View. I made additional layout since I put Goolge API JS in the head section, placed as map.php. Finally I found although we can define col1.php, col2.php and col3.php with main.php, but I found my map.php missing some , still I have no ideas how to make it right.

    Although these questions are very basic, I can not find any samples to explain how to deal with it. I mean, in traditionally way. I don’t have enough time to trace the framework myself. I just losing time.

    At last, Yii’s demo is lousy. The Yii_Playground is good, yet not a complete one.

    • Instead of spending your time complaining about Yii, why don’t you just stick with CodeIgniter? If you were happy with CodeIgniter, I can’t imagine why you’d force yourself to learn a new framework, especially one that you’re clearly having difficulties with. If doing this sample project in CodeIgniter is “so easy, so simple”, then do it in CodeIgniter.

  20. Hi Larry,

    Going back to comment #17 (sorry :)) I’ve got that function in my employee model but how do you actually use that when populating the departmentHeadId dropdown options?

    I guess I’m asking what goes in the textField parameter of the CHtml::listData() function:

    echo CHtml::activeDropDownList($model, ‘deptHeadId’, CHtml::listData(Employee::model()->findAll(), ‘id’, ‘what_goes_here?’));
    Thanks again

    • Good question and I don’t know the answer 100% for certain off the top of my head. Maybe getFullName()? If that doesn’t work and you can’t figure it out, I’ll look into this more.

  21. Aye the problem I’m having is that I don’t have an instance of employee at the time of this call I think (seeing as I’m in the department model) so i can’t see how I can use the employee’s getFullName function. It would need to be run on each employee as the list was populated somehow?

    • Well, you’d have an instance of Employee for each item in the drop-down list, so, yes, it’d need to be run as the list is created. I forget if or how that’s possible.

  22. Most useful of all the Yii documentation I’ve seen. Thanks for taking the time to write it.

    My database has some one-many, and a few many-to-many table relationships. I can make changes at the view level (I’ve successfully used dropdown), but I’d like to understand where the best place to make the switch is from the ID of the related table and its name.

    I don’t want the ID that link to the related table to show up anywhere on views or forms, only the name.

    You’ve mentioned making changes in the model.

    I guess what I’m looking for is suggestions on the optimum set of changes to make in order to “hide” the related table ids.

    In this case the mySQL tables are Gadget and GadgetMaker where GadgetMaker has many Gadgets, linked by id_mak, but what I want to see is name_mak.

    • Thank you very much, Mark. If I get some spare time, maybe I’ll develop a full-on book about Yii. I’m not sure I’m following your question. You don’t want the ID of the related table to be visible in the drop-down or you don’t want it to be visible even in the HTML source? Normally what you need to do in these situations is use the ID as the value of the drop-down menu and use the name as the displayed label, which I think is what I do in this post.

  23. Hii! Larry thanks for ur blogs on Yii. I am new to this framework but your continuous effort helped me a lot. I am developing an application in which i have to manage huge amount of teachers along with their specified fields and managing them for various training portals.. So i hope you will help me out in this.


    • You’re quite welcome. Thanks for the nice words. I will happy to be assist you as best I can. Just keep in mind that the comments section to a blog isn’t the best place to post lots of code or really complex questions.

  24. Hii Larry i am trying to write web service for my application can you guide me how to start with?? And do me a favor by telling me where to post my queries for you to have quick response!?


    • I can’t guarantee you a quick response. I’m just one person and I’m in the middle of writing a book, so I’m extremely busy. If you were to use, however, the Yii forums, you’d make your questions available for numerous people to answer.

      As for the Web service question, that’s lacking any details to provide a concrete answer, but you could like on my post on Yii with Flash. I used Web services in that project and I talked about how to implement Web services in Yii.

  25. Ok thanks Larry i checked your post and i will tell you about it in detail! I quite understand your work load, please just let me know when your book release date is??
    thanks for your comments and posts. It really helped a lot!!


    • The book will be out in November, I expect. It’s titled “Effortless E-commerce with PHP and MySQL”. I’ll continue to post updates about it here. Thanks for your interest!

  26. Great tutorial! Thanks for the considerable effort this has to have taken.

    I’m beginning to use this to maintain a club roster. I need to restrict users to viewing/editing only their own records while admins will be able to edit all. I’d appreciate a short comment on where that rule might be placed/enforced.


  27. hi … this is good site for new learners..
    I have some doubt in yii.. can you please help me?
    i have some values in my view.i want those values in my controller . when i click an ajax submit button. can you please help me in this with some methods..

    • You’re questions really too vague for me to provide a detailed answer. And the comments to a blog post isn’t really the best place for this kind of help. Have you tried the Yii support forums?

  28. Hi Larry, nice tutorial there. I want to ask about how to change the design significantly.
    How to change the header menu?header image?whole design?
    How to change the design to something we have designed in photoshop?

    • Thanks for the nice words. As I say in the third paragraph of this post, protected/views/layouts/main.php controls the layout of every page in the site.

  29. Back to Jon’s problem (esp. comment #36). I had exactly the same issue and found this:

    Summarizing – if you have getFullName function defined in your model, just put ‘FullName’ as last argument of listData function. Worked with me perfectly.

  30. Larry, I find your blog extremely useful, so big thanks for your effort.

    I can’t figure out, how to display name instead of id in index view (ie. on a list of employees with their departments id’s I’d rather have department names). I have relations defined and tried a few ways, no success so far.

    • Thanks, Pawel. You’re welcome and I’m glad you’re finding it useful. Hard to answer your question precisely given the information provided, but basically it’d be a matter of using $model->name. If you’re trying to display information about a related model, you’d use $model->relation->name.

  31. Hi Larry, how do I put status name instead of status id in view blog?

  32. On post page as “http://localhost/blog/index.php?r=post”. This page shows:
    Content:This blog system is developed using Yii.
    Tag:yii, blog
    Status:2 <= How can I change "2" to Status description?


    • Okay, I haven’t looked at the blog example in some time. It seems that those status values correlate to constants defined in the Post Model. I don’t know offhand if there’s a way to get the description from the number.

  33. I must say, great guide on the yii framework. I have just read all the posts and it was very helpfull since i just started exploring yii framework :)

  34. Muchas gracias por tu ayuda, una guía perfecta para iniciarse.

    Sigue así :D

  35. Hi Larry,
    You are doing a great job by sharing your knowledge with us people. I am getting back at programming after some 7 years and have chosen php as the programming tool. I see that there’s a lot to learn but the problem is that I want to go rapidly and do not have much time to work on it. Can you suggest me some tips what will help me progress rapidly.What are the classes that I need to study first in order to get going. The rest, I presume, I can do it gradually.

    I have a problem with a table of products where the primary key is the code of theproduct of type char and which is not autoincrement. Yii’s generated code considers it as autoincrement and does not allow me to input the code when I create a new product. Also I get a 404 error when I click on the code in the list operations. Can you please help me? I also wish to know if it is possible to change the look of the application written with Yii or will all applications look alike as far as the interfaces are concerned?

    • Hello Julia. Thank you for the feedback and for the nice words. As for your question, if you’re specifically looking to learn Yii as fast as possible, the base Model, View, and Controller classes are key, as are the HTML and form classes. As for using a CHAR as the primary key, I’ve not been in a situation where I’ve used Yii for such a table, so I don’t have an answer for you on that. Maybe there are some Model rules you can change? As for the 404 error, what URL gives you that error? As for changing the look of the application, you can definitely do that with ease. You can edit the layout and other View files to change the look for an application. If you’d like to change the default look for all new Yii-generated applications, you can edit the template files that come with the framework. Cheers!

      • Hi Larry,
        Thank you very much for your answer. I marvel at your readiness to help the way you do.
        The URL is : ….index.php?r=products/view&id= XYZ. My table is named is products and the product code (primary key) is XYZ. The equivalent URL for the employee example (…index.php?r=employee/view&id = 1) works fine and gives me a view of that particular employee where I can do the CRUD operations. Thanks for your answer. Can I send communicate by email with you?

        • Hello Julia. Thanks for the nice words. I find that answering people’s questions makes me a better writer and teacher, though, as I get a better sense of what it’s like to be on the other side. Yes, you can communicate with me by email. But if you’re looking for technical support/answers to questions, understand that it’ll be maybe 2 weeks before I reply. Technical support and questions are best addressed in my support forums. If a question or issue is particular to a specific post, I can try to answer it in these comments, but there are limits to how practical that is. The main thing is this: If you ask a question in a public way (i.e., online), then my answer will be available to anyone, and that’s of a huge value.

          As for your question, that URL should not be giving you a 404 error, unless the host is incorrect. Is it a server error or a Yii error you’re seeing?

          • Hi Larry,

            It’s a Yii error message. I know I found this code in one of the php files but can’t trace it now. I badly need your help. This problem is hindering my progress. Thank you very much

          • Okay, so then there’s a mismatch between the requesting URL and the Yii code. The options are: 1) There’s no matching controller. 2) There’s no matching action in that controller. 3) If applicable (which I think would be in your case), the loadModel() method of the controller isn’t loading a single model. I suspect that’s the problem in your case. You can enable Web logging to help see what’s going on. Also, some simple echo statements in the controllers and actions will help you confirm what is or is not happening (that’s basic PHP debugging stuff you should get in the habit of using).

      • Hi Larry,

        I forgot to ask you: can you please tell me the folders containing the classes you mentioned were important for me to learn. Thanks.

  36. I love your articles. I’ve spent about 4 hours with Yii and have gotten much farther than I’ve gotten with CakePHP after months of tinkering. I’ve been procedurally programming in PHP for years, and am extremely comfortable with OOP in general from Java and C++, so I thought I would take naturally to any MVC framework I picked. In CakePHP I found it difficult to manage something as basic as modifying the view to accommodate a dropdown for those one->many relationships. Like Yii, the defaults when using “cake bake” (cake’s equivalent to yiic) are almost all text boxes which clearlyisn’t what is called for in this situation, but your explanation jumps right to the obvious need and I find that understanding of basic necessities lacking in the CakePHP community.

    So, I’m officially a Yii convert. Thanks!

    • Hello David. Thanks for the nice words. I’m glad you like Yii and my writing. You know, some people wonder why I prefer Yii or why they should use it, let alone switch to it, and it’s really just a matter of what works for you. Yii works for me, and it seems to work for you, too. Best wishes!

  37. Thanks larry for these wonderful posts.
    Read all these posts, learned while working on the code and voila., I could make my first simple yii app :)
    This is the beginning!

    Thanks again :)

  38. Hi Larry,

    Thank you for having shown me the way to find the cause of the problem. It is with this function: public function loadModel($id) { $model=modelClass; ?>::model()->findByPk((int)$id); if($model===null) throw new CHttpException(404,’The requested page does not exist.’); return $model; }
    The primary key (id of my table) is of alphanumeric type (defined as char in mysql). By what, should I replace ‘int’. Thanks

  39. Hi Larry! I so love your Yii tutorial! My nose was bleeding while reading the Yii documentation from Yii site, and I’m so glad I found your tutorial which made me understand the concepts of MVC and how to work with Yii in just a few hours!

    I’m sure to buy your Yii book in case you decided to write one :)

    • Thank you very much, Morris. The Yii documentation has actually come a long way in the past two years, but still… Glad it was useful and I am actually hoping to self-publish a Yii book next year.

  40. thanks so much

  41. Hi Larry, It’s a very nice tutorial.
    I have a question relative to the view part of the employee. When you render the list or manage i can only see the fields of the active record (employee) but how can I show the name of the department, instead of the code?.

  42. Coucou from France.
    Very good job !!

  43. Hi Larry,

    Very nice tutorial for beginners, i read all of 7/8 posts, i understand everything, but i have a doubt in this post
    “One last thing about the layout scripts is that you can easily have different layouts for different sections of the application. To do so, in the Controller method, change the layout value before rendering the view. Provide the name of the layout file, minus the extension. So this line says to use protected/views/layouts/home.php for the index action:
    ” …
    Pls explain,

    Thanks John.

    • Thanks for the nice words. I’m not exactly sure what you’re looking for (in other words, I’m not sure what else to say beyond what I said). Could you clarify what’s not clear to you so I can rephrase it better?

      • Thanks Larry for your reply, i am using yii 1.1.6 version, I created a layout file home.php like main.php in layout folder, I change the code in function actionIndex() [ $this->render(‘index’); TO $this->render(‘home’); ] in the file SiteController.php, but not reflect the template view in home.php..

        I don’t know, that was i misunderstanding or version issues…

        Otherwise for me your posts are very useful to learn YII…


        • I see. Thanks for the nice words and sorry for the confusion. The render() method dictates which specific View file gets executed. That’s not how you change the primary layout file. The code for changing the layout file is above, assigning a new value to the public $layout attribute.

  44. Hi Larry,

    I need some help understand the layout system better;) I come from Pardo Coding and there you have a very strange PLACEHOLDER system, where you can define a central Layout and fill in those…

    E.g. I want to create a jquery ui layout and I have layout containers for north, west, east, south, center…
    Now I want to put content in center and from the same view in west as navigation (jqtree). Is there a way to make something like:

    html code…

    php content_one

    html code….


    ??? Thx! Cheers Phil

    • Hello Phil. You can use renderPartial() to include a View file without a layout. So your main View file does whatever and uses as many of those calls as necessary to get the result you’re looking for (if I understand your question correctly).

      • do you have an example for this?

        I want a central layout (main) where i include 5 view files (at different places) so can this be done with renderPartial???

        Thanks a lot for your support!

        • You’re welcome, but, no, I don’t have an example of this already. You might be able to find something useful by just searching for “Yii” and “renderPartial”.

          • Hi, I found some detail information and thx to your tutorial, i get thinks done, as I needed;) So hope to get deeper into it and maybe write a short tutorial in my own blog;)

  45. Thank you so much for these tutorials, they are really great and immensely helpful!

  46. Have you written a book that teaches Yii yet. Your tutorial is very well written for an introduction to Yii. A proper book will be much much better for many who want to learn more about Yii.

  47. For whatever reason, I can’t get the CRUD interface for department working at all. I just get a 404. All other steps seemed to complete fine

  48. Great Post. Was very explanatory than the documentation. It took lot of time to figure out how $content works.
    Hi Larry, Can you post how we can avoid pagination for some pages and use a scroller to populate all the listings in a scroller ? Or please point me in the right direction. I have some pages where i have to use scroller instead of pagination.

    • Thanks for the nice words. Offhand I don’t have the answers for your questions. I would search online, use the Yii documentation, or the Yii forums.

Trackbacks and Pingbacks:

  1. Tutorial – 8 easy steps to create a web application with YII – Part 4 and Last | Tom's Think Tank - December 30, 2011

    […] you want to learn more on YII view’s design I suggest to read the very good tutorial by Larry […]

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