Skip to content

Instantly share code, notes, and snippets.

@baldurrensch
Forked from merk/ApplianceTypeListener.php
Created January 28, 2013 22:30
Show Gist options
  • Save baldurrensch/4659886 to your computer and use it in GitHub Desktop.
Save baldurrensch/4659886 to your computer and use it in GitHub Desktop.
<?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'
);
}
}
<?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