Created
January 23, 2014 09:09
-
-
Save stof/8575380 to your computer and use it in GitHub Desktop.
Allowing extra keys in forms by removing them from the submitted data
This file contains 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 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'; | |
} | |
} |
This file contains 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 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); | |
} | |
} |
This file contains 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
<?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