-
-
Save breenie/5755114 to your computer and use it in GitHub Desktop.
Forked for my reference, thanks makasim!
This file contains hidden or 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 Foo; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
use Symfony\Component\Form\FormEvents; | |
use Symfony\Component\Form\FormEvent; | |
/** | |
* Changes Form->bind() 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). | |
*/ | |
class PatchSubscriber implements EventSubscriberInterface | |
{ | |
public function onPreBind(FormEvent $event) | |
{ | |
$form = $event->getForm(); | |
$clientData = $event->getData(); | |
$clientData = array_replace($this->unbind($form), $clientData ?: array()); | |
$event->setData($clientData); | |
} | |
/** | |
* Returns the form's data like $form->bind() expects it | |
*/ | |
protected function unbind($form) | |
{ | |
if ($form->hasChildren()) { | |
$ary = array(); | |
foreach ($form->getChildren() as $name => $child) { | |
$ary[$name] = $this->unbind($child); | |
} | |
return $ary; | |
} else { | |
return $form->getClientData(); | |
} | |
} | |
static public function getSubscribedEvents() | |
{ | |
return array( | |
FormEvents::PRE_BIND => 'onPreBind', | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment