src/Form/Security/AddShopFieldSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Form\Security;
  4. use App\Entity\Franchise\Franchise;
  5. use App\Entity\Security\ShopManager;
  6. use App\Entity\Shop\Shop;
  7. use App\Form\FormHelper;
  8. use App\Repository\Shop\ShopRepository;
  9. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\Form\FormEvent;
  12. use Symfony\Component\Form\FormEvents;
  13. use Symfony\Component\HttpFoundation\RequestStack;
  14. class AddShopFieldSubscriber extends FormHelper implements EventSubscriberInterface
  15. {
  16.     public function __construct(
  17.         private RequestStack $requestStack
  18.     ) {
  19.     }
  20.     public static function getSubscribedEvents(): array
  21.     {
  22.         return [FormEvents::PRE_SET_DATA => 'preSetData'];
  23.     }
  24.     public function preSetData(FormEvent $event): void
  25.     {
  26.         $entity = $event->getData();
  27.         if (false === $entity instanceof ShopManager) {
  28.             return;
  29.         }
  30.         $franchise = $event->getForm()->has('franchise')
  31.             ? null
  32.             : $this->getFranchiseFromRequest()
  33.         ;
  34.         $event->getForm()->add('shop', EntityType::class, $this->getEntityParameters(
  35.             Shop::class,
  36.             'app.admin.pages.shops.form.shop',
  37.             null,
  38.             true,
  39.             ['query_builder' => fn (ShopRepository $repository) => $repository->getDefaultQB($franchise, true)]
  40.         ));
  41.     }
  42.     private function getFranchiseFromRequest(): ?Franchise
  43.     {
  44.         $request = $this->requestStack->getCurrentRequest();
  45.         if (null === $request || false === $request->hasSession()) {
  46.             return null;
  47.         }
  48.         $session = $request->getSession();
  49.         return $session->get('franchise');
  50.     }
  51. }