By Example: CHtml

"By Example" cookbook pages will provide coding examples for many of the commonly used classes within Yii. We will try to provide as many usage examples as possible for keep these pages as helpful as possible.

Smarthead will be pulling these from the forum when he is not finding the answers on his own. Please request examples using the comments below or ask for an example in the forum. Thanks.

Avaiable methods:

  • CHtml::link()

  • CHtml::button()

  • CHtml::textField()

  • CHtml::listData()

  • CHtml::dropDownList()


:: CHtml::link() method

public static string link(string $text, mixed $url='#', array $htmlOptions=array ( ))

Generates a hyperlink tag.


Example 1: Linking to a controller action

<?php echo CHtml::link('Link Text',array('controller/action')); ?>

HTML Output:

<a href="index.php?r=controller/action">Link Text</a>

Example 2: Linking to a controller action with querystring parameters

<?php echo CHtml::link('Link Text',array('controller/action',
                                         'param1'=>'value1')); ?>

HTML Output:

<a href="index.php?r=controller/action&param1=value1">Link Text</a>

Example 3: Linking to a controller action with multiple querystring parameters

<?php echo CHtml::link('Link Text',array('controller/action',
                                         'param1'=>'value1',
                                         'param2'=>'value2',
                                         'param3'=>'value3')); ?>

HTML Output:

<a href="index.php?r=controller/action&param1=value1&param2=value2&param3=value3">Link Text</a>

Example 4: Link opening a new page

<?php echo CHtml::link('Link Text',array('controller/action',
                   'param1'=>'value1'), array('target'=>'_blank'); ?>

HTML Output:

<a target="_blank" href="index.php?r=controller/action&param1=value1">Link Text</a>

Example 5: Linking to a controller action inside the actual controller

(Suppose you are in the PostController/view and wants to link to PostController/create)

Just remove the 'controller' part from the string

<?php echo CHtml::link('Link Text',array('action')); ?>

If you are linking to an action from another controller, use the syntax of the former examples.


Example 6: Linking to a controller action from the site root

(Suppose you are inside a module and wants to make the link from a controller of the root application)

In this case, add an slash "/" at the start of the string url

<?php echo CHtml::link('Link Text',array('/controller/action')); ?>

This makes more sense if you are working with modules.


Example 7: Linking to a controller action from another module

Replace below the module-id with desired module id .

<?php echo CHtml::link('Link Text',array('/module-id/controller/action')); ?>

Example 8: Linking to a controller action from the same module

This is useful when you want to make absolute paths avoiding to use static module names.

<?php echo CHtml::link('Link Text',array('/{$this->module->id}/controller/action')); ?>

_

_

:: CHtml::button() method

public static string button(string $label='button', array $htmlOptions=array ( ))

Generates a button.


Example 1: Connecting a button to a controller action

<?php echo CHtml::button('Button Text', array('submit' => 'controller/action')); ?>

HTML Output:

<input id="yt0" type="button" value="Button Text" name="yt0"/>
<script type="text/javascript">
/*<![CDATA[*/
jQuery(document).ready(function() {
             jQuery('#yt0').click(function( {
                            jQuery.yii.submitForm(
                                     this,
                                     'controller/action',{}
                                          );return false;});
                                  });
/*]]>*/
</script>

_

_

:: CHtml::textField() method

public static function textField($name,$value='',$htmlOptions=array())

Generates a textfield.


Example 1: Generating an empty textfield, just with a name

<?php echo CHtml::textField('Text'); ?>

Example 2: Generating a textfield with name and value

<?php echo CHtml::textField('Text', 'some value'); ?>

Example 3: Generating a textfield with customized id, width and maxlength

<?php echo CHtml::textField('Text', 'some value',
 array('id'=>'idTextField', 
       'width'=>100, 
       'maxlength'=>100); ?>

*Note: use 'cols' instead of 'width' when working with textareas


Example 4: Generating a disabled textfield

<?php echo CHtml::textField('Text', 'some value', 
    array('disabled'=>true); ?>

_

_

:: CHtml::listData() method

public static function listData($models,$valueField,$textField,$groupField='')

Generates data for dropDownList and listBox, using the format $key=>$value.


Example 1: Generating a list data for categories

<?php 
     /*you can use here any find method you think 
     proper to return your data from db*/
     $models = categories::model()->findAll();
 
     // format models resulting using listData     
     $list = CHtml::listData($models, 
                'category_id', 'category_name');    
 
     print_r($list);

HTML Output (Example):

array("1" => "Arts", "2" => "Science", "3" => "Culture");

Example 2: Generating an ordered list data for categories using findAll parameter

<?php 
     $models = categories::model()->findAll(
                 array('order' => 'category_name'));
 
     $list = CHtml::listData($models, 
                'category_id', 'category_name');    
 
     print_r($list);

HTML Output (Example):

array("1" => "Arts", "3" => "Culture", "2" => "Science");

_

_

:: CHtml::dropDownList() method

public static function dropDownList($name,$select,$data,$htmlOptions=array())

Generates a dropdown list.

$name: A name for the dropdownList; $select: selected item from the $data $data: an array of the type $key => $value (the possible values of you dropdownlist); $htmlOptions: another options.


Example 1: Generating a simple dropdownlist for gender

<?php echo CHtml::dropDownList('listname', $select, 
              array('M' => 'Male', 'F' => 'Female'));

The $select parameter must contain value 'M' or 'F'.


Example 2: Generating a simple dropdownlist for gender with an 'empty' element.

This example will avoid the dropdownlist to be blank when no value, outputing some proper information to the user

<?php echo CHtml::dropDownList('listname', $select, 
              array('M' => 'Male', 'F' => 'Female'),
              array('empty' => '(Select a gender'));

Example 3: Using data from a model function.

It is better to have you gender list definition inside your model definition.

At model:

public function getGenderOptions(){
    return array('M' => 'Male', 'F' => 'Female');
}

At view:

<?php echo CHtml::dropDownList('listname', $select, 
              $model->genderOptions,
              array('empty' => '(Select a gender'));

Example 4: Using data from db

In order to create a dropdownList with data from db, you have to combine it with listData method that will format models from db into array of $key=>$value.

This part is equal to listData Example 2:

// retrieve the models from db
$models = categories::model()->findAll(
                 array('order' => 'category_name'));
 
// format models as $key=>$value with listData
$list = CHtml::listData($models, 
                'category_id', 'category_name');

Now, we generate our dropdowList from the $list variable

<?php echo CHtml::dropDownList('categories', $category, 
              $list,
              array('empty' => '(Select a category'));

You cand find CHtml class at yii/framework/web/helpers/CHtml.php

Links

Russian Version dropDownList()

Russian Version listData()

Russian Version textField()

Russian Version link()

Total 16 comments:

#683
Nice
by Asgaroth at 9:42pm on September 25, 2009.

Its nice you are doing this i know may people will apreciate it.

#686
Very helpful - would love to see more!
by bobnvic at 9:51am on September 28, 2009.

Examples like this help me quite a bit. I would love to see examples for many other CHtml methods as some are quite different. Ideally, it would be nice to have examples of use in or linked from the Yii Framework Class Reference guide for easy reference. I often go there to find out about a method, and then end up searching the forum for examples, however that often isn't very helpful.

Thanks for doing this!

#689
Great initiative!
by rickgrana at 9:47am on September 29, 2009.

Congratulations!

#703
list box
by bumeshrai at 10:27am on October 4, 2009.

please give an example of ordered list box populated by db/table.

#711
сенк
by Zolter at 10:16pm on October 7, 2009.

Спасибо, отлично

#712
I'd like to use anchors on this article for each method
by rickgrana at 10:18pm on October 7, 2009.

But seems that MarkDown doesn't allows it. Anyone knows how can I do this?

#714
CHTML RadioButtonList
by sardscreed at 10:25am on October 9, 2009.

does yii framework provides multiple radiobuttonlist on one form?

please give example pls..

#752
option been "selected"
by dimis283 at 10:51am on October 20, 2009.

How can an option been "selected"

#755
Re: option been "selected"
by rickgrana at 10:48pm on October 20, 2009.

set the second paramter for dropDownList

#897
Enclose an image with a link
by tigermunky at 12:26am on December 14, 2009.

Hi there!

How would you use CHtml::link() to enclose an image tag with a link?

e.g. (pls excuse the space after '<', not sure how to write the html code without it actually being displayed)

< a class="logo_link" href="/" >< img src="logo.gif" width="200" height="50" alt="logo" />

#927
dropdownlist
by venkatesh1586 at 12:50pm on December 23, 2009.

Reply me..., how to compare the value to display the dropdownlist?

#934
very helpful information
by colt at 12:42am on December 26, 2009.

Very helpful information! Please keep on going with methods examples! :)

#938
To venkatesh and tigermunky
by rickgrana at 12:38pm on December 29, 2009.

@venkatesh: What do you intend to compare?

@tigermunky: Not sure, but maybe you can do CHtml::link(CHtml::image("logo.gif"), "/")

#939
I'd like suggestions
by rickgrana at 12:41pm on December 29, 2009.

Which function should I describe next?

#1048
How to call onclick event for a link by using CHtml::link() function?
by prasad z at 1:15am on January 26, 2010.

hi,

It is nice example that describes use of CHtml::link() function().

Please can you please give an example of using CHtml::link() function for calling onclick event?

Thank You.

#1554
How to avoid unintentionally disabling a textField
by jward at 6:21am on June 3, 2010.

RE: Example 4: Generating a disabled textfield.
Using 'disabled'=>true will disable a textField.
Unfortunately, using 'disabled'=>false will also disable a textField because the value is ignored. Merely the presence of a key named 'disabled' will disable the textField.
Workaround: Use a different key. "Enabled" has no real effect but at least by using it the textField won't be disabled.

Example of code fragments to permit editing specific fields within a new record but disallow updating:

        if($model->isNewRecord)   
            $textFieldOption='enabled';   
        else   
            $textFieldOption='disabled';   
    <?php echo $form->textField($model,'username',array($textFieldOption=>true));  //enabled only if new  ?>   
    <?php echo $form->textField($model,'password',array($textFieldOption=>true)); ?>   
    <?php echo $form->textField($model,'email'); //always allow editing     ?>   



Your Comment:

You may enter comment using Markdown syntax.

Please login with your forum account.
Note: you must have at least ONE forum post with your account.