Skip to content

Instantly share code, notes, and snippets.

@lwillems
Last active November 17, 2022 08:03
Show Gist options
  • Save lwillems/bdb662b58a0a48bc4b0d91a28434c6ad to your computer and use it in GitHub Desktop.
Save lwillems/bdb662b58a0a48bc4b0d91a28434c6ad to your computer and use it in GitHub Desktop.
Easyadmin csv export using leagueCsv and iterable (inspired from https://symfonycasts.com/screencast/easyadminbundle/global-action)
<?php
public function exportAdminData(QueryBuilder $queryBuilder, FieldCollection $fields, string $entityName): StreamedResponse
{
$headers = [];
$properties = array_keys($queryBuilder->getQuery()->setMaxResults(1)->getSingleResult(AbstractQuery::HYDRATE_ARRAY));
foreach ($properties as $property) {
$headers[$property] = ucfirst($property);
foreach ($fields as $field) {
// Override property name if a custom label was set
if ($property === $field->getProperty() && $field->getLabel()) {
$headers[$property] = $field->getLabel();
// And stop iterating
break;
}
}
}
$response = new StreamedResponse(function () use ($queryBuilder, $headers) {
$csv = Writer::createFromStream(fopen('php://output', 'w'));
$csv->insertOne(array_values($headers));
$csv->addFormatter(function (array $data) {
return $this->serializer->normalize($data);
});
$csv->insertAll($queryBuilder->getQuery()->toIterable([], AbstractQuery::HYDRATE_ARRAY));
});
$dispositionHeader = $response->headers->makeDisposition(
HeaderUtils::DISPOSITION_ATTACHMENT,
sprintf('%s_%s.csv', $entityName, (new \DateTime)->format('Y-m-d_H:i:s'))
);
$response->headers->set('Content-Disposition', $dispositionHeader);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
return $response;
}
<?php
public function export(AdminContext $context, FilterFactory $filterFactory, CsvService $csvService): Response
{
$fields = FieldCollection::new($this->configureFields(Crud::PAGE_INDEX));
$filters = $filterFactory->create($context->getCrud()->getFiltersConfig(), $fields, $context->getEntity());
$queryBuilder = $this->createIndexQueryBuilder($context->getSearch(), $context->getEntity(), $fields, $filters);
try {
return $csvService->exportAdminData($queryBuilder, $fields, $context->getEntity()->getName());
} catch (NoResultException $exception) {
$this->addFlash('danger', 'Can not export as csv if no line match !');
return $this->redirect($context->getReferrer());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment