Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save adrienbrault/3766678 to your computer and use it in GitHub Desktop.
Save adrienbrault/3766678 to your computer and use it in GitHub Desktop.
SF2 Form Event Subscriber that replace non submitted values by the default.
<?php
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
/**
* ReplaceNotSubmittedValuesByDefaultsListener
*
* @author Adrien Brault <[email protected]>
*/
class ReplaceNotSubmittedValuesByDefaultsListener implements EventSubscriberInterface
{
private $factory;
private $ignoreRequiredFields;
public function __construct(FormFactoryInterface $factory, $ignoreRequiredFields = true)
{
$this->factory = $factory;
$this->ignoreRequiredFields = $ignoreRequiredFields;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return array(FormEvents::PRE_BIND => 'preBind');
}
/**
* {@inheritdoc}
*/
public function preBind(FormEvent $event)
{
$form = $event->getForm();
$submittedData = $event->getData();
if ($form->getConfig()->getCompound()) {
foreach ($form->all() as $name => $child) {
if (!isset($submittedData[$name])
&& (!$this->ignoreRequiredFields || !$child->isRequired())) {
$submittedData[$name] = $child->getData();
}
}
}
$event->setData($submittedData);
}
}
<?php
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use JMS\DiExtraBundle\Annotation as DI;
use XXXBundle\Form\EventListener\ReplaceNotSubmittedValuesByDefaultsListener;
/**
* @DI\FormType
*/
class CollectionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$subscriber = new ReplaceNotSubmittedValuesByDefaultsListener($builder->getFormFactory());
$builder->addEventSubscriber($subscriber);
$builder->add('page', 'hidden', array('required' => false, 'attr' => array(
'id' => 'page',
)));
$builder->add('limit', 'hidden', array('required' => false, 'attr' => array(
'id' => 'limit',
)));
}
public function getName()
{
return 'XXX_rest_collection';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment