Created
September 8, 2015 01:40
-
-
Save miguelplazasr/a473b000371f167c8c9d to your computer and use it in GitHub Desktop.
Country Subscriber for AddressType
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\PropertyAccess\PropertyAccess; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
class AddCountryFieldSubscriber 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 addCountryForm($form, $country = null) | |
{ | |
$formOptions = array( | |
'class' => 'AppBundle:Country', | |
'mapped' => false, | |
'label' => 'Country', | |
'empty_value' => 'Country', | |
'attr' => array( | |
'class' => 'country_selector form-control select2', | |
), | |
); | |
if ($country) { | |
$formOptions['data'] = $country; | |
} | |
$form->add('country', '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); | |
$country = ($city) ? $city->getState()->getCountry() : null; | |
$this->addCountryForm($form, $country); | |
} | |
public function preSubmit(FormEvent $event) | |
{ | |
$form = $event->getForm(); | |
$this->addCountryForm($form); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment