src/Form/EventListener/AddMunicipalityFieldSubscriber.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\Form\EventListener;
  3. use App\Entity\FederalEntity;
  4. use App\Entity\Locality;
  5. use App\Entity\Municipality;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Shapecode\Bundle\HiddenEntityTypeBundle\Form\Type\HiddenEntityType;
  8. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\Form\Extension\Core\Type\TextType;
  11. use Symfony\Component\Form\FormEvent;
  12. use Symfony\Component\Form\FormEvents;
  13. use Symfony\Component\Form\FormInterface;
  14. class AddMunicipalityFieldSubscriber implements EventSubscriberInterface
  15. {
  16.     private $em;
  17.     public function __construct(EntityManagerInterface $em)
  18.     {
  19.         $this->em $em;
  20.     }
  21.     private function addField(FormInterface $form, ?Locality $locality)
  22.     {
  23.         $federalEntity $locality $locality->getMunicipality()->getFederalEntity() : null;
  24.         $choices $federalEntity $federalEntity->getMunicipalities() : [];
  25.         $data $locality $locality->getMunicipality() : null;
  26.         $form
  27.             ->add('municipality'EntityType::class,[
  28.                 'class' => Municipality::class,
  29.                 'placeholder' => '...',
  30.                 'mapped' => false,
  31.                 'choices' => $choices,
  32.                 'data' => $data,
  33.             ]);
  34.     }
  35.     public function onFormPreSetData(FormEvent $event)
  36.     {
  37.         $data$event->getData();
  38.         $form $event->getForm();
  39.         $locality = (!$data || null === $data->getId()) ? null $data->getLocality();
  40.         $this->addField($form$locality);
  41.     }
  42.     public function onFormPreSubmit(FormEvent $event)
  43.     {
  44.         $data$event->getData();
  45.         $form $event->getForm();
  46.         $localityId  $data['locality']; 
  47.         $locality $this->em->getRepository(Locality::class)->find($localityId);
  48.         $this->addField($form$locality);
  49.       
  50. //        $documentTypeId = $data['documentType'];
  51. //        $documentType = $this->em->getRepository(DocumentType::class)->find($documentTypeId);
  52. //        $documents = $documentType->getDocuments();
  53. //        $this->addField($form, $documentType, $documents);
  54.     }
  55.     public static function getSubscribedEvents()
  56.     {
  57.         return [
  58.             'form.pre_set_data' => 'onFormPreSetData',
  59.             FormEvents::PRE_SUBMIT => 'onFormPreSubmit',
  60.         ];
  61.     }
  62. }