adding class and links to Ctreeview node

You are viewing revision #5 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#12) »

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, but 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, AS text, IS NOT NULL AS hasChildren "
            . "FROM tree AS m1 LEFT JOIN tree AS m2 ON "
            . "WHERE m1.parent_id <=> $parentId "
            . "GROUP BY ORDER BY ASC"
        $children = $req->queryAll();
        echo str_replace(

after the query($children = $req->queryAll()) in 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.

4 0
Viewed: 15 493 times
Version: Unknown (update)
Category: Tips
Written by: bingjie2680
Last updated by: bingjie2680
Created on: Jul 8, 2011
Last updated: 6 years ago
Update Article


View all history

Related Articles