vincej
562
28
Laravel

How to format nested set table data to work in JsTree?

Posted 3 months ago by vincej

I have been trying to use jsTree.com to deliver a dynamic tree of categories in my view. However, despite following the instructions as given both their docs as well as those given in Javascripting.com. Consistently I am getting the JS error: Uncaught TypeError: Cannot read property 'toString' of null

I believe this is caused by my nested set table which delivers the root category parent as being null. By definition the Root category can not have a parent. Documentation states that the root must have # as it's parent however gives no clue how to achieve this. Unless of course, I have not properly implemented the JsTree code. I am using the Ajax method to retrieve my table data. JsTree will execute the AJAX.

$(function() {
        $('#jstree').jstree({
            'core' : {
                'data' : {
                    "url" : "/getTree",
                    "dataType" : "json"
                }
            }
        });
    });

Controller

public function getTree(){
         $nodes = $this->category->orderByDepth();
         echo json_encode($nodes);

    }

Model

public function orderByDepth()  // this finds all nodes and their respective depth.
        {  $nodeDepth = DB::select('SELECT category_id AS id,  name AS text, (SELECT name 
           FROM nested_categories t2 
           WHERE t2.lft < t1.lft AND t2.rgt > t1.rgt    
           ORDER BY t2.rgt-t1.rgt ASC
           LIMIT 1) 
           AS parent FROM nested_categories t1 
           ORDER BY (rgt-lft) DESC');
           return $nodeDepth;
        }

Does anyone know how to make this work? It has been driving me crazy for two days now. Many thanks !

Please sign in or create an account to participate in this conversation.