<?php
namespace App\Form\EventListener;
use App\Entity\Locality;
use App\Entity\Municipality;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormInterface;
use App\Entity\FederalEntity;
class AddFederalEntityFieldSubscriber implements EventSubscriberInterface
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
private function addField(FormInterface $form, ?Locality $locality)
{
$data = ($locality) ? $locality->getMunicipality()->getFederalEntity() : null ;
$preferredChoices = $this->em->getRepository(FederalEntity::class)->find(12);
$form
->add('federalEntity', EntityType::class,[
'class' => FederalEntity::class,
'placeholder' => 'Seleccione el nombre de la Entidad Federativa',
'mapped' => false,
'data' => $data,
//'preferred_choices' => [$preferredChoices]
]);
}
public function onFormPreSetData(FormEvent $event)
{
$data= $event->getData();
$form = $event->getForm();
$locality = (!$data || null === $data->getId()) ? null : $data->getLocality();
$this->addField($form, $locality);
}
public static function getSubscribedEvents()
{
return [
'form.pre_set_data' => 'onFormPreSetData',
];
}
}