Skip to content

Instantly share code, notes, and snippets.

@baldurrensch
Forked from merk/ApplianceTypeListener.php
Created January 28, 2013 22:30
Show Gist options
  • Select an option

  • Save baldurrensch/4659886 to your computer and use it in GitHub Desktop.

Select an option

Save baldurrensch/4659886 to your computer and use it in GitHub Desktop.
<?php
namespace Ibms\AppBundle\Form\EventListener;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\From;
use Ibms\SupplierBundle\Entity\Supplier;
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;
public function __construct($fieldName, FormFactoryInterface $factory)
{
$this->factory = $factory;
$this->fieldName = $fieldName;
}
public function preBind(FormEvent $event)
{
$form = $event->getForm();
$data = $event->getData();
$this->addApplianceType($form, $data['supplier']);
}
public function preSetData(FormEvent $event)
{
$form = $event->getForm();
$data = $event->getData();
if (null === $data) {
return;
}
$supplierId = $data->getSupplier() ?
$data->getSupplier()->getId() :
null;
$this->addApplianceType($form, $supplierId);
}
protected function addApplianceType(FormInterface $form, $supplierId)
{
$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' => function (EntityRepository $er) use ($supplierId) {
$qb = $er->createQueryBuilder('a');
$qb->add('from', new From('Ibms\\SupplierBundle\\Entity\\Supplier', 's'), true)
->andWhere('a MEMBER OF s.applianceTypes')
->andWhere('s.id = :supplierId');
$qb->setParameters(array(
'supplierId' => $supplierId,
));
return $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