Article Content:Build dynamic tree nodes with jstree and codeigniter

Build dynamic tree nodes with jstree and codeigniter

Build dynamic tree nodes with jstree and codeigniter.

jsTree is Jquery plugin, that provides interactive trees. It is absolutely free, open source 

In this tutorial, we will integrate JsTree with Codeigniter to build dynamic hierarchy-tree.

if you don't hear about jstree you can read full documentation and show more examples from here

Before I start, you should know that you can use this way in any framework or pure PHP, it is some different but the way to do it is one.


1-  Create table schema

I suggest that you have table like this to make hierarchy database, this structure sometimes called (adjacency list model)

    parent_id INT(10) DEFAULT NULL,
INSERT INTO categories (id, parent_id, name) VALUES
    (1,  NULL, 'Electronics'),
    (2,  1,    'Cameras and Photography'),
    (3,  1,    'Computers and Tablets'),
    (4,  1,    'Cell Phones and Accessories'),
    (5,  1,    'TV and Audio'),
    (6,  2,    'Digital Cameras'),
    (7,  2,    'Camcorders'),
    (8,  2,    'Accessories'),
    (9,  3,    'Laptops'),
    (10, 3,    'Desktops'),
    (11, 3,    'Netbooks'),
    (12, 3,    'Tablets'),
    (13, 4,    'Cell Phones'),
    (14, 4,    'Smartphones'),
    (15, 4,    'Accessories'),
    (16, 5,    'Televisions'),
    (17, 5,    'Home Audio'),
    (18, 5,    'Speakers and Subwoofers'),
    (19, 16,   'CRT'),
    (20, 16,   'LCD'),
    (21, 16,   'LED'),
    (22, 16,   'Plasma'),
    (23, 12,   'Android'),
    (24, 12,   'iPad');

2-  Create tree controller and add show_tree method 

this method to show the tree nodes

    function show_tree()
        $this->form_validation->set_error_delimiters("", "");
         $this->form_validation->set_rules('node', 'node ', 'trim|required');
        if($this->form_validation->run()== false){

3- create tree model and add tree_all method

this method to retrieve tree nodes from the table

    function tree_al() {
        $result = $this->db->query("SELECT  id, name,name as text, parent_id FROM categories  ")->result_array();
            foreach ($result as $row) {
                $data[] = $row;
            return $data;

 4-  Create another method in jstree controller

this method to output data as JSON nodes

    function getChildren()
        $result = $this->tree->tree_all();

        $itemsByReference = array();

// Build array of item references:
        foreach($result as $key => &$item) {
            $itemsByReference[$item['id']] = &$item;
            // Children array:
            $itemsByReference[$item['id']]['children'] = array();
            // Empty data class (so that json_encode adds "data: {}" )
            $itemsByReference[$item['id']]['data'] = new StdClass();

// Set items as children of the relevant parent item.
        foreach($result as $key => &$item)
            if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
                $itemsByReference [$item['parent_id']]['children'][] = &$item;

// Remove items that were added to parents elsewhere:
        foreach($result as $key => &$item) {
            if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
        foreach ($result as $row) {
            $data[] = $row;

// Encode:
        echo json_encode($data);

5- Create view file to show the tree


<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<link rel="stylesheet" href="base_url() ?>global/site/dist/style.min.css" />
<script src="base_url() ?>global/site/dist/jstree.min.js"></script>

    <script type="text/javascript">

                //setting to hidden field
                //fill data to tree  with AJAX call
                $('#tree-container').on('changed.jstree', function (e, data) {
                    var i, j, r = [];
                    // var state = false;
                    for(i = 0, j = data.selected.length; i < j; i++) {
                            'plugins': ["wholerow","checkbox"],
                            'core' : {
                                "multiple" : true,
                                'data' : {
                                    "url" : "base_url() ?>tree/getChildren",
                                    "dataType" : "json" // needed only if you do not supply JSON headers
                            'checkbox': {
                                three_state: false,
                                cascade: 'up'
                            'plugins': ["checkbox"]

<div class="row">

    <div class="container">

        <input type="hidden" name="node" id="node" value="" />

        <div class="form-group">
            <div id="tree-container"></div>
the final result will be like this


  • Jason
    Hey there. i stumbled across your website and i must say, i really like your articles. I am a fellow Codeigniter user, but am still learning the Models usage. I have a small question though. Let's say in the model the $result variable was selecting files and sub-directories of parent directories based off of a set path. Do you know how to approach this? Instead of loading from the database? Great article BTW and keep them coming, they're all fantastic!
    December 22, 2016
    • admin
      Hi Jason , You are welcome as A new Friend , about your question it i very easy to do it with php , you have two choices 1- scandir function 2- RecursiveIteratorIterator i prefer scandir and you can follow steps in this answer in the url and it will work good http://stackoverflow.com/questions/33188758/how-to-list-directories-sub-directories-and-all-files-in-php thanks
      December 23, 2016
  • Ina325
    Hi sir, I'm quite new to codeigniter and this article was very helpful for me to build a dynamic tree. Thank you very much! I'm having a problem with creating deleting and renaming the tree nodes, because when I try to access the id of the nodes from the uri, it gives me the format j1_x, and due to this I have no idea how to handle it and save records in database with the appropriate nodes. I've been searching everywhere and it says that should pass the data to json, but it's not very helpful. Any kind of help would be appreciated! Many thanks in advance!
    February 4, 2017
  • Helene
    Hi, Thanks a lot for this tutorial ! I use Code Igniter, but I'm really a beginner whith JQuery. Thanks to your tuto I have implemented a dynamic jstree. But now, I want to have checkbox selected according to my database and I really don't see how must be the json format in this case. If you have any idea, that's would be great ! Thanks for your very good tutorials !
    May 31, 2018
    • admin
      hi Helene ,you are welcome , it is very easy to implement this task , just take a look at jstree documentation under json example you will find selected property which should return as true and opened property should return as true , for more details red this page https://www.jstree.com/docs/json/
      June 2, 2018
      • Helene
        Hi, I've not found the solution to transfer the checkbox properties with the json that describe the tree. So I've have another idea. It's less elegant but it works ! I've put a hidden field in the body named jsfields and add a function that use it for the tree: The hidden field contains the id I have to check when the tree is loaded, coma separated. $('#tree-container').on('loaded.jstree', function (e, data) { var i, r = []; checkedid=$("#jsfields").val(); r=checkedid.split(','); console.log(r.join('/')); for(i = 0; i< r.length; i++) { $('#tree-container').jstree(true).select_node(r[i]); } }) Have a good day !
        June 4, 2018

Leave a Reply

Your email address will not be published.

Notify me of followup comments via e-mail.
You can also Subscribe without commenting.