-
-
Save onema/6060077 to your computer and use it in GitHub Desktop.
Form PatchSubsciber for Symfony 2.3. This Form Event Subscriber will help prepare data for a PATCH request. It can be added in your CustomFormType::buildForm method.
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\EventSubscriber; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
use Symfony\Component\Form\FormEvents; | |
use Symfony\Component\Form\FormEvent; | |
/** | |
* Changes Form->submit() behavior so that it treats not set values as if they | |
* were sent unchanged. | |
* | |
* Use when you don't want fields to be set to NULL when they are not displayed | |
* on the page (or to implement PUT/PATCH requests). | |
* @link https://gist.github.com/makasim/3720535 for more information | |
*/ | |
class PatchSubscriber implements EventSubscriberInterface | |
{ | |
public function onPreSubmit(FormEvent $event) | |
{ | |
$form = $event->getForm(); | |
$clientData = $event->getData(); | |
$clientData = array_replace($this->prepareData($form), $clientData ?: array()); | |
$event->setData($clientData); | |
} | |
/** | |
* Returns the form's data like $form->submit() expects it | |
*/ | |
protected function prepareData($form) | |
{ | |
if ($form->count()) { | |
$data = array(); | |
foreach ($form->all() as $name => $child) { | |
$data[$name] = $this->prepareData($child); | |
} | |
return $data; | |
} else { | |
return $form->getViewData(); | |
} | |
} | |
static public function getSubscribedEvents() | |
{ | |
return array( | |
FormEvents::PRE_SUBMIT => 'onPreSubmit', | |
); | |
} | |
} |
Hi, thank you for this patch it's been very useful. However, I've had a little problem with boolean field, rendered as a checkbox. When unchecked, to set the field to false, it's considered empty and then replaced by the patch and set to true. Am I missing somehting, how can I deal with that?
Thank you
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, thank you for the patch. $options['method'] is always "POST" here. Nevertheless, I kicked this condition, because I dont need it. Thanks again.