how to add validation to unbound form field in symfony2

后端 未结 2 1930
不思量自难忘°
不思量自难忘° 2021-01-03 14:39

I am trying to validate an unbound field in my symfony2 form.

I have googled it and found several similar solutions, so I did a copy-paste and put my own stuff in th

相关标签:
2条回答
  • 2021-01-03 15:16

    CallbackValidator FQCN should be Symfony\Component\Form\CallbackValidator .

    0 讨论(0)
  • 2021-01-03 15:33

    So, for anyone else needing validation for unbound form fields in symfony 2 here Is how I ended up doing it - turned out I was missing a bunch of use statements, they weren't listed on any of the sites where I found other threads on the subject.

    I have weeded out everything but the essentials. Thanks to m2mdas for helping me along on this one.

    <?php
    
    namespace BizTV\UserBundle\Form;
    
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilder;
    use Symfony\Component\Form\FormInterface;
    use Symfony\Component\Form\CallbackValidator;
    use Symfony\Component\Form\FormValidatorInterface;
    use Symfony\Component\Form\FormError;
    
    
    use Doctrine\ORM\EntityRepository;
    
    class newServerType extends AbstractType
    {
    
        public function buildForm(FormBuilder $builder, array $options)
        {   
            $builder->add('screenName', null, array('property_path' => false, 'label' => 'Namn på skärmen (användaren kan ändra det senare) '));
    
            $builder-> addValidator(new CallbackValidator(function(FormInterface $form){
              $screenName = $form->get('screenName')->getData();
                if (empty($screenName)) {
                  $form['screenName']->addError(new FormError("Du måste ange ett namn för den nya skärmen"));
                }
            }));    
        }
    
        public function getName()
        {
            return 'biztv_userbundle_newservertype';
        }
    }
    
    0 讨论(0)
提交回复
热议问题