Trong bài trước chúng ta đã học cách Tuỳ biến Grid (fields, filters, actions, pagination).
Ở bài cuối của series này, chúng ta sẽ đi sâu hơn vào các tình huống thực tế phức tạp mà nhiều dự án Sylius gặp phải:
-
Hiển thị dữ liệu từ API hoặc service bên ngoài (không phải Doctrine).
-
Tích hợp tính năng Export CSV/Excel.
-
Đưa grid vào dashboard admin.
-
Một số tip tối ưu performance khi làm việc với dataset lớn.
1. Grid với data source không phải Doctrine
Mặc định, Sylius Grid dùng Doctrine/ORM driver để query database. Nhưng bạn hoàn toàn có thể lấy dữ liệu từ service, repository custom, hoặc API ngoài.
Ví dụ: tạo grid hiển thị danh sách log từ một service ngoài.
sylius_grid:
grids:
app_admin_logs:
driver:
name: service
options:
service: App\Service\LogsProvider
fields:
id:
type: string
label: ID
message:
type: string
label: Message
createdAt:
type: datetime
label: Created At
Service LogsProvider phải implement GridDriverInterface (hoặc trả về Pagerfanta/DoctrineQueryBuilder tương thích).
namespace App\Service;
use Sylius\Component\Grid\Data\DataSourceInterface;
use Sylius\Component\Grid\Data\DataSourceProviderInterface;
class LogsProvider implements DataSourceProviderInterface
{
public function getDataSource(array $configuration): DataSourceInterface
{
// Call API ngoài và convert dữ liệu
$logs = [
['id' => 1, 'message' => 'Order created', 'createdAt' => new \DateTime()],
['id' => 2, 'message' => 'Order shipped', 'createdAt' => new \DateTime()],
];
return new ArrayDataSource($logs); // class bạn tự implement
}
}
Với cách này, grid không còn phụ thuộc vào Doctrine, mà lấy được data từ bất kỳ nguồn nào.
2. Export dữ liệu từ Grid
Một nhu cầu phổ biến là xuất dữ liệu ra CSV hoặc Excel, trong Sylius chúng ta có 2 hướng làm:
2.1. Dùng plugin sẵn có
-
FriendsOfSylius/SyliusGridExportPlugin: hỗ trợ export grid sang CSV/Excel.
-
Cấu hình nhanh, tự động thêm nút Export vào grid.
composer require friendsofsylius/sylius-grid-export-plugin
Cấu hình:
sylius_grid:
grids:
app_admin_order:
actions:
main:
export:
type: export
label: Export
options:
format: csv
Sau khi cài plugin, grid sẽ có nút Export ra CSV.
2.2. Tự viết action Export
Nếu bạn muốn custom định dạng file, có thể tự viết action:
actions:
main:
export_csv:
type: link
label: Export CSV
options:
link:
route: app_admin_order_export_csv
// Controller
#[Route('/admin/orders/export/csv', name: 'app_admin_order_export_csv')]
public function exportCsv(OrderRepository $repo): Response
{
$orders = $repo->findAll();
$csv = fopen('php://memory', 'w+');
fputcsv($csv, ['Number', 'Email', 'Total']);
foreach ($orders as $order) {
fputcsv($csv, [$order->getNumber(), $order->getCustomer()->getEmail(), $order->getTotal()]);
}
rewind($csv);
return new Response(stream_get_contents($csv), 200, [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="orders.csv"',
]);
}
Kết quả: click Export → tải về file CSV chứa danh sách order.
3. Grid trong dashboard admin
Bạn có thể dùng grid như widget trong dashboard. Ví dụ: hiển thị 5 đơn hàng mới nhất.
Controller:
public function dashboard(OrderRepository $repo): Response
{
$latestOrders = $repo->findBy([], ['createdAt' => 'DESC'], 5);
return $this->render('Admin/Dashboard/index.html.twig', [
'latestOrders' => $latestOrders,
]);
}
Twig file:
<h3>Latest Orders</h3>
<table class="table">
<thead>
<tr><th>Number</th><th>Email</th><th>Total</th></tr>
</thead>
<tbody>
{% for order in latestOrders %}
<tr>
<td>{{ order.number }}</td>
<td>{{ order.customer.email }}</td>
<td>{{ order.total|sylius_money(order.currencyCode) }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Bạn có thể reuse grid config hoặc chỉ render dữ liệu raw cho nhanh.
4. Tối ưu performance cho grid lớn
Khi grid có 10k+ record, bạn sẽ thấy query chậm. Một số tips:
-
Luôn bật pagination (limits: [10, 25, 50]).
-
Thêm index trong DB cho field dùng filter/sorting.
-
Dùng partial hydration (chỉ select cột cần thiết).
-
Với data khổng lồ, hãy cân nhắc dùng Elasticsearch/Kibana thay vì grid.
5. Kết luận
Trong bài này, bạn đã học cách nâng cấp Grid Sylius với:
-
Data source ngoài (service/API).
-
Export CSV/Excel (dùng plugin hoặc tự viết).
-
Dashboard widget.
-
Tips tối ưu performance khi grid lớn.
Như vậy, sau series 3 bài, chúng ta đã đi từ cơ bản đến nâng cao:
-
Giới thiệu Grid.
-
Tuỳ biến Grid (fields, filters, actions, pagination).
-
Grid nâng cao (API, export, dashboard, performance).
Grid trong Sylius không chỉ là bảng hiển thị, mà là một mini framework quản lý dữ liệu cực kỳ mạnh mẽ.
Dong Nguyen
Software Engineer.
BÌNH LUẬN
Địa chỉ email của bạn sẽ không được công khai.