<?php
namespace App\Form\EventListener;
use App\Entity\FederalEntity;
use App\Entity\Locality;
use App\Entity\Municipality;
use Doctrine\ORM\EntityManagerInterface;
use Shapecode\Bundle\HiddenEntityTypeBundle\Form\Type\HiddenEntityType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
class AddMunicipalityFieldSubscriber implements EventSubscriberInterface
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
private function addField(FormInterface $form, ?Locality $locality)
{
$federalEntity = $locality ? $locality->getMunicipality()->getFederalEntity() : null;
$choices = $federalEntity ? $federalEntity->getMunicipalities() : [];
$data = $locality ? $locality->getMunicipality() : null;
$form
->add('municipality', EntityType::class,[
'class' => Municipality::class,
'placeholder' => '...',
'mapped' => false,
'choices' => $choices,
'data' => $data,
]);
}
public function onFormPreSetData(FormEvent $event)
{
$data= $event->getData();
$form = $event->getForm();
$locality = (!$data || null === $data->getId()) ? null : $data->getLocality();
$this->addField($form, $locality);
}
public function onFormPreSubmit(FormEvent $event)
{
$data= $event->getData();
$form = $event->getForm();
$localityId = $data['locality'];
$locality = $this->em->getRepository(Locality::class)->find($localityId);
$this->addField($form, $locality);
// $documentTypeId = $data['documentType'];
// $documentType = $this->em->getRepository(DocumentType::class)->find($documentTypeId);
// $documents = $documentType->getDocuments();
// $this->addField($form, $documentType, $documents);
}
public static function getSubscribedEvents()
{
return [
'form.pre_set_data' => 'onFormPreSetData',
FormEvents::PRE_SUBMIT => 'onFormPreSubmit',
];
}
}