Tutorials

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)

CREATE TABLE IF NOT EXISTS categories (
    id INT(10) NOT NULL AUTO_INCREMENT,
    parent_id INT(10) DEFAULT NULL,
    name VARCHAR(50) DEFAULT NULL, PRIMARY KEY (id)
);
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');
        //$this->load->view('messaging');
        if($this->form_validation->run()== false){
            $this->load->view('show_tree');
        }else{
            redirect('tree/show_tree/');
        }
    }

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']]))
                unset($result[$key]);
        }
        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">
            $(document).ready(function(){

                //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++) {
                        r.push(data.instance.get_node(data.selected[i]).id);
                    }
                    $('#txttuser').val(r.join(','));
                }).jstree({
                            '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"]
                        }
                )
            });
</script>


<div class="row">

    <div class="container">


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

        <div class="form-group">
            <div id="tree-container"></div>
            </div>
        </div>
    </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
    Reply
    • admin
      info@webeasystep.com
      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
      Reply
  • 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
    Reply
  • Ravi Mane
    rase
    July 31, 2017
    Reply

Leave a Reply

Your email address will not be published.


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