Welcome Guest, Not a member yet? Register   Sign In
Menu with subitems from DB - CI noob
#5

[eluser]noideawhattotypehere[/eluser]
Code:
private function _generate_menu($array, $arrayattrs = NULL, $parent = 0, $level = 0, $firstloop = TRUE) {
        if ($array == NULL) {
            return false;
        }
        global $html;
        $has_children = false;
        foreach ($array as $key => $value) {
            if ($value['parent_id'] == $parent) {
                if ($has_children === false) {
                    $has_children = true;
                    if ($firstloop && $arrayattrs != NULL) {
                        $attributes = '';
                        foreach ($arrayattrs as $attr) {
                            $attributes .= ' ' . $attr;
                        }
                        $html .= '<ul' . $attributes . '>';
                    } else {
                        $html .= '<ul>';
                    }
                    $level++;
                }
                $html .= '<li><a href="' . $value['address'] . '">' . $value['name'] . '</a>';
                $this->_generate_menu($array, NULL, $value['id'], $level, FALSE);
                $html .= '</li>';
            }
        }
        if ($has_children === true)
            $html .= '</ul>';
        return $html;
    }

call it like
Code:
$your_menu = $this->_generate_menu($array_with_pages);

you can also add array of lets say ids etc
Code:
$this->_generate_menu($array_with_pages, $array_with_attrs);
where $array_with_attrs is like array('id="my_menu_class"', 'class="my_menu_class"')

To add a class to items with submenus you could use jQuery or modify the function, heres jq example (with bonus 'active' class to link leading to current page, please note that .menu is a class for our menu, see above how to use it)
Code:
#script type="text/javascript"#
            jQuery(document).ready(function() {
                $("ul.menu li").children("ul").each(function() {
                    $(this).addClass("submenu");
                });
                $("ul.menu a").filter(function() {
                    return this.href == location.href.replace(/#.*/, "");
                }).parent().addClass("active");
            });
#/script#

PS: You could also change the function not to use global variables, i dont really like them but I'm too lazy to fix that for you.
PS2: You sure you want a class on li elements in submenu instead of nested ul's?


Messages In This Thread
Menu with subitems from DB - CI noob - by El Forum - 02-02-2014, 07:04 AM
Menu with subitems from DB - CI noob - by El Forum - 02-02-2014, 08:10 AM
Menu with subitems from DB - CI noob - by El Forum - 02-02-2014, 12:32 PM
Menu with subitems from DB - CI noob - by El Forum - 02-02-2014, 03:28 PM
Menu with subitems from DB - CI noob - by El Forum - 02-04-2014, 02:45 AM



Theme © iAndrew 2016 - Forum software by © MyBB