Last active
October 10, 2015 14:48
-
-
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
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\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); | |
} | |
// [ ... ] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is useful for dynamically embed form.