<?php
namespace App\Form\EventListener;
use App\Entity\Cias;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\PropertyAccess\PropertyAccess;
class AddCiaFieldSubscriber implements EventSubscriberInterface
{
private $factory;
public function __construct(FormFactoryInterface $factory)
{
$this->factory = $factory;
}
public static function getSubscribedEvents()
{
return [
FormEvents::PRE_SET_DATA => 'onPreSetData',
FormEvents::PRE_SUBMIT => 'onPreSubmit',
];
}
private function addCiaForm($form, $cia)
{
$formOptions = array(
'class' => Cias::class,
'auto_initialize' => false,
'label' => 'Empresa',
'placeholder' => 'Seleccione empresa',
'required' => true
);
if($cia) {
$formOptions['data'] = $cia;
}
$form->add($this->factory->createNamed('ciaId', EntityType::class, null, $formOptions));
}
public function onPreSetData(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if(null === $data) {
return;
}
$cia = ($data->getCiaId()) ? $data->getCiaId()->getId() : null;
$this->addCiaForm($form, $cia);
}
public function onPreSubmit(FormEvent $event)
{
$form = $event->getForm();
$data = $event->getData();
$ciaId = array_key_exists('ciaId', $data)? $data['ciaId']:null;
$this->addCiaForm($form, $ciaId);
}
}