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

Widgets Bundle Laravel Package

badpixxel/widgets-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require badpixxel/widgets-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        BadPixxel\WidgetsBundle\WidgetsBundle::class => ['all' => true],
    ];
    
  2. First Widget Create a basic widget class in src/Widgets/:

    namespace App\Widgets;
    
    use BadPixxel\WidgetsBundle\Widget\AbstractWidget;
    
    class MyFirstWidget extends AbstractWidget
    {
        public function getTitle(): string
        {
            return 'My Custom Widget';
        }
    
        public function getContent(): string
        {
            return '<p>Hello, Dashboard!</p>';
        }
    }
    
  3. Register Widget Add the widget to your dashboard configuration in config/packages/badpixxel_widgets.yaml:

    widgets:
        dashboard:
            - App\Widgets\MyFirstWidget
    
  4. Display Widgets Render widgets in a Twig template:

    {% for widget in widgets %}
        {{ widget.render() }}
    {% endfor %}
    

First Use Case: Quick Bootstrap Widget

Use the built-in BootstrapWidget for rapid UI integration:

use BadPixxel\WidgetsBundle\Widget\BootstrapWidget;

class StatsWidget extends BootstrapWidget
{
    public function getTitle(): string
    {
        return 'System Stats';
    }

    public function getContent(): string
    {
        return $this->renderStatsCard();
    }

    private function renderStatsCard(): string
    {
        return $this->renderCard([
            'title' => 'Active Users',
            'value' => 42,
            'icon' => 'users',
        ]);
    }
}

Implementation Patterns

Widget Lifecycle

  1. Initialization Override initialize() to fetch data early:

    public function initialize()
    {
        $this->data = $this->entityManager->getRepository(User::class)->getActiveUsers();
    }
    
  2. Caching Use setCacheLifetime() to cache widget output:

    public function __construct()
    {
        $this->setCacheLifetime(3600); // Cache for 1 hour
    }
    
  3. Dependency Injection Inject services via constructor:

    public function __construct(
        private UserRepository $userRepo,
        private ClockInterface $clock
    ) {}
    

Dashboard Integration

  1. Dynamic Widget Loading Load widgets dynamically via a service:

    # config/packages/badpixxel_widgets.yaml
    widgets:
        dashboard:
            - '@widget.service_id'  # Service-based widget
    
  2. Widget Groups Organize widgets into tabs/sections:

    // In a custom dashboard controller
    $widgets = $this->widgetManager->getWidgets('dashboard');
    $widgets->groupBy(['tab1', 'tab2']);
    
  3. Conditional Rendering Skip widgets based on user roles:

    public function isVisible(): bool
    {
        return $this->security->isGranted('ROLE_ADMIN');
    }
    

Advanced Patterns

  1. Widget Events Listen to widget events (e.g., WidgetRenderEvent):

    $eventDispatcher->addListener(
        WidgetEvents::PRE_RENDER,
        [$this, 'onPreRender']
    );
    
  2. Widget Templates Override Twig templates:

    {# templates/widgets/my_widget.html.twig #}
    <div class="custom-widget">
        {{- include '@Widgets/default.html.twig' -}}
    </div>
    
  3. Widget Configuration Use configure() to accept runtime options:

    public function configure(array $options)
    {
        $this->options = $options;
    }
    

Gotchas and Tips

Common Pitfalls

  1. Caching Issues

    • Clear cache after adding new widgets:
      php bin/console cache:clear
      
    • Avoid caching widgets with dynamic data (e.g., real-time stats).
  2. Dependency Conflicts

    • Ensure sonata-project/block-bundle is installed if using Sonata integration:
      composer require sonata-project/block-bundle
      
  3. Twig Template Overrides

    • Place custom templates in templates/widgets/ to avoid overwrites during updates.
  4. Widget Registration

    • Widgets must be autoloaded or manually registered in the bundle’s Resources/config/services.yaml.

Debugging Tips

  1. Log Widget Output Enable debug mode in config/packages/badpixxel_widgets.yaml:

    debug: true
    
  2. Check Widget Events Use Symfony’s event dispatcher to log widget lifecycle:

    $eventDispatcher->addListener(
        WidgetEvents::POST_RENDER,
        function (WidgetRenderEvent $event) {
            $this->logger->debug('Widget rendered:', ['widget' => $event->getWidget()->getClass()]);
        }
    );
    
  3. Inspect Widget Data Dump widget data in Twig:

    {{ dump(widget.getData()) }}
    

Extension Points

  1. Custom Widget Types Extend AbstractWidget for reusable logic:

    abstract class ChartWidget extends AbstractWidget
    {
        protected function renderChart(): string { /* ... */ }
    }
    
  2. Widget Storage Save widget configurations to the database:

    use BadPixxel\WidgetsBundle\Widget\WidgetStorageInterface;
    
    public function __construct(private WidgetStorageInterface $storage) {}
    
  3. Widget Permissions Integrate with Symfony’s security system:

    public function isVisible(): bool
    {
        return $this->security->isGranted('VIEW_DASHBOARD');
    }
    

Configuration Quirks

  1. YAML vs. PHP Config Prefer PHP config for complex widget arrays:

    // config/packages/badpixxel_widgets.php
    return [
        'widgets' => [
            'dashboard' => [
                'App\Widgets\MyWidget',
                ['@widget.service', ['param' => 'value']],
            ],
        ],
    ];
    
  2. Widget Prioritization Order matters in the widgets array—earlier entries render first.

  3. Bootstrap Version Ensure your Bootstrap CSS/JS matches the bundle’s defaults (v4/v5). Override in assets/ if needed.

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