Skip to content

Instantly share code, notes, and snippets.

@stof
Created January 23, 2014 09:09
Show Gist options
  • Save stof/8575380 to your computer and use it in GitHub Desktop.
Save stof/8575380 to your computer and use it in GitHub Desktop.
Allowing extra keys in forms by removing them from the submitted data
<?php
namespace Acme\DemoBundle\Form;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormBuilderInterface;
class ExtraKeysExtension extends AbstractTypeExtension
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventSubscriber(new ExtraKeysListener());
}
public function getExtendedType()
{
return 'form';
}
}
<?php
namespace Acme\DemoBundle\Form;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ExtraKeysListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
// The priority must be lower than the event listener of the CollectionType to avoid breaking it
return array(FormEvents::PRE_SUBMIT => array('cleanData', -5));
}
public function cleanData(FormEvent $event)
{
$form = $event->getForm();
$data = $event->getData();
if (!is_array($data)) {
return;
}
$data = array_intersect_key($data, $form->all());
$event->setData($data);
}
}
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="acme_demo.form.extra_keys_extension" class="Acme\DemoBundle\Form\ExtraKeysExtension">
<tag name="form.type_extension" alias="form" />
</service>
</services>
</container>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment