src/Form/EventListener/AddFederalEntityFieldSubscriber.php line 38

Open in your IDE?
  1. <?php
  2. namespace App\Form\EventListener;
  3. use App\Entity\Locality;
  4. use App\Entity\Municipality;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\Form\FormEvent;
  9. use Symfony\Component\Form\FormInterface;
  10. use App\Entity\FederalEntity;
  11. class AddFederalEntityFieldSubscriber implements EventSubscriberInterface
  12. {
  13.     private $em;
  14.     public function __construct(EntityManagerInterface $em)
  15.     {
  16.         $this->em $em;
  17.     }
  18.     private function addField(FormInterface $form, ?Locality $locality)
  19.     {
  20.         $data = ($locality) ? $locality->getMunicipality()->getFederalEntity() : null ;
  21.         $preferredChoices $this->em->getRepository(FederalEntity::class)->find(12);
  22.         $form
  23.             ->add('federalEntity'EntityType::class,[
  24.                 'class' => FederalEntity::class,
  25.                 'placeholder' => 'Seleccione el nombre de la Entidad Federativa',
  26.                 'mapped' => false,
  27.                 'data' => $data,
  28.                 //'preferred_choices' => [$preferredChoices]
  29.             ]);
  30.     }
  31.     public function onFormPreSetData(FormEvent $event)
  32.     {
  33.         $data$event->getData();
  34.         $form $event->getForm();
  35.         $locality = (!$data || null === $data->getId()) ? null $data->getLocality();
  36.         $this->addField($form$locality);
  37.     }
  38.     public static function getSubscribedEvents()
  39.     {
  40.         return [
  41.             'form.pre_set_data' => 'onFormPreSetData',
  42.         ];
  43.     }
  44. }