Skip to content

Instantly share code, notes, and snippets.

@onatskyy
Forked from makasim/gist:3720535
Last active August 29, 2015 14:10
Show Gist options
  • Save onatskyy/1d54086f2faa3b4cab2e to your computer and use it in GitHub Desktop.
Save onatskyy/1d54086f2faa3b4cab2e to your computer and use it in GitHub Desktop.
<?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