0

im building an gallery app and i need it to be in tree format , im using the jstree extension to build it , and i need the json to be in this format:

$(function () {
    $("#demo1").jstree({ 
        "json_data" : {
            "data" : [
                { 
                    "data" : "A node", 
                    "metadata" : { id : 23 },
                    "children" : [ "Child 1", "A Child 2" ]
                },
                { 
                    "attr" : { "id" : "li.node.id1" }, 
                    "data" : { 
                        "title" : "Long format demo", 
                        "attr" : { "href" : "#" } 
                    } 
                }
            ]
        },
        "plugins" : [ "themes", "json_data", "ui" ]
    }).bind("select_node.jstree", function (e, data) { alert(data.rslt.obj.data("id")); });
});

and im using this database:

categorys: id name id_father

products: id name price category_id

please help me guys , >_< , im using an MVC structure in my project and its possible to do things like foreach(modelinstance as model) ...

help i realy need it and i have no idea how to build it

1 Answer 1

2

This is the function that I use, youll need CNestedSetBehavior in your model though, I recomend this way of setting up hierarquical data, as it is much faster to retrieve:

protected function formatJstree(){
        $categories = $this->descendants()->findAll();
        $level=0;
        $parent = 0;
        $data = array();
        foreach( $categories as $n => $category )
        {
            $node = array(
                'data'=> "{$category->title}",
                'attr'=>array('id'=>"category_id_{$category->category_id}")
            );
            if($category->level == $level){
                $data[$parent]["children"][] = $node;
            }
            else if($level != 0 && $category->level > $level){
                if(!isset($data[$n]["children"])){
                    $data[$n]["children"] = array();
                }
                $data[$parent]["children"][] = $node;
            }
            else
            {
                $data[] = $node;
                $parent = $n;
            }
            $level=$category->level;

        }
        return $data;

    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.