Skip to content

Instantly share code, notes, and snippets.

@jakzal
Last active October 10, 2015 14:48
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakzal/3707235 to your computer and use it in GitHub Desktop.
Save jakzal/3707235 to your computer and use it in GitHub Desktop.
Using Symfony2 form events to prevent overwriting not submitted fields with empty values
<?php
namespace Acme\Bundle\UserBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
class UserType extends AbstractType
{
/**
* @param FormBuilder $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', 'text', array('error_bubbling' => true))
->add('name', 'text', array('error_bubbling' => true));
$callback = function(FormEvent $event) {
if (null === $event->getData()) {
$event->setData($event->getForm()->getData());
}
};
$builder->get('email')->addEventListener(FormEvents::PRE_SUBMIT, $callback);
$builder->get('name')->addEventListener(FormEvents::PRE_SUBMIT, $callback);
}
// [ ... ]
}
@marfillaster
Copy link

This is useful for dynamically embed form.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment