Skip to content

Instantly share code, notes, and snippets.

@miguelplazasr
Created September 8, 2015 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miguelplazasr/1bfd9da929527237fcee to your computer and use it in GitHub Desktop.
Save miguelplazasr/1bfd9da929527237fcee to your computer and use it in GitHub Desktop.
City Subscriber for AddressType when select States
<?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