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

Pd Widget Laravel Package

appaydin/pd-widget

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require appaydin/pd-widget
    

    Ensure Pd\WidgetBundle\PdWidgetBundle::class is enabled in config/bundles.php.

  2. Configure Routing: Add to config/routes.yaml:

    widget:
        resource: "@PdWidgetBundle/Resources/config/routing.yml"
    
  3. Doctrine Mapping: Update config/packages/doctrine.yaml to resolve UserInterface:

    doctrine:
        orm:
            resolve_target_entities:
                Pd\WidgetBundle\Entity\UserInterface: App\Entity\User
    
  4. Optional Config: Customize widget behavior in config/packages/framework.yaml:

    pd_widget:
        base_template: '@PdWidget/widgetBase.html.twig'
        return_route: 'admin_dashboard'
    

First Use Case: Display a Simple Widget

  1. Create a Widget Class:

    // src/Widgets/HelloWidget.php
    namespace App\Widgets;
    
    use Pd\WidgetBundle\Builder\Item;
    use Pd\WidgetBundle\Event\WidgetEvent;
    
    class HelloWidget {
        public function builder(WidgetEvent $event) {
            $widgets = $event->getWidgetContainer();
            $widgets->addWidget(
                (new Item('hello', 3600))
                    ->setGroup('demo')
                    ->setName('hello_widget.name')
                    ->setTemplate('widgets/hello.html.twig')
                    ->setData(['message' => 'Hello, World!'])
            );
        }
    }
    
  2. Register the Widget:

    # config/services.yaml
    App\Widgets\HelloWidget:
        tags:
            - { name: kernel.event_listener, event: widget.start, method: builder }
    
  3. Render the Widget:

    {% extends 'base.html.twig' %}
    {% block body %}
        {{ pd_widget_render('demo') }}
    {% endblock %}
    
  4. Create the Template:

    # templates/widgets/hello.html.twig
    <div class="widget-hello">
        <h3>{{ widget.data.message }}</h3>
    </div>
    

Implementation Patterns

Widget Lifecycle

  1. Event-Driven Workflow:

    • Widgets are built during the widget.start event.
    • Use WidgetEvent to access the container and add widgets dynamically.
  2. Grouping and Filtering:

    • Organize widgets into groups (e.g., admin, dashboard).
    • Render specific groups or individual widgets:
      {{ pd_widget_render('admin') }}          {# All widgets in 'admin' group #}
      {{ pd_widget_render('admin', ['user_info']) }} {# Only 'user_info' widget #}
      
  3. Data Handling:

    • Use setData() to pass dynamic data to templates:
      ->setData(function () {
          return ['userCount' => $this->userRepository->count()];
      })
      
    • Data is accessible in Twig as widget.data.
  4. Caching:

    • Set cache duration (in seconds) via the Item constructor:
      (new Item('widget_key', 3600)) {# Cache for 1 hour #}
      

Common Patterns

  1. Dynamic Widgets:

    • Fetch data conditionally in setData():
      ->setData(function () use ($request) {
          return ['active' => $request->isXmlHttpRequest()];
      })
      
  2. Role-Based Access:

    • Restrict widgets to specific roles:
      ->setRole(['ROLE_ADMIN'])
      
  3. Reusable Templates:

    • Extend a base template for consistent styling:
      {% extends pd_widget.base_template %}
      {% block widget_content %}
          {{ parent() }}
          <div class="custom-styles">{{ widget.data.message }}</div>
      {% endblock %}
      
  4. Action Buttons:

    • Include interactive elements via @PdWidget/widgetAction.html.twig:
      {% include '@PdWidget/widgetAction.html.twig' %}
      

Integration Tips

  1. Admin Panel Integration:

    • Use widget groups to segment admin dashboard sections (e.g., users, settings).
  2. Frontend Dashboards:

    • Combine with Symfony UX for reactive widgets:
      {{ pd_widget_render('dashboard', ['stats']) }}
      
  3. Testing:

    • Mock WidgetEvent in unit tests:
      $event = $this->createMock(WidgetEvent::class);
      $event->method('getWidgetContainer')->willReturn($container);
      $widget->builder($event);
      

Gotchas and Tips

Pitfalls

  1. Doctrine UserInterface Mismatch:

    • Ensure resolve_target_entities in doctrine.yaml points to your actual User entity.
    • Fix: Update the mapping if using a custom user class.
  2. Caching Issues:

    • Widgets cache by key and group. Clear cache after changes:
      php bin/console cache:clear
      
    • Debug: Temporarily set cache duration to 0 to test live updates.
  3. Template Overrides:

    • If pd_widget_render() outputs nothing, verify:
      • The widget group exists.
      • The template path is correct (e.g., widgets/userInfo.html.twig).
      • The widget is active (check isActive in Twig).
  4. Event Listener Registration:

    • Forgetting to tag the service as a kernel event listener will silently fail.
    • Fix: Ensure tags: [kernel.event_listener] is present in services.yaml.
  5. Deprecated Properties:

    • Older versions used setContent() for static text. Prefer setData() + template for flexibility.

Debugging Tips

  1. Log Widget Data: Add a debug dump in your widget builder:

    public function builder(WidgetEvent $event) {
        $widgets = $event->getWidgetContainer();
        $widgets->addWidget((new Item('debug', 0))
            ->setData(function () {
                return ['debug' => 'Widget loaded!'];
            })
        );
    }
    
  2. Check Active Widgets: In Twig, dump active widgets to verify rendering:

    {{ dump(pd_widget_render('admin', [], true)) }} {# Show raw widget data #}
    
  3. Event Dispatcher: Ensure the widget.start event is dispatched. Add a listener to verify:

    public function onKernelRequest(GetResponseEvent $event) {
        $event->getRequest()->attributes->set('widgets_loaded', true);
    }
    

Extension Points

  1. Custom Base Template: Override base_template in config to modify widget styling globally:

    pd_widget:
        base_template: 'custom_widget_base.html.twig'
    
  2. Dynamic Widget Groups: Build groups dynamically based on user roles or permissions:

    ->setGroup($this->security->getToken()->getUser()->getRole())
    
  3. Widget Actions: Extend @PdWidget/widgetAction.html.twig to add custom buttons:

    {# templates/widgets/custom_actions.html.twig #}
    <button class="btn-edit">{{ 'widget.edit'|trans }}</button>
    
  4. Internationalization: Use translation keys for widget names/descriptions:

    ->setName('widget.user_info.name')
    

    Ensure translations are loaded in your Twig environment.

  5. Performance:

    • For heavy widgets, lazy-load data in setData():
      ->setData(function () {
          return $this->expensiveService->getData(); // Load only when needed
      })
      
    • Use setCacheDuration(0) for real-time widgets.
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.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme