We are going to deploy the new yiiframework.com website on March 23, 2018 from 8:00 to 12:00 UTC.
Website and Yii documentation will not be available in this time frame. Check the news for more details.

Yii 1.1: adding class and links to Ctreeview node


This article will show you how to add links and class to each node in ctreeview. so you can attach events in js by obtaining handler on anchor or class.

I am new to Yii, and I love this framewrok. lately I have been playing a bit with ctreeview. and I find out there is a lack of documentation about adding links to ctree node, so here, I would like to share my experience with you, because I think this is a quite common practice if you are using ctreeview. this article is based on this article


So I assume that you have something like this in your controller:

public function actionAjaxFillTree()
        if (!Yii::app()->request->isAjaxRequest) {
        $parentId = "NULL";
        if (isset($_GET['root']) && $_GET['root'] !== 'source') {
            $parentId = (int) $_GET['root'];
        $req = Yii::app()->db->createCommand(
            "SELECT m1.id, m1.name AS text, m2.id IS NOT NULL AS hasChildren "
            . "FROM tree AS m1 LEFT JOIN tree AS m2 ON m1.id=m2.parent_id "
            . "WHERE m1.parent_id <=> $parentId "
            . "GROUP BY m1.id ORDER BY m1.name ASC"
        $children = $req->queryAll();
        echo str_replace(

after the query($children = $req->queryAll()) in the above code, add the following loop to insert a link to each node, you can also add a class or id along with it.

foreach($children as $child){
     $nodeText = CHtml::openTag('a', $options);
      $nodeText.= $child['text'];
      $nodeText.= CHtml::closeTag('a')."\n";
      $child['text'] = $nodeText;

And replace




So try it out now.

Total 2 comments

#7637 report it
saegeek at 2012/04/04 05:49am
a tip

if you would like to have URLs only on childs use this @ foreach loop :

foreach($children as $child){
$child['text'] = ($child['hasChildren'] == true ? $child['text'] : CHtml::openTag('a', $options).$child['text'].CHtml::closeTag('a')."\n");
#4459 report it
macinville at 2011/07/11 03:13am
Extension now available

There is already an extension that can handle such task. You can view it here.

Leave a comment

Please to leave your comment.

Write new article
  • Written by: bingjie2680
  • Category: Tips
  • Yii Version: 1.1
  • Votes: +4 / -1
  • Viewed: 15,398 times
  • Created on: Jul 8, 2011
  • Last updated: Aug 6, 2011
  • Tags: ctreeview, link, class