symfony2 knpmenu,带数据库的多级菜单

时间:2015-12-30 09:31:12

标签: php symfony knpmenubundle

是否可以使用knpmenu bundle为symfony2创建多级菜单,而不知道会有多少级别。如果有2级最大值

,则foreach以下是好的
      class MenuRepository
           public function getMenuItems()
         {
           return $this->findBy(array('active' => '1'), array('parent' => 'ASC', 'order' => 'ASC'));
         }

      }

      class Builder extends ContainerAware
      {
        $menuItems = $em->getRepository('AcmeBundle:Menu')->getMenuItems();
        foreach ($menuItems as $key => $item) {
          if ($item->getParent() == null) {
            $menu->addChild($item->getId(),
            array(
              'route' => $item->getRoute().'_display',
              'label' => $item->getTitle(),
              'routeParameters' => array('slug' => $item->getParametry())));
          } else {
            if (isset($menu[$item->getParent()->getId()] )) {
              $menu[$item->getParent()->getId()]->addChild($item->getId(), array(
                  'route' => $item->getRoute().'_display',
                  'label' => $item->getTitle(),
                  'routeParameters' => array('slug' => $item->getParam())));
            } 
          }
        }

insertChild

的递归函数
function insertChild($needle,$haystack) {
  foreach($haystack as $key=>$value) {
      $current_key=$key;
      if($needle->getParent()->getId()===$key ||
        ($this->insertChild($needle ,$value->getChildren()) !== false)) {
        $haystack[$key]->addChild($needle->getId(),
          array(
            'route' => $needle->getRoute().'_display',
            'label' => $needle->getTitle(),
            'routeParameters' => array('slug' => $needle->getParam())
          ));
          return $haystack[$key];
      }
  }
  return false;
}

0 个答案:

没有答案