How to make text field compulsory only when the checkbox is checked with symfony annotation validations in model classes -


it simple question i've run out of juice here. vat field compulsory when isvatable checkbox check user otherwise can ignored. how achieve group validation (annotations) in model class, not entity?

i checked validation groups , group sequence honest didn't head around.

formtype

class usertype extends abstracttype {     public function buildform(formbuilderinterface $builder, array $options = [])     {         $builder             ->setmethod($options['method'])             ->setaction($options['action'])             ->add('vat', 'text')             ->add('isvatable', 'checkbox')         ;     }      public function getname()     {         return 'user';     }      public function setdefaultoptions(optionsresolverinterface $resolver)     {         $resolver->setdefaults(             ['data_class' => 'my\frontendbundle\model\usermodel']         );     } } 

modelclass

class usermodel {     /**      * @assert\notblank(message="vat required when checkbox checked.")      */     protected $vat;      /**      * @var bool      */     protected $isvatable = false; } 

i find @assert\true() constraint on method works me these sorts of validation scenario. can add validation constraints methods properties, pretty powerful.

the basic idea can create method, give annotation - if method returns true validation passes; if returns false fails.

class usermodel {     /**      * @var string      */     protected $vat;      /**      * @var bool      */     protected $isvatable = false;      /**      * @assert\true(message="please enter vat number")      */     public function isvatsetwhenisvatablechecked()     {         // if property unchecked don't         // want validation return true         if (!$this->isvatable) {             return true;         }          // return true if $this->vat not null         // might want add additional          // validation here make sure          return !is_null($this->vat);     } } 

additionally, can map error message specific form field error_mapping option in formtype object, documented here:

http://symfony.com/blog/form-goodness-in-symfony-2-1#error-mapping-fu

hope helps :)


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -