Difference between #10 and #11 of
Display an AJAX tree from your DB using CTreeView

Revision #11 has been created by François Gannaz on May 25, 2012, 11:23:58 AM with the memo:

Added headers and a final note
« previous (#10) next (#12) »

Changes

Title unchanged

Display an AJAX tree from your DB using CTreeView

Category unchanged

Tutorials

Yii version unchanged

Tags unchanged

AJAX, CTreeView

Content changed

## The database
 
 
This example uses a MySQL DB with a table named `tree` with the fields `id`, `name`, and `parent_id`. The `parent_id` will be `NULL` for root elements. The SQL is kept simple (no autoinc, no FK, etc).

~~~~
[...]
MySQL has no recursive queries. In order to fetch tree nodes, you have to recursively send SQL queries for each node, asking for its children. The easiest way to do so is to send these queries with AJAX, so that the tree can be displayed even if the deep nodes haven't been fetched yet. If you're using Oracle or Postgresql, there are other solutions, though this will also work.

## The view
 
 
In your view, add:

~
[...]
```~

This will create a tree widget [CTreeView](http://www.yiiframework.com/doc/api/1.1/CTreeView/) on your page, and its data will be fetch
ed using the `ajaxFillTree` of the current controller. ## The controller
 
 
So we have to add this action to the controller:

~
[...]
When sending the JSON-encoded result, there's a little trick: the javascript wants the `hasChildren` attribute to be a boolean. But the SQL result just contains 0 or 1, so we have to convert it, at least for the "false" case. Instead of operating on the string result, one could modify the PHP array with a `foreach`.

The `exit()` might not be necessary, but if you enabled the logs to Firebug or extensions like a debug toolbar, then Yii
willmay write some JS at the end of your response, and it will break the JSON format.
 
 that would break the JSON format. The drawback of `exit()` is that logs won't be written, whereas `Yii::app()->end()` ends gracefully.
 
 
### Final note
 
 
This is meant as a simple introduction. There are many ways to enhance this:
 
 
* Refactor the action by putting its 3 last lines into a model.
 
* Inscrease the abstraction level, so that the code can be used on various models, as long as they share the same table structure.
 
* If the tree content rarely changes, you may consider using a different structure, like nested sets. This will make most queries easier, e.g. fetching the path of a node.
19 0
21 followers
Viewed: 59 518 times
Version: 1.1
Category: Tutorials
Written by: François Gannaz
Last updated by: François Gannaz
Created on: Apr 7, 2010
Last updated: 5 years ago
Update Article

Revisions

View all history