<?php
namespace App\Form\Subscriber;
use App\Entity\Common\Country;
use App\Entity\Common\County;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class CountrySubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private EntityManagerInterface $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents()
{
return [
FormEvents::PRE_SET_DATA => 'onPreSetData',
FormEvents::POST_SUBMIT => 'onPostSubmit'
];
}
/**
* Adds *county* field to checkout form
*
* Available options of this field depend on the value of
* *country* field. If a valid country value exists,
* then only counties of that country will be loaded, otherwise
* an empty dropdown should be presented to end user.
*
* @param FormEvent $event
*/
public function onPreSetData(FormEvent $event)
{
$country = $event->getData();
$form = $event->getForm()->getParent();
if (null !== $country) {
$form->add('county', EntityType::class, [
'required' => false,
'class' => County::class,
'choice_label' => 'name',
'placeholder' => 'Επιλέξτε νομό',
'query_builder' => function (EntityRepository $er) use ($country) {
return $er->createQueryBuilder('c')
->where('c.country = :country')
->setParameter('country', $country)
->orderBy('c.name');
},
'label' => '* Νομός'
]);
} else {
$country = $this->em->getRepository(Country::class)->find(86);
$form->add('county', EntityType::class, [
'required' => false,
'class' => County::class,
'choice_label' => 'name',
'placeholder' => 'Επιλέξτε νομό',
'label' => '* Νομός'
]);
}
}
/**
* Populates *county* form field according to selected country
*
* @param FormEvent $event
*/
public function onPostSubmit(FormEvent $event)
{
$countryId = $event->getData();
$country = $this->em->getRepository(Country::class)->find($countryId);
if (null !== $country) {
$form = $event->getForm()->getParent();
$form->add('county', EntityType::class, [
'class' => County::class,
'choice_label' => 'name',
'placeholder' => 'Επιλέξτε νομό',
'query_builder' => function (EntityRepository $er) use ($country) {
return $er->createQueryBuilder('c')
->where('c.country = :country')
->setParameter('country', $country)
->orderBy('c.name');
},
'label' => '* Νομός'
]);
}
}
}