Skip to content

Instantly share code, notes, and snippets.

@miguelplazasr
Created September 8, 2015 01:40
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/a473b000371f167c8c9d to your computer and use it in GitHub Desktop.
Save miguelplazasr/a473b000371f167c8c9d to your computer and use it in GitHub Desktop.
Country Subscriber for AddressType
<?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