Last active
June 26, 2017 06:32
-
-
Save makasim/3720535 to your computer and use it in GitHub Desktop.
form partial bind
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 Foo\CoreBundle\Form\EventListener; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
use Symfony\Component\Form\FormEvents; | |
use Symfony\Component\Form\FormEvent; | |
use Symfony\Component\Form\FormInterface; | |
/** | |
* 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 | |
{ | |
/** | |
* @param \Symfony\Component\Form\FormEvent $event | |
*/ | |
public function onPreBind(FormEvent $event) | |
{ | |
$clientData = $event->getData(); | |
$unbindClientData = $this->unbind($event->getForm()); | |
if (is_array($unbindClientData)) { | |
$clientData = array_replace($unbindClientData, $clientData ?: array()); | |
} | |
$event->setData($clientData); | |
} | |
/** | |
* Returns the form's data like $form->bind() expects it | |
* | |
* @return mixed | |
*/ | |
protected function unbind(FormInterface $form) | |
{ | |
if (count($form) > 0) { | |
$clientData = array(); | |
foreach ($form as $name => $childForm) { | |
$clientData[$name] = $this->unbind($childForm); | |
} | |
return $clientData; | |
} | |
return $form->getViewData(); | |
} | |
/** | |
* @return string[] | |
*/ | |
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
Nice works. Unfortunately the subscriber doesnt works for unmapped form fields.