Created
September 8, 2015 01:41
-
-
Save miguelplazasr/1bfd9da929527237fcee to your computer and use it in GitHub Desktop.
City Subscriber for AddressType when select States
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 AddCityFieldSubscriber implements EventSubscriberInterface { | |
private $propertyPathToCity; | |
public function __construct($propertyPathToCity) { | |
$this->propertyPathToCity = $propertyPathToCity; | |
} | |
public static function getSubscribedEvents() { | |
return array( | |
FormEvents::POST_SET_DATA => 'preSetData', | |
FormEvents::PRE_SUBMIT => 'preSubmit' | |
); | |
} | |
private function addCityForm($form, $state_id) { | |
$formOptions = array( | |
'class' => 'AppBundle:City', | |
'empty_value' => 'City', | |
'label' => 'City', | |
'attr' => array( | |
'class' => 'city_selector form-control', | |
), | |
'query_builder' => function (EntityRepository $repository) use ($state_id) { | |
$qb = $repository->createQueryBuilder('c') | |
->innerJoin('c.state', 's') | |
->where('s.id = :state') | |
->setParameter('state', $state_id) | |
; | |
return $qb; | |
} | |
); | |
$form->add($this->propertyPathToCity, '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_id = ($city) ? $city->getState()->getId() : null; | |
$this->addCityForm($form, $state_id); | |
} | |
public function preSubmit(FormEvent $event) { | |
$data = $event->getData(); | |
$form = $event->getForm(); | |
$state_id = array_key_exists('state', $data) ? $data['state'] : null; | |
$this->addCityForm($form, $state_id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment