-
-
Save baldurrensch/4659886 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Ibms\AppBundle\Form\EventListener; | |
use Doctrine\ORM\QueryBuilder; | |
use Ibms\SupplierBundle\Entity\Supplier; | |
use Ibms\SupplierBundle\Entity\SupplierManager; | |
use Symfony\Component\Form\FormEvent; | |
use Symfony\Component\Form\FormEvents; | |
use Symfony\Component\Form\FormFactoryInterface; | |
use Symfony\Component\Form\FormInterface; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
class ApplianceTypeListener implements EventSubscriberInterface | |
{ | |
private $factory; | |
private $fieldName; | |
private $supplierManager; | |
public function __construct($fieldName, FormFactoryInterface $factory, SupplierManager $supplierManager) | |
{ | |
$this->factory = $factory; | |
$this->fieldName = $fieldName; | |
$this->supplierManager = $supplierManager; | |
} | |
public function preBind(FormEvent $event) | |
{ | |
$form = $event->getForm(); | |
$data = $event->getData(); | |
$qb = $this->supplierManager->queryApplianceTypes(); | |
$qb->setParameter('supplierId', $data['supplier']); | |
$this->addApplianceType($form, $qb); | |
} | |
public function preSetData(FormEvent $event) | |
{ | |
$form = $event->getForm(); | |
$data = $event->getData(); | |
if (null === $data or null === $data->getSupplier()) { | |
return; | |
} | |
$qb = $this->supplierManager->queryApplianceTypes($data->getSupplier()); | |
$this->addApplianceType($form, $qb); | |
} | |
protected function addApplianceType(FormInterface $form, QueryBuilder $qb) | |
{ | |
$form->add($this->factory->createNamed($this->fieldName, 'entity', null, array( | |
'class' => 'Ibms\\SupplierBundle\\Entity\\ApplianceType', | |
'empty_value' => 'Pick one', | |
'property' => 'type', | |
'required' => false, | |
'query_builder' => $qb, | |
))); | |
} | |
public static function getSubscribedEvents() | |
{ | |
return array( | |
FormEvents::PRE_BIND => 'preBind', | |
FormEvents::PRE_SET_DATA => 'preSetData' | |
); | |
} | |
} |
This file contains hidden or 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 | |
class ConsumingType extends AbstractType | |
{ | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
// ... | |
// Handles adding a dropdown for Type given the forms set data | |
$builder->addEventSubscriber(new ApplianceTypeListener('type', $builder->getFormFactory())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment