<?php
namespace App\Form\EventListener;
use App\Entity\ciaMen;
use App\Entity\Cias;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class AddCiaMenFieldSubscriber 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 addCiaMenForm($form, $ciaId)
{
$formOptions = array(
'class' => ciaMen::class,
'choice_label' => 'fullname',
'auto_initialize' => false,
'label' => 'Tramitador',
'placeholder' => 'Seleccione tramitador',
'required' => true,
'query_builder' => function (EntityRepository $er) use ($ciaId) {
if($ciaId instanceof Cias) {
return $er->createQueryBuilder('ciaMen')
->where('ciaMen.ciaId = :ciaId')
->andWhere('ciaMen.active = 1')
->orderBy('ciaMen.fullname', 'ASC');
} else {
return $er->createQueryBuilder('ciaMen')
->where('ciaMen.active = 1')
->orderBy('ciaMen.fullname','ASC');
}
}
);
$form->add($this->factory->createNamed('ciaMenId', EntityType::class, null, $formOptions));
}
public function onPreSetData(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if(null === $data)
return;
$ciaId = ($data->getCiaId())? $data->getCiaId() : null;
$this->addCiaMenForm($form, $ciaId);
}
public function onPreSubmit(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
$ciaId = array_key_exists('ciaId', $data)? $data['ciaId']:null;
$this->addCiaMenForm($form, $ciaId);
}
}