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
Post a Comment