doctorx32/sylius-grid-json-driver-bundle
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],
];
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 }
API Requirements:
Ensure the target API endpoint (/api/products) returns a Sylius Grid-compatible JSON response with matching field/filter names.
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
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 }
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
Pagination Handling: Configure pagination via grid options:
driver:
options:
url: "/api/orders"
pagination:
enabled: true
limit: 20
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
/v1/products) to avoid breaking changes.options.auth or use Symfony’s HTTP client middleware.onFailure event to handle API errors gracefully (e.g., show a fallback message).HttpClient with a test server:
$client = static::createClient();
$client->getContainer()->set('sylius_grid.driver.json.client', new MockHttpClient());
Field Name Mismatches:
label overrides in YAML or preprocess API data with a custom driver extension.CORS Issues:
Pagination Conflicts:
?page=1 while others use ?offset=0&limit=20. Configure pagination explicitly:
driver:
options:
pagination:
type: offset # or "page"
Rate Limiting:
Data Type Mismatches:
string, money). Use custom field types or preprocess data:
fields:
"[created_at]":
type: datetime
options:
format: "Y-m-d H:i:s"
Check API Responses: Enable debug mode and inspect the raw JSON response:
driver:
options:
debug: true # Logs API responses to Symfony's profiler
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.
Symfony Profiler:
Use the profiler to inspect grid driver events (e.g., sylius_grid.driver.json.fetch).
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'
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);
}
Override Templates:
Customize how data is rendered by overriding the grid’s Twig templates (e.g., sylius_grid/grid/_cell.html.twig).
Host vs. URL:
host for the base URL and url for the endpoint path. Avoid hardcoding full URLs in url.driver:
options:
host: "https://api.example.com"
url: "/v1/products"
Environment Variables:
Dynamically set host or auth via environment variables:
driver:
options:
host: "%env(API_HOST)%"
auth: "%env(API_TOKEN)%"
Fallback Data: Provide fallback data if the API is unavailable:
driver:
options:
fallback_data: "@=service('app.fallback_data_provider').getData()"
How can I help you explore Laravel packages today?