src/Form/EventListener/AddCiaMenFieldSubscriber.php line 70

Open in your IDE?
  1. <?php
  2. namespace App\Form\EventListener;
  3. use App\Entity\ciaMen;
  4. use App\Entity\Cias;
  5. use Doctrine\ORM\EntityRepository;
  6. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  7. use Symfony\Component\Form\FormFactoryInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\Form\FormEvent;
  10. use Symfony\Component\Form\FormEvents;
  11. class AddCiaMenFieldSubscriber implements EventSubscriberInterface
  12. {
  13.     private $factory;
  14.     public function __construct(FormFactoryInterface $factory)
  15.     {
  16.         $this->factory $factory;
  17.     }
  18.     public static function getSubscribedEvents()
  19.     {
  20.         return [
  21.             FormEvents::PRE_SET_DATA => 'onPreSetData',
  22.             FormEvents::PRE_SUBMIT   => 'onPreSubmit',
  23.         ];
  24.     }
  25.     private function addCiaMenForm($form$ciaId)
  26.     {
  27.         $formOptions = array(
  28.             'class' => ciaMen::class,
  29.             'choice_label' => 'fullname',
  30.             'auto_initialize' => false,
  31.             'label' => 'Tramitador',
  32.             'placeholder' => 'Seleccione tramitador',
  33.             'required' => true,
  34.             'query_builder' => function (EntityRepository $er) use ($ciaId) {
  35.                 if($ciaId instanceof Cias) {
  36.                     return $er->createQueryBuilder('ciaMen')
  37.                         ->where('ciaMen.ciaId = :ciaId')
  38.                         ->andWhere('ciaMen.active = 1')
  39.                         ->orderBy('ciaMen.fullname''ASC');
  40.                 } else {
  41.                     return $er->createQueryBuilder('ciaMen')
  42.                         ->where('ciaMen.active = 1')
  43.                         ->orderBy('ciaMen.fullname','ASC');
  44.                 }
  45.             }
  46.         );
  47.         $form->add($this->factory->createNamed('ciaMenId'EntityType::class, null$formOptions));
  48.     }
  49.     public function onPreSetData(FormEvent $event)
  50.     {
  51.         $data $event->getData();
  52.         $form $event->getForm();
  53.         if(null === $data)
  54.             return;
  55.         $ciaId = ($data->getCiaId())? $data->getCiaId() : null;
  56.         $this->addCiaMenForm($form$ciaId);
  57.     }
  58.     public function onPreSubmit(FormEvent $event)
  59.     {
  60.         $data $event->getData();
  61.         $form $event->getForm();
  62.         $ciaId array_key_exists('ciaId'$data)? $data['ciaId']:null;
  63.         $this->addCiaMenForm($form$ciaId);
  64.     }
  65. }