Yii 1.1: By Example: CHtml

79 followers

"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() 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')); ?>

Example 9: Linking to a controller action via POST with confirmation dialog

Delete actions created using gii require the delete request be sent via POST to help prevent deleting objects by accident. Below is an example how to create a link that sends the request via POST and also asks for confirmation. Where you are redirected after the delete depends on your delete action. Note that the id link parameter below is a GET type parameter (submit URL will be something like http://example.com/post/delete/id/100).

<?php echo CHtml::link('Delete',"#", array("submit"=>array('delete', 'id'=>$data->ID), 'confirm' => 'Are you sure?')); ?>

If you are using CSRF protection in your application do not forget to add csrf parameter to the htmlOptions array.

<?php echo CHtml::link('Delete',"#", array("submit"=>array('delete', 'id'=>$data->ID), 'confirm' => 'Are you sure?', 'csrf'=>true)); ?>

Example 10: Linking to a controller action via POST with POST parameters

If you need to make POST request with arbitary link with additional POST parameters you should use following code (submit URL will be something like http://example.com/blog/deletePost/param/100).

<p><?php echo lnk('Delete blog post', '#', array(
    'submit'=>array('blog/deletePost', 'param'=>100),
    'params'=>array('id'=>$post->id, 'status'=>Post::STATUS_DELETED_BY_OWNER),
    'csrf'=>true,
)); ?></p>

CHtml::ajaxLink() method

Syntax:

public static string ajaxLink(string $text, mixed $url, array $ajaxOptions=array ( ), array $htmlOptions=array ( ))

Default example

echo CHtml::ajaxLink(
    $text = 'Click me', 
    $url = '/', 
    $ajaxOptions=array (
        'type'=>'POST',
        'dataType'=>'json',
        'success'=>'function(html){ jQuery("#your_id").html(html); }'
        ), 
    $htmlOptions=array ()
    );

Example #1 : Ajax request using ajaxLink

//In view:
 
echo CHtml::ajaxLink(
    'Test request',          // the link body (it will NOT be HTML-encoded.)
    array('ajax/reqTest01'), // the URL for the AJAX request. If empty, it is assumed to be the current URL.
    array(
        'update'=>'#req_res'
    )
);
 
echo '<div id="req_res">...</div>';
 
 
//In controller
public function actionReqTest01() {
    echo date('H:i:s');
    Yii::app()->end();
}

Example #2 : Ajax request using ajaxLink with loading image

//In view:
echo CHtml::ajaxLink(
    'Test request',          // the link body (it will NOT be HTML-encoded.)
    array('ajax/reqTest01Loading'), // the URL for the AJAX request. If empty, it is assumed to be the current URL.
    array(
        'update'=>'#req_res_loading',
        'beforeSend' => 'function() {           
           $("#maindiv").addClass("loading");
        }',
        'complete' => 'function() {
          $("#maindiv").removeClass("loading");
        }',        
    )
);
 
echo '<div id="req_res_loading">...</div>';
 
 
//In controller:
public function actionReqTest01Loading() {
       sleep(4);   // Sleep for 4 seconds just to demonstrate the Loading Image can be seen, for learning purpose only      
       echo date('H:i:s');
    Yii::app()->end();
}

Reference: Ajaxlink

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' => array('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'=>'disabled'); ?>

Example 5: Generating a hidden textfield

<?php echo CHtml::hiddenField('Text', 'some value', 
    array('id'=>'idTextField'); ?>

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

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

With condition -

echo CHtml::dropDownList('categories', $category, 
              CHtml::listData(categories::model()->findAll("Status=1"),
              'category_id', 'category_name'),
              array('empty' => '(Select a category'));

Example 5: Generating dropdownlist with option groups.

If you need to generate dropdownlist using both optgroup and option tags use the following code.

<div class="cars-select">
    <?php echo CHtml::dropDownList('Cars', 'car_id', array(
        'Mazda'=>array(
            'mazda-rx7'=>'RX7',
            'mazda-rx5'=>'RX5',
        ),
        'Volvo'=>array(
            'volvo-b9tl'=>'B9TL',
            'volvo-l90e-radlader'=>'L90E Radlader',
        ),
    )); ?>
</div>

Code above should generate following HTML.

<div class="cars-select">
    <select name="Cars" id="Cars">
        <optgroup label="Mazda">
            <option value="mazda-rx7">RX7</option>
            <option value="mazda-rx5">RX5</option>
        </optgroup>
        <optgroup label="Volvo">
            <option value="volvo-b9tl">B9TL</option>
            <option value="volvo-l90e-radlader">L90E Radlader</option>
        </optgroup>
    </select>
</div>

CHtml::image() method

public static string image(string $src, string $alt='', array $htmlOptions=array ( ))

Generates a image tag.


Example 1: Image only

<?php echo CHtml::image(Yii::app()->request->baseUrl.'/img/image.png'); ?>

HTML Output:

<img src="/img/image.png" />

Example 2: Image with alt attribute

<?php echo CHtml::image(Yii::app()->request->baseUrl.'/img/image.png', 
'this is alt tag of image'); ?>

HTML Output:

<img src="/img/image.png" alt="this is alt tag of image" />

Example 3: Add width, height and others attribute for image

<?php echo CHtml::image(Yii::app()->request->baseUrl.'/img/image.png',
      'this is alt tag of image',
      array('width'=>'100px','height'=>'100px','title'=>'image title here')); ?>

HTML Output:

<img src="/img/image.png" alt="this is alt tag of image" title="image title here" width="100" height="100" />

You can also add another html attributes like class, id etc. for image in the similar way to adding width and height attribute for image above.


Example 4: Image with link

<?php $image = CHtml::image(Yii::app()->request->baseUrl.'/img/image.png',
      'this is alt tag of image');
 
      echo CHtml::link($image,array('book/view','id'=>'book_id')); ?>

HTML Output:

<a href="index.php?r=book/view&id=book_id"><img src="/img/image.png" alt="this is alt tag of image" /></a>

You can find CHtml class at yii/framework/web/helpers/CHtml.php view on Github, all CHtml methods here.

Links

Russian

Japanese

Total 15 comments

#17491 report it
Gerhard Liebenberg at 2014/06/22 02:36pm
creating id
$options = array(
    'class' => 'singleline',
    'size'  => '1',
    'id'    => 'myId'
    'empty' => '',
    'style' => 'width:300px;',
);
 
echo $form->dropDownList($model, 'columnName', $listdata, $options);
   or
echo $form->dropDownList($name, $defaultValue, $listdata, $options);

The $name is sent to the server. The id (part of options) is used by jquery.

#17485 report it
vijay p s at 2014/06/20 05:24am
creating id

how can we create a id for the dropdown.

#15815 report it
Nisanth thulasi at 2013/12/19 06:43am
Error on Example 3: Generating a textfield with customized id, width and maxlength

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)); ?>

missing one ')'

#15675 report it
leo4all at 2013/12/06 02:24am
Custom Data Attributes

Does anyone knows how to add Custom Data Attributes (HTML5 data-*) to dropDownList

Country table (id, name, iso_code, calling_code)

<select name="Country[id]" id="Country_id">
<option value="">Select Country</option>
<option value="1" data-ISO="USA">United States (+1)</option>
<option value="1" data-ISO="GB">United Kingdom (+44)</option>
</select>
echo $form->dropDownList(Country::model(), 'id', 
CHtml::listData(Country::model()->findAll(), 'id','fullName'),
array('prompt' => 'Select Country', 
); 
 
function getFullName()
{
return $this->country_short_name.' (+'.$this->calling_code.')';
}
#15176 report it
Rajith R at 2013/10/15 03:34am
Text Area Readonly

example

<?php echo CHtml::textArea('Text', $content,
 array('id'=>'widget', 
 'readonly' => true,
       'style'=>'width:700px;height:340px;')); ?>
#14739 report it
turco_7 at 2013/09/06 02:46pm
For Question #13460 about default item on dropdownlist

Dear,

For selected item by dafault you need to use the next option: for example item id 78 must be the default.

array('options' => array('78'=>array('selected'=>true)))

Here you have how to use it:

<?php echo $form->dropDownList($model,'estado_id',CHtml::listData(estado::model()->findAll(),'id', 'estado'),array('options' => array('78'=>array('selected'=>true)))); ?>

Regards!

#13857 report it
rajesh chaurasia at 2013/07/02 07:32am
onmouseover

CHtml::link( CHtml::encode($data->name), array('view', 'id'=>$data->idCategory), array('class'=>'linkClass','onmouseover'=>'doSomething();') );

#13460 report it
Odun: The Last Gunslinger at 2013/05/29 07:53pm
Dropdown with selected value

how do u create a dropdown with a default selected value using CHtml::dropdownlist & ListData?

#11965 report it
jamband at 2013/02/16 02:05am
RE: can display image link instead of text link ?

Yes.
Example:

<?php
$image = CHtml::image(Yii::app()->baseUrl.'/images/thumb-1.jpg');
echo CHtml::link($image, Yii::app()->baseUrl.'/images/image-1.jpg');
?>
#11951 report it
ajayraval at 2013/02/15 02:45am
links with image

can display image link instead of text link ?

#11720 report it
Gerhard Liebenberg at 2013/01/29 11:31am
CHtml::link, urlManager and Ajax url problems

Hi guys

I have this line in my urlManager:

'<controller:\w+>' =>'<controller>/admin', // if no action is included, then
                                           // use actionAdmin

However, when the user clicks on the CHtml::link to go to actionAdmin, then the above line causes CHtml::link to NOT include the action's name in the url in the browser's address bar.

This seems to cause problems when Ajax has to use the url.

So, if you get Ajax 404 and 'response failed' errors, start by making sure that your url contains both controller and action names.

(I'm not an Ajax expert, so if this sounds like nonsense, please let me know.)

#10821 report it
AndreiCurelaru at 2012/11/26 06:43am
That's what a call clear doc

Something as clear as that, should exist for the rest.

Maybe a "Yii By Exemple" wiki categ, where we could all contribute articles like that one ?!

#7592 report it
DerKaktus at 2012/04/01 07:35pm
Button with confirmation
CHtml::button('Delete', 
                array('submit' => array('user/delete','id'=>$model->usId),
                            'name'=>'btnDelete',
                            'confirm'=>'Are you sure you want to delete?',
                            'class'=>'btn btn-large btn-danger',
                            'style'=>'width:160px;'
                        ));
#4263 report it
hasanavi at 2011/06/21 06:42am
Want more

This is a great Wiki, Want more something like this.

#3074 report it
junxiong at 2011/03/14 03:23am
Link with confiirmation

I think we also need to add link with confirmation, especially in delete condition

CHtml::link(t("Delete"), "#", array("submit"=>array("delete","id"=>"$model->id" ),"confirm"=>"Are you sure?"));

Leave a comment

Please to leave your comment.

Write new article