How to Create Dynamic Tree View Menu

Hi,
In this tutorial I will describe to you, how to create tree view structure menu with help of php, mysql and css. It’s very common to use in any web project, I have seen a lot of code sample through goggling and I have created treeview menu based on search.
Actually I need to create task list menu tree view based on project task. A single task may be divided number of subtask.So I need to add subtask dynamically as meanwhile time its reflect also on tree view.


You can also check other tutorial of TreeView Menu

Below steps to produce tree view menu:

Step 1: First we will Create treeview table in mysql database. this table contains four column.id is the task id and name is the task name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
-
-- Table structure for table `treeview_items`
--

CREATE TABLE IF NOT EXISTS `treeview_items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(200) NOT NULL,
  `title` varchar(200) NOT NULL,
  `parent_id` varchar(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

--
-- Dumping data for table `treeview_items`
--

INSERT INTO `treeview_items` (`id`, `name`, `title`, `parent_id`) VALUES
(1, 'task1', 'task1title', '2'),
(2, 'task2', 'task2title', '0'),
(3, 'task3', 'task1title3', '0'),
(4, 'task4', 'task2title4', '3'),
(5, 'task4', 'task1title4', '3'),
(6, 'task5', 'task2title5', '5');

Step 2: Tree view recursive method
I have created below tree createTreeView() method which call recursive if current task id is greater than prev task id.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function createTreeView($array, $currentParent, $currLevel = 0, $prevLevel = -1) {

foreach ($array as $categoryId => $category) {

if ($currentParent == $category['parent_id']) {                       
    if ($currLevel > $prevLevel) echo " <ol class='tree'> "; 

    if ($currLevel == $prevLevel) echo " </li> ";

    echo '<li> <label for="subfolder2">'.$category['name'].'</label> <input type="checkbox" name="subfolder2"/>';

    if ($currLevel > $prevLevel) { $prevLevel = $currLevel; }

    $currLevel++; 

    createTreeView ($array, $categoryId, $currLevel, $prevLevel);

    $currLevel--;               
    }   

}

if ($currLevel == $prevLevel) echo " </li>  </ol> ";

}

Step 3: Create index file to show tree view.
This is main file of treeview example here we will call createTreeView() method with required parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<body>
<link rel="stylesheet" type="text/css" href="_styles.css" media="screen">
<?php
mysql_connect('localhost', 'root');
mysql_select_db('test');


$qry="SELECT * FROM treeview_items";
$result=mysql_query($qry);


$arrayCategories = array();

while($row = mysql_fetch_assoc($result)){ 
 $arrayCategories[$row['id']] = array("parent_id" => $row['parent_id'], "name" =>                       
 $row['name']);   
  }
?>
<div id="content" class="general-style1">
<?php
if(mysql_num_rows($result)!=0)
{
?>
<?php 

createTreeView($arrayCategories, 0); ?>
<?php
}
?>

</div>
</body>
</html>

Step 4: Create CSS file style.css
Here we will write all css related class, currently I am using order list to create tree view. you can also change image path here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
img { border: none; }
input, select, textarea, th, td { font-size: 1em; }
    
/* CSS Tree menu styles */
ol.tree
{
    padding: 0 0 0 30px;
    width: 300px;
}
    li 
    { 
        position: relative; 
        margin-left: -15px;
        list-style: none;
    }
    li.file
    {
        margin-left: -1px !important;
    }
        li.file a
        {
            background: url(document.png) 0 0 no-repeat;
            color: #fff;
            padding-left: 21px;
            text-decoration: none;
            display: block;
        }
        li.file a[href *= '.pdf']   { background: url(document.png) 0 0 no-repeat; }
        li.file a[href *= '.html']  { background: url(document.png) 0 0 no-repeat; }
        li.file a[href $= '.css']   { background: url(document.png) 0 0 no-repeat; }
        li.file a[href $= '.js']        { background: url(document.png) 0 0 no-repeat; }
    li input
    {
        position: absolute;
        left: 0;
        margin-left: 0;
        opacity: 0;
        z-index: 2;
        cursor: pointer;
        height: 1em;
        width: 1em;
        top: 0;
    }
        li input + ol
        {
            background: url(toggle-small-expand.png) 40px 0 no-repeat;
            margin: -0.938em 0 0 -44px; /* 15px */
            height: 1em;
        }
        li input + ol > li { display: none; margin-left: -14px !important; padding-left: 1px; }
    li label
    {
        background: url(folder-horizontal.png) 15px 1px no-repeat;
        cursor: pointer;
        display: block;
        padding-left: 37px;
    }

    li input:checked + ol
    {
        background: url(toggle-small.png) 40px 5px no-repeat;
        margin: -1.25em 0 0 -44px; /* 20px */
        padding: 1.563em 0 0 80px;
        height: auto;
    }
        li input:checked + ol > li { display: block; margin: 0 0 0.125em;  /* 2px */}
        li input:checked + ol > li:last-child { margin: 0 0 0.063em; /* 1px */ }
Result:

treeview

  • ST

    What is the complete code please?
    How to call the function?

    • http://phpflow.com Parvez

      I have added source script, please download and enjoy.

      • Badshah Sahib

        very good job bro very very nice tutorial

  • Rasha

    Hi Parverz can you send me the complete source code of
    How to Create Dynamic Tree View Menu
    because i couldn’t run this,thanks

    • http://phpflow.com Parvez

      Hi Rasha,
      I have added download source link.

  • http://chilev.wordpress.com Blue Grizzly

    This is very helpful to me! Thanks!

  • carlos

    Please could create a treeview based on this table, and the table indicador would be the first person and below them show the name of the person who registered through the indicador

    • http://phpflow.com Parvez

      you can enter person(A) name under ‘name’ column. if it has registered persons(B) sets parent id 0 for A person and set perant id od A person to B member.

  • as92

    hai..how can i add checkbox into your coding?..my system requirement needs to add the checkbox

    • http://phpflow.com Parvez

      you can HTML tag in code.

      • ram

        I want replace the folder icon with chekbox option. But i am not able to do that. It doesn’t display

        • http://phpflow.com Parvez

          can you send me code plz?, so that i can analyse whats problem going on.

  • http://www.arkapravamajumder.com Arka

    Can you tell me, how to show tree view by choosing a particular task? Suppose I want show tree from “task3”. then how do I fix this issue? please help me, its very urgent. Thanks In Advance

    • http://phpflow.com Parvez

      If you dont want tree of on particular task,siply set parent id 0.

  • saqlain

    hi
    nice work dear its working…

  • ramu

    we are displaying based on the parent id please help me

    • http://phpflow.com Parvez

      Here we have a condition if parent id is 0 then we are taking a main node of tree, you can replace 0 with your parent id.

  • Gurdep Singh

    Great work Sir.Thnxx

  • kalyan

    Hai Parvez..this very useful and easily understandable to my project….nice post…Thank u verymuch…

  • kamran anjum

    i see your code this is very good effort but i want to make dynamic tree having 2 childs for example 2/2 tree where a parent has two child and so on plz if you help me i am thankful to you
    best regards

    • http://phpflow.com Parvez

      You can use attched code,I hopes help you.

  • naqqash

    sir i want to add a product against the parent_id how can i display it under the parent category

    • http://phpflow.com Parvez

      Hi,
      you can just simply put you product name in db against parentid.

  • zoleex

    Thank you. if you do not want to start from scratch?

  • zoleex

    hello
    How to dump out that the total number of matches found?
    thank you

    super code…

    • http://phpflow.com Parvez

      you can use this function.
      mysql_num_rows($result)

  • svikarthikeyan

    very helpfull to develop mlm thanks

  • Archavin

    Do you have any idea if we want to do the same work but the hierarchy is divided in multiple in many records.
    something like that :
    ————————————————————————-
    Level1 level2 level3 level4
    ————————————————————————-

    for each level1 there is one or more corresponding from the level2 and so on for the rest (level3 and level4)

    thanks

    • http://phpflow.com Parvez

      Hi Archavin,
      You can modify html layout based on your requirement.

  • Bagus

    WOW, its Worked…Thanks Sir!

  • Prakash

    Your download link is conceptual its very good and its working finely.
    Thanks . .

  • Anton

    Hi, I have just tested your menu and it works great so far. Thank you for that.
    But I have a question: is it possible to put a text field after each label for tag?
    I would like to use this to fill a mysql datadase with it.

    Thanks in advance

    Anton

    • http://phpflow.com Parvez

      yes, you can.

  • pallavi

    Can we give hyperlink to each node??
    Please reply as soon as possible..

    • http://phpflow.com Parvez

      Yes we can,you can add hyperlink between node.
      node

  • Eli

    Hi, I could not run the codes, I’m beginner in php and I don’t know what is the problem. These are my errors:

    Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/TestFolder/treeview/treeview.php on line 14

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/TestFolder/treeview/treeview.php on line 65

    Could you help me please.
    Thank you.

    • http://phpflow.com Parvez

      Hi,
      You have error on ‘while($row = mysql_fetch_assoc($result)’ line.You have passed $result as Boolean instead of resource.

      Have you cheked below query:
      $qry=”SELECT * FROM treeview_items”;
      $result=mysql_query($qry);

      Please varify $results contains data.

      • Eli

        Thank you for your reply, No. I did not add/change anything; I just download your codes and run on my laptop. I expected to see the same result as yours. (your screenshop).

        Do I need to do something?

        • http://phpflow.com Parvez

          Have you run SQL script on your mysql instance.?

  • Erick

    it works…
    but… how and where i put my url or links…
    and when i click menu (task3), (task1) expand.??
    would you help me..??

    • http://phpflow.com Parvez

      You can add between ”.$category[‘name’].’ here anchor tag.like $category[‘name’]

  • Khayyam

    Hey Parvez.
    Good job Thanks, but it’s not actually for IE
    Regards

  • wolfstein

    I’m having trouble with $arrayCategories[$row[‘id’]] = array(“parent_id” => $row[‘parent_id’], “name” =>

    [‘id’] ?

    can you help me please,
    thxs

    • http://phpflow.com Parvez

      Whats error you are getting.?

  • Victor FOrman

    When I used this code, my check-box is located on the next line instead of inline with the folder icon. Although, I need to click above the box to expand and contract the tree branch. How do I move the check box up as is displayed in your picture example?

    Thank you.

    • http://phpflow.com Parvez

      Hi Victor,
      I Think your in build css overriding the tree view css attributes,you need to fix your css class.

  • Victor FOrman

    Parvez,

    Thank you for the quick reply. I’m really new to the PHP and CSS world. How can I make this open into a new window all together instead of being inside an existing frame on my web-site?

    Thanks again,
    Victor

    • http://phpflow.com Parvez

      You can use iframe or model plugin to open in new window.

      • Victor FOrman

        Thank you Very much for your help. I’ll give that a try.

  • Wolfstein

    Ok it’s work i add some query like this:
    $sql=SELECT
    id,
    pid As parent_id,
    pn As parent_name,
    GROUP_CONCAT(cn separator ‘, ‘) child_name
    FROM my_tbl
    WHERE
    GROUP BY parent_name
    ORDER BY parent_id
    but how can i click to target_url that i want?

    thxs anyway

  • Paul-Emanuel

    Hello
    I like very much your tree view.
    Do you know if there is a way to capture the event when selectin one of the node?
    How?
    Thanks

    • http://phpflow.com Parvez

      Yes, you need to add a class on each node where you want capture evnet and fire jquery live event on that class.

  • chandhu

    hi Parvez
    it is very useful for me.
    and my requirement is when i click on sub menu it should be highlighted and stay there.
    it should not be collapse.

    • http://phpflow.com Parvez

      Hi Chandhu,
      You can use hide and show method of jquery or toggle method of jquery.

  • chandhu

    Hi Parvez

    Thanks in advance.
    i am new to php. and i am not having knowledge of jquey,
    please me the modified code to my email.
    thank you..

    • http://phpflow.com Parvez

      ok, i ll get time i ll send u.

      • chandhu

        Hi….
        I am still working on that but not get any solutions for that please help me.

        • http://phpflow.com Parvez

          Can u plz send me your source code with Mysql Script.
          Please share your requirement as well.My mail id : phpflow[at]gmail[dot]com

          • http://phpflow.com Parvez

            Hi Chandu,
            use this code as a jquery.

            $(“.file”).hide(),
            $(“li”).click(function(){
            //$(“.file”).toggle();
            $(‘.file’, this).toggle(); // p00f
            });

  • Ridwan Hidayat

    bye the way,,, thanks for this.
    but when i click in other place of treeview. this all always collapse.

    • http://phpflow.com Parvez

      it will collapse if you will clicked on ‘li’.,May be your li width is more.?

  • Stephen

    Hi Parvez

    This is a great example and works very well. The only thing I am struggling with is how to capture which node a user has selected do you have any extended examples on how to do this?

    Thanks again.

    • http://phpflow.com Parvez

      Hi Stephen,
      Thanks,I have an idea for your problem,You can add an attribute on each node which value would be ‘node name’, Now you need to capture ‘on click’ event with jquery and get node name.

      Thanks
      Parvez Alam

  • Prem

    Hi Parvez
    This is a very good example but if you click on any task(not on plus and minus) resulting the collapse and expand the first root task.
    How can we fix this?
    thanks in advance

    • http://phpflow.com Parvez

      Hi,
      You need to remove event from li and add on (plus and minus link).
      Thanks
      Parvez Alam

  • Rajeev

    Excellent Tutorial.
    How to show the contents of child in a new window >

    • http://phpflow.com Parvez

      thanks, you need to add ‘_blank’ attribute on anchor tag.

  • Rajeev

    Dear Parvez.
    I am a cut paste master, not a programmer. The code works perfectly on my machine. However, is it possible to add a context menu which when right clicked on a particular node , allows adding, editing and deleting a node. And yes, contents of the field in a new window. No idea about anchor tag. Is this what was meant. Subfile 1
    Doesn’t work .

    Your help is required.

    Rajeev.

    • http://phpflow.com Parvez

      Hi rajeev,
      You need to change as below for anchor tag.

    • .
    • for context menu you need to create ur own or can use any jquery plugin for this.

  • Marco

    hi, my question is

    in this line $qry=”SELECT * FROM treeview_items”;

    if i want something like this —— $qry=”SELECT * FROM treeview_items where id = 3″;

    and the tree start in task3 and retrive the childrens having in the parent_id 3 recursive

    • http://phpflow.com Parvez

      You can do that with existing code just create parent-child relation on result array which is sending to treeView function.

  • Tran

    Sir, I want replace the folder icon with check box option. But i am not able to do that. It doesn’t display that.

    • http://phpflow.com Parvez

      sorry for late rply, i was on vacation.You need to add chkbox html on folder icon css.

      • Tran

        Thanks for your reply. Its works. But my need is that when we click the parent then the children displayed downwards with checkbox.

        • http://phpflow.com Parvez

          you can control with your custom css class.

  • Prem

    Hi Parvez I apply the tree view in my website but now i need to give drag and drop facility in it
    can you guide me for that how can i do it
    Thanks

    • http://phpflow.com Parvez

      for that u need to add drag and drop jquery plugin and do some work on json type data.

  • Tran

    Sir I have another doubt,
    Display the details of the form like grid in the same page and we can edit and delete details in the same page.

    • http://phpflow.com Parvez

      yes with help of ajax.

  • PANKAJ

    How to add checkboxes before menu name?

    • http://phpflow.com Parvez

      do u want checkbox on + icon.

  • Manar

    good work ,I need help to display the tree from right to left please
    I can not do that when I am trying the layout differ

    • http://phpflow.com Parvez

      Yes for this you need to play with css.You can customized source code as per your requirement.

  • santu

    This is a very good example but I need help to display the treeview
    $qry=”SELECT * FROM data WHERE rfid or myid=’$id’ “;

    not work single tree?

    • http://phpflow.com Parvez

      myid is parentid

  • Srinivasan

    Sir, your code was very helpful but instead of the folder image the id is displaying which is given in the database at the time of inserting .
    Please help!!!!!!!!!!!!!

    • http://phpflow.com Parvez

      have you included css in your page.

      • Srinivasan

        Sir i have solved the issue, thank you very much .
        How do i put check box for each folder because depending on the ticks in the check box i am going to construct a pivot table

        • http://phpflow.com Parvez

          There is already a checkbox on folder, you can just remove css properties,it will show.

          • Srinivasan

            Sorry sir, I am very new to php. Apologies for my repeated queries, the checkbox seem to display but i cannot tick them. It would be helpful if you tell me css part to make it work. Thanks a million in advance.

          • http://phpflow.com Parvez

            You need to use jquery live event on checkbox click to show your desire view.

  • robindas195

    This is a very good example
    SELECT * FROM `treeview_items` WHERE parent_id or id=’3′
    parent id “0” if the tree view , showing
    but
    SELECT * FROM `treeview_items` WHERE parent_id or id=’5′
    parent id “5” if the tree view is not showing
    pls help

    • http://phpflow.com Parvez

      in database records are exist which has id/parent_id=5.?

  • JBlaw

    Hello,

    Thanks for the script.

    I would like to put it horizontaly, and put some extra , like admin
    how to make that?
    Thanks

    • http://phpflow.com Parvez

      Do You want tree view horizontally, you can handle using CSS.The best way like wordpress admin menu you can create using bootstrap3 easily.