Created
July 12, 2013 13:21
-
-
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..?
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 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