Skip to content

Instantly share code, notes, and snippets.

@b00gizm
Created July 12, 2013 13:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b00gizm/5984415 to your computer and use it in GitHub Desktop.
Save b00gizm/5984415 to your computer and use it in GitHub Desktop.
Adding a validation constraint in Symfony2 based on the existence and value of a form field via Symfony's form events. Good idea (best practice?) or dirty hack..?
<?php
namespace T7\Bundle\OAuthBundle\Form;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\ExecutionContextInterface;
use Symfony\Component\Validator\Constraints as Assert;
use T7\Bundle\OAuthBundle\Entity\User;
class LoginOrSignupType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email')
->add('password')
->add('new_user', 'choice', array(
'choices' => array(
0 => "I have a password.",
1 => "I'm new!",
),
'multiple' => false,
'expanded' => true,
'mapped' => false,
'property_path' => null,
))
;
$builder
->addEventListener(
FormEvents::PRE_BIND,
function(FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
if (isset($data['new_user']) && $data['new_user']) {
$form
->add('email', 'text', array(
'constraints' => new Assert\Email(),
))
;
}
}
)
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'T7\Bundle\OAuthBundle\Entity\User',
));
}
public function getName()
{
return 'user';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment