Tuesday, June 24, 2014

Make a multi level (No fixed level as 3 level OR 4 level, NO HARD CODE) dynamic Drop-Down Menu

People often make a menu (for website OR for sofware) , and often they (not everyone) make it static, as like (main menu item, sub menu, sub - sub menu)

maximum three level menu.

and they write down the code as a HARD code.


SO, i am here to teach you how can you make your menu multi leveled, as i said,

you can make your menu as "main menu item -> sub- menu item -> sub-sub menu item -> sub-sub-sub menu item....... and

unlimited sub items.... no bound."


first of all,

you have to make a table, with rows ->

id (int PK), menu_item_name (varchar), root (int)

thats it,

now, give the root column a default value (0),

the purpose is -- ( if you give no root to an entry, it will take 0 as default )

and we take that item as our MAIN MENU ITEM,

now, insert some data like below,




id menu_item_name root
1 Home 0
2 About Us 0
3 Contact Us 0
4 Portfolio 0
5 Security Product 4
6 Safety Product 4
7 Comfort Product 4
8 Security Product 1 5
9 Security Product 2 5
10 Safety Product 1 6
11 Safety Product 2 6
12 Comfort Product1 7
13 Comfort Product2 7
14 Security Product1's Sub Product1 8
15 Security Product1's Sub Product2 8
etc........................


And now, we have to run the query to fetch items from the table,


1. first of all, fetch all items who has the root = 0  (main items)



2. then, you have to pass these above item's ids to a recursive function,


query_for_main_items: >>

        $data=fetch_items_with_id_where_root=0

        echo "<ul>";
        foreach($data as $d):
              echo "<li>".$d->menu_item_name."</li>";
              fetchAllItemsOfThisRoot($d->id); // recursive function calling.. for first time.
        endforeach;
        echo "</ul>";


query_for_sub_menu_items: >> 

        fetchAllItemsOfThisRoot($root_id){

              $data=fetch_items_with_id_where_root=$root_id
              echo "<ul>";
              foreach($data as $d):
                     echo "<li>".$d->menu_item_name."</li>";
                     fetchAllItemsOfThisRoot($d->id); // recursive function calling..
              endforeach;
             echo "</ul>";
        }


thats it,

if i get the feedback, i will proceed to the next level, where you will give the address
link to each of the items generated above, dynamically


Thanks in advance...
   

1 comment: