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

Sylius Grid Json Driver Bundle Laravel Package

doctorx32/sylius-grid-json-driver-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require doctorx32/sylius-grid-json-driver-bundle
    

    Enable the bundle in config/bundles.php (Laravel 4.x+):

    return [
        // ...
        Sylius\Bundle\GridBundle\Driver\Json\SyliusGridJsonDriverBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Define a grid in config/packages/sylius_grid.yaml (or equivalent):

    sylius_grid:
        grids:
            app_admin_external_products:
                driver:
                    name: json
                    options:
                        url: "/api/products"
                        host: "https://external-api.example.com"
                fields:
                    "[id]": ~
                    "[name]": { type: string }
                filters:
                    search: { type: string }
    
  3. API Requirements: Ensure the target API endpoint (/api/products) returns a Sylius Grid-compatible JSON response with matching field/filter names.


Implementation Patterns

Common Workflows

  1. Fetching External Data: Use the JSON driver to display data from third-party APIs (e.g., ERP, CRM) in Sylius grids without custom controllers. Example:

    driver:
        name: json
        options:
            url: "/v1/inventory"
            host: "https://inventory-service.example.com"
            auth: "Bearer {token}"  # Optional: Pass auth via config or environment
    
  2. Dynamic Field Mapping: Leverage YAML placeholders ([field]) to dynamically map API fields to Sylius grid columns. Example:

    fields:
        "[product_name]": { type: string, label: "Product Name" }
        "[price]": { type: money }
    
  3. Filter Integration: Sync grid filters with API query parameters. The bundle automatically translates Sylius filters to URL query strings:

    filters:
        search: { type: string, label: "Search" }
        category: { type: entity, options: { choices: ["electronics", "clothing"] } }
    

    Resulting API call: /api/products?search=term&category=electronics

  4. Pagination Handling: Configure pagination via grid options:

    driver:
        options:
            url: "/api/orders"
            pagination:
                enabled: true
                limit: 20
    
  5. Caching Responses: Cache API responses to reduce external calls (use Symfony’s HTTP cache or a custom cache layer):

    driver:
        options:
            cache:
                enabled: true
                ttl: 3600  # 1 hour
    

Integration Tips

  • API Versioning: Prefix URLs with version paths (e.g., /v1/products) to avoid breaking changes.
  • Authentication: Pass tokens via options.auth or use Symfony’s HTTP client middleware.
  • Error Handling: Override the driver’s onFailure event to handle API errors gracefully (e.g., show a fallback message).
  • Testing: Mock the JSON driver in tests using Symfony’s HttpClient with a test server:
    $client = static::createClient();
    $client->getContainer()->set('sylius_grid.driver.json.client', new MockHttpClient());
    

Gotchas and Tips

Pitfalls

  1. Field Name Mismatches:

    • The bundle expects exact field/filter name matches between the grid config and API response.
    • Fix: Use label overrides in YAML or preprocess API data with a custom driver extension.
  2. CORS Issues:

    • If the API is hosted on a different domain, ensure CORS headers are configured on the API server.
    • Workaround: Use a proxy endpoint in your Laravel app to bypass CORS.
  3. Pagination Conflicts:

    • Some APIs use ?page=1 while others use ?offset=0&limit=20. Configure pagination explicitly:
      driver:
          options:
              pagination:
                  type: offset  # or "page"
      
  4. Rate Limiting:

    • External APIs may throttle requests. Implement retries or exponential backoff in a custom driver listener.
  5. Data Type Mismatches:

    • The bundle assumes API fields map directly to Sylius types (e.g., string, money). Use custom field types or preprocess data:
      fields:
          "[created_at]":
              type: datetime
              options:
                  format: "Y-m-d H:i:s"
      

Debugging

  1. Check API Responses: Enable debug mode and inspect the raw JSON response:

    driver:
        options:
            debug: true  # Logs API responses to Symfony's profiler
    
  2. Validate JSON Structure: Ensure the API returns a response matching Sylius Grid’s expected format:

    {
        "items": [...],
        "total": 100,
        "filters": { ... },
        "fields": { ... }
    }
    

    Tip: Use JSONLint to validate the API response.

  3. Symfony Profiler: Use the profiler to inspect grid driver events (e.g., sylius_grid.driver.json.fetch).


Extension Points

  1. Custom Driver Options: Extend the driver by overriding its configuration:

    driver:
        options:
            custom_option: "value"
    

    Then implement a custom driver class:

    namespace App\Sylius\Grid\Driver;
    
    use Sylius\Bundle\GridBundle\Driver\JsonDriver;
    
    class CustomJsonDriver extends JsonDriver {
        protected function configureOptions() {
            $this->options['custom_option'] = $this->options['custom_option'] ?? null;
        }
    }
    

    Register it in services.yaml:

    sylius_grid.driver.json: '@app.sylius.grid.driver.json'
    
  2. Pre/Post-Processing: Use Symfony events to modify data before/after fetching:

    // config/services.yaml
    App\EventListener\GridJsonListener:
        tags:
            - { name: kernel.event_listener, event: sylius_grid.driver.json.fetch, method: onFetch }
    
    // src/EventListener/GridJsonListener.php
    public function onFetch(FetchEvent $event) {
        $data = $event->getData();
        $data['items'] = array_map(fn($item) => $this->transform($item), $data['items']);
        $event->setData($data);
    }
    
  3. Override Templates: Customize how data is rendered by overriding the grid’s Twig templates (e.g., sylius_grid/grid/_cell.html.twig).


Configuration Quirks

  1. Host vs. URL:

    • Use host for the base URL and url for the endpoint path. Avoid hardcoding full URLs in url.
    • Example:
      driver:
          options:
              host: "https://api.example.com"
              url: "/v1/products"
      
  2. Environment Variables: Dynamically set host or auth via environment variables:

    driver:
        options:
            host: "%env(API_HOST)%"
            auth: "%env(API_TOKEN)%"
    
  3. Fallback Data: Provide fallback data if the API is unavailable:

    driver:
        options:
            fallback_data: "@=service('app.fallback_data_provider').getData()"
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui