src/Form/EventListener/AddCiaFieldSubscriber.php line 62

Open in your IDE?
  1. <?php
  2. namespace App\Form\EventListener;
  3. use App\Entity\Cias;
  4. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\Form\FormEvent;
  7. use Symfony\Component\Form\FormFactoryInterface;
  8. use Symfony\Component\Form\FormEvents;
  9. use Symfony\Component\PropertyAccess\PropertyAccess;
  10. class AddCiaFieldSubscriber implements EventSubscriberInterface
  11. {
  12.     private $factory;
  13.     public function __construct(FormFactoryInterface $factory)
  14.     {
  15.         $this->factory $factory;
  16.     }
  17.     public static function getSubscribedEvents()
  18.     {
  19.         return [
  20.             FormEvents::PRE_SET_DATA => 'onPreSetData',
  21.             FormEvents::PRE_SUBMIT   => 'onPreSubmit',
  22.         ];
  23.     }
  24.     private function addCiaForm($form$cia)
  25.     {
  26.         $formOptions = array(
  27.             'class' => Cias::class,
  28.             'auto_initialize' => false,
  29.             'label' => 'Empresa',
  30.             'placeholder' => 'Seleccione empresa',
  31.             'required' => true
  32.         );
  33.         if($cia) {
  34.             $formOptions['data'] = $cia;
  35.         }
  36.         $form->add($this->factory->createNamed('ciaId'EntityType::class, null$formOptions));
  37.     }
  38.     public function onPreSetData(FormEvent $event)
  39.     {
  40.         $data $event->getData();
  41.         $form $event->getForm();
  42.         if(null === $data) {
  43.             return;
  44.         }
  45.         $cia = ($data->getCiaId()) ? $data->getCiaId()->getId() : null;
  46.         $this->addCiaForm($form$cia);
  47.     }
  48.     public function onPreSubmit(FormEvent $event)
  49.     {
  50.         $form $event->getForm();
  51.         $data $event->getData();
  52.         $ciaId array_key_exists('ciaId'$data)? $data['ciaId']:null;
  53.         $this->addCiaForm($form$ciaId);
  54.     }
  55. }