Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Menu Bundle Laravel Package

alpixel/menu-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require alpixel/menu-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Alpixel\MenuBundle\AlpixelMenuBundle::class => ['all' => true],
    ];
    
  2. Database Migration: Run migrations to create the required tables:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. First Use Case: Access the admin interface at /admin/menu to create your first menu. Use the built-in CRUD interface to add items, set parent-child relationships, and configure routes/anchors.


Where to Look First

  • Admin UI: /admin/menu – The primary interface for managing menus.
  • Twig Integration: Check Resources/views/AlpixelMenuBundle for default templates.
  • Configuration: config/packages/alpixel_menu.yaml (if auto-generated).

Implementation Patterns

Core Workflows

  1. Menu Creation:

    • Use the admin panel to define menus (e.g., "Main Navigation," "Footer Links").
    • Assign routes (e.g., app.homepage) or anchors (#contact) to menu items.
  2. Dynamic Rendering:

    • Render menus in Twig with:
      {{ render(knp_menu('main_menu', {'template': 'AlpixelMenuBundle:Menu:main.html.twig'})) }}
      
    • Override templates in templates/AlpixelMenuBundle/Menu/ for custom styling.
  3. Sorting and Nesting:

    • Drag-and-drop reordering is supported via pixassociates/sortable-behavior-bundle.
    • Parent-child relationships create hierarchical menus (e.g., dropdowns).
  4. Route-Based Items:

    • Link items to Symfony routes (e.g., route: 'app.user_profile').
    • Use routeParameters for dynamic segments (e.g., { id: user.id }).
  5. Anchor Links:

    • Add # prefixed items (e.g., #services) for page anchors.

Integration Tips

  • Symfony Events: Listen to alpixel_menu.item.pre_save or alpixel_menu.item.post_remove for custom logic:

    // src/EventListener/MenuListener.php
    public function onMenuItemSave(MenuItemEvent $event) {
        $item = $event->getItem();
        // Modify $item->setCustomField(...);
    }
    

    Register in services.yaml:

    services:
        App\EventListener\MenuListener:
            tags:
                - { name: kernel.event_listener, event: alpixel_menu.item.pre_save }
    
  • Custom Menu Builders: Extend Alpixel\MenuBundle\Builder\MenuBuilder to add logic (e.g., hide items based on user roles):

    class CustomMenuBuilder extends MenuBuilder {
        public function buildMenu() {
            $menu = parent::buildMenu();
            if (!$this->security->isGranted('ROLE_ADMIN')) {
                $menu->removeChild('admin_dashboard');
            }
            return $menu;
        }
    }
    

    Configure in config/packages/alpixel_menu.yaml:

    alpixel_menu:
        builder: App\Builder\CustomMenuBuilder
    
  • Translation: Use trans in menu items (e.g., label: 'app.menu.home'). Ensure translations are loaded in your Twig environment.


Gotchas and Tips

Pitfalls

  1. Outdated Dependencies:

    • The bundle relies on KnpMenuBundle v2.1 and Symfony 2.8+. Conflicts may arise with newer Symfony versions (e.g., 5.x). Test thoroughly.
    • Fix: Pin dependencies in composer.json or fork the bundle for updates.
  2. Missing Migrations:

    • If you skip migrations, the admin panel will fail with EntityManager errors.
    • Fix: Always run doctrine:migrations:migrate after installation.
  3. Caching Issues:

    • Menu rendering may not update immediately due to Symfony’s cache. Clear cache after changes:
      php bin/console cache:clear
      
  4. Sortable Behavior Quirks:

    • The pixassociates/sortable-behavior-bundle integration can cause JS errors if not configured properly.
    • Fix: Ensure jQuery UI is loaded and the sortable behavior is enabled in your MenuItem entity.

Debugging

  1. Admin Panel Errors:

    • Check var/log/dev.log for Doctrine or Twig exceptions.
    • Common causes: Missing translations, invalid route names, or permission issues.
  2. Menu Not Rendering:

    • Verify the menu name matches exactly (e.g., 'main_menu' vs. 'mainMenu').
    • Ensure the Twig template path is correct:
      {% if menu is not empty %}
          {{ knp_menu_render(menu, { 'template': 'AlpixelMenuBundle:Menu:main.html.twig' }) }}
      {% endif %}
      
  3. Route Parameters:

    • If using dynamic routes (e.g., { id }), ensure the routeParameters are passed correctly:
      {{ path('app.user_profile', { id: user.id }) }}
      

Extension Points

  1. Custom Fields: Add fields to MenuItem via Doctrine extensions:

    // src/Entity/MenuItem.php
    /**
     * @ORM\Column(type="string", nullable=true)
     */
    private $customIcon;
    

    Update the admin form template (Resources/views/AlpixelMenuBundle/MenuItem/_form.html.twig).

  2. Menu Item Types: Extend the MenuItem entity to support custom types (e.g., "Button," "Divider"):

    // src/Entity/MenuItem.php
    /**
     * @ORM\Column(type="string", enum={"link", "button", "divider"})
     */
    private $type = 'link';
    
  3. Security Trimming: Use KnpMenu’s SecurityContext to hide items:

    $menu->addChild('Admin', ['route' => 'app.admin'])
         ->setAttribute('security', 'is_granted("ROLE_ADMIN")');
    
  4. API Access: Expose menu data via API by creating a custom controller:

    // src/Controller/ApiMenuController.php
    public function getMenu(string $name): JsonResponse {
        $menu = $this->menuBuilder->buildMenu($name);
        return $this->json($menu->toArray());
    }
    

Configuration Quirks

  1. Default Menu Name: The admin panel defaults to 'main_menu'. Change it in config/packages/alpixel_menu.yaml:

    alpixel_menu:
        default_menu: 'primary_navigation'
    
  2. Template Overrides: Copy Resources/views/AlpixelMenuBundle/Menu/ to templates/AlpixelMenuBundle/Menu/ to override defaults without modifying the bundle.

  3. Anchor Links: Ensure anchors are prefixed with # (e.g., #contact). The bundle strips this prefix internally but re-adds it during rendering.

  4. Localization: Menu items support translation keys (e.g., label: 'app.menu.home'). Ensure your translation files (e.g., translations/messages.en.yaml) include:

    app:
        menu:
            home: Homepage
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware