|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace App\Trait; |
| 6 | + |
| 7 | +use App\Service\Exporter; |
| 8 | +use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection; |
| 9 | +use EasyCorp\Bundle\EasyAdminBundle\Config\Action; |
| 10 | +use EasyCorp\Bundle\EasyAdminBundle\Config\Crud; |
| 11 | +use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext; |
| 12 | +use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController; |
| 13 | +use EasyCorp\Bundle\EasyAdminBundle\Factory\FilterFactory; |
| 14 | +use Symfony\Component\Translation\TranslatableMessage; |
| 15 | + |
| 16 | +trait ExportCrudControllerTrait |
| 17 | +{ |
| 18 | + private Exporter $exporter; |
| 19 | + |
| 20 | + protected function setExporter(Exporter $exporter) |
| 21 | + { |
| 22 | + $this->exporter = $exporter; |
| 23 | + } |
| 24 | + |
| 25 | + protected function createExportAction(string|TranslatableMessage $label = null): Action |
| 26 | + { |
| 27 | + return Action::new('export', $label ?? new TranslatableMessage('Export')) |
| 28 | + ->createAsGlobalAction() |
| 29 | + ->linkToCrudAction('export'); |
| 30 | + } |
| 31 | + |
| 32 | + public function export(AdminContext $context) |
| 33 | + { |
| 34 | + if (!isset($this->exporter)) { |
| 35 | + throw new \RuntimeException(sprintf('Exporter not set in %s', static::class)); |
| 36 | + } |
| 37 | + |
| 38 | + assert($this instanceof AbstractCrudController); |
| 39 | + // Lifted from self::index(). |
| 40 | + $fields = FieldCollection::new($this->configureFields(Crud::PAGE_INDEX)); |
| 41 | + $context->getCrud()->setFieldAssets($this->getFieldAssets($fields)); |
| 42 | + $filters = $this->container->get(FilterFactory::class)->create($context->getCrud()->getFiltersConfig(), $fields, |
| 43 | + $context->getEntity()); |
| 44 | + $queryBuilder = $this->createIndexQueryBuilder($context->getSearch(), $context->getEntity(), $fields, $filters); |
| 45 | + |
| 46 | + return $this->exporter->export($queryBuilder->getQuery(), static::getEntityFqcn()); |
| 47 | + } |
| 48 | +} |
0 commit comments