Created
September 8, 2015 01:40
-
-
Save miguelplazasr/eb8e9d987596859842a3 to your computer and use it in GitHub Desktop.
States Subscriber for AddressType when Select Countries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace AppBundle\Form\EventListener; | |
use Symfony\Component\Form\FormEvent; | |
use Symfony\Component\Form\FormEvents; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
use Symfony\Component\PropertyAccess\PropertyAccess; | |
use Doctrine\ORM\EntityRepository; | |
class AddStateFieldSubscriber implements EventSubscriberInterface { | |
private $propertyPathToCity; | |
public function __construct($propertyPathToCity) { | |
$this->propertyPathToCity = $propertyPathToCity; | |
} | |
public static function getSubscribedEvents() { | |
return array( | |
FormEvents::PRE_SET_DATA => 'preSetData', | |
FormEvents::PRE_SUBMIT => 'preSubmit' | |
); | |
} | |
private function addStateForm($form, $country_id, $state = null) { | |
$formOptions = array( | |
'class' => 'AppBundle:State', | |
'empty_value' => 'State', | |
'label' => 'State', | |
'mapped' => false, | |
'attr' => array( | |
'class' => 'state_selector form-control', | |
), | |
'query_builder' => function (EntityRepository $repository) use ($country_id) { | |
$qb = $repository->createQueryBuilder('s') | |
->innerJoin('s.country', 'c') | |
->where('c.id = :country') | |
->orderBy('s.name', 'ASC') | |
->setParameter('country', $country_id) | |
; | |
return $qb; | |
} | |
); | |
if ($state) { | |
$formOptions['data'] = $state; | |
} | |
$form->add('state', 'entity', $formOptions); | |
} | |
public function preSetData(FormEvent $event) { | |
$data = $event->getData(); | |
$form = $event->getForm(); | |
if (null === $data) { | |
return; | |
} | |
$accessor = PropertyAccess::createPropertyAccessor(); | |
$city = $accessor->getValue($data, $this->propertyPathToCity); | |
$state = ($city) ? $city->getState() : null; | |
$country_id = ($state) ? $state->getCountry()->getId() : null; | |
$this->addStateForm($form, $country_id, $state); | |
} | |
public function preSubmit(FormEvent $event) { | |
$data = $event->getData(); | |
$form = $event->getForm(); | |
$country_id = array_key_exists('country', $data) ? $data['country'] : null; | |
$this->addStateForm($form, $country_id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment