Yii 1.1: htmlOptions explained for various controls.


Most controls that are rendered by CHtml have an argument called $htmlOptions. This argument is an array that holds the attributes of the HTML element. For example the following code:

<?php echo CHtml::link("Yii","http://www.yiiframework.com",array("style"=>"color: orange;")); ?>

Will render this link:

<a style="color: orange;" href="http://www.yiiframework.com">Yii</a>

Some tags are more complicated, for example a drop down list is composed of multiple tags:


To get attributes onto the options, add a sub-array called "options" to your htmlOptions. For example to color each item in your drop down a different color this code:

$items = array("1" => "first", "2" => "second");
$options["options"] = array("1"=>array("style" => "color:red"), "2"=>array("style"=>"color:blue"));
echo CHtml::dropDownList("myDropDown", null, $items,$options);

Produces this html:

<select name="myDropDown" id="myDropDown"> 
<option value="1" style="color:red">first</option> 
<option value="2" style="color:blue">second</option> 

Note: Please add to this wiki if you know of other special cases!

Total 1 comment

#2820 report it
Mukke at 2011/02/14 03:48am

great comment, i never found how to do this but it makes sense now. this doesn't go for style only tho,

when working with custom js you will need to either use htmlOptions or jQuery("body").delegate(element,event,function(){ but then you'll need your element to have an id given with htmlOptions

i use the 2nd when the actions on an element are more omplicated then just running a function onSubmit or onClick or whatever

To go further on this, sometimes if your not happy with how yii does a js function you can always 'undelegate' it before you redelegate it, for further info just visit the jQuery's docu

Leave a comment

Please to leave your comment.

Write new article
  • Written by: Woil
  • Category: Tips
  • Yii Version: 1.1
  • Votes: +18 / -1
  • Viewed: 56,877 times
  • Created on: Feb 11, 2011
  • Last updated: Feb 11, 2011
  • Tags: htmlOptions, chtml