symfony - Entity validation - either zero or at least three -


i'm using symfony 2.8 version , have encountered following problem. want field 'seealso' of entity 'article' restricted have either 0 (none) or @ least 3 objects (another articles). have these in yaml validation:

seealso:  - count:    min: 3    minmessage: 'you have got pick 0 or @ least 3 articles' 

it checks if less 3 well, not allow me let field empty. how make work?

you should define custom validation. can proceed in 2 ways

1 create custom validation constraint

first of need create constraint class

use symfony\component\validator\constraint;  /**  * @annotation  */ class constraintzerooratleastthreeconstraint extends constraint {     public $message = 'put here validation error message';      public function validatedby()     {         return get_class($this).'validator';     } } 

here have defined constraint message , you're telling symfony validator (that we're going define below)

use symfony\component\validator\constraint; use symfony\component\validator\constraintvalidator;  class zerooratleastthreeconstraintvalidator extends constraintvalidator {     public function validate($value, constraint $constraint)     {         if (!count($value)) {             return;         }          if (count($value) >= 3) {             return;         }          $this           ->context           ->buildvalidation('you should choose 0 or @ least 3 elements')           ->addviolation();     } } 

now can use validator upon property annotating @ constraintzerooratleastthreeconstraint (that of course have import in entity file in order use)

of course can customize values 0 , 3 generalize constraint zerooratleasttimesconstraint using

public function __construct($options) {     if (!isset($options['atleasttimes'])) {         throw new missingoptionexception(...);     }      $this->atleasttimes = $options['atleasttimes']; } 

2 create callback validation function inside entity

/**  * @assert\callback  */ public function validate(executioncontextinterface $context, $payload) {     if (!count($this->getarticles()) {        return;     }      if (count($this->getarticles() >= 3) {         return;     }      $context       ->buildviolation('you should choose 0 or @ least 3 articles')       ->addviolation(); } 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -