Madhab452
Madhab452

Reputation: 323

Symfony validate a property if another property is not not blank

I have a class

Class SubjectSegment{ 
 /**
 *@CustomAssert\MyCitizenshipNumber()
 */ 
 private $citizenshipNumber; 
 /**
 *@CustomAssert\MyDate()
 */ 
 private $citizenshipNumberIssuedDate;
}

what i really want to do is valid citizenshipNumberIssuedDate if citizenshipNumber is present...

What is the best way to achieve this

Upvotes: 4

Views: 3145

Answers (3)

Madhab452
Madhab452

Reputation: 323

Class SubjectSegment{   

    /**  
    *@CustomAssert\MyCitizenshipNumber()  
    */  
    private $citizenshipNumber;   

    /** 
    *@CustomAssert\MyDate(group={"is_my_citizenship_number"})  
    */   
    private $citizenshipNumberIssuedDate;

    public function getGroupSequence(){ 
        $sequence = ['SubjectSegment']; 
        if(null != $this->CitizenshipNumber){ 
          $sequence[] = 'is_my_citizenship_number'; 
        } 
        return $sequence; 
    } 
}

validator:

$violations = $container->get('validator')->validate($segment = new SubjectSegmet(), null,$segment->getGroupSequence() );

Upvotes: 3

pietro
pietro

Reputation: 872

Hi you should look on http://symfony.com/doc/current/reference/constraints/Callback.html

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContext;

/**
 * @Assert\Callback(methods={"isCitizenDateValid"})
 */

Class SubjectSegment{ 
    /**
    *@CustomAssert\MyCitizenshipNumber()
    */ 
    private $citizenshipNumber; 
    /**
    *@CustomAssert\MyDate()
    */ 
    private $citizenshipNumberIssuedDate;

    public function isCitizenDateValid(ExecutionContext $context)
    {
        //Do your validation here for your exemple :
        if(null === $this->citizenshipNumber && null === $this->citizenshipNumberIssuedDate) {
            $context->addViolationAtSubPath('citizenshipNumberIssuedDate', 'The date is required', array(), null);
        }
    }
}

Upvotes: 4

Matteo
Matteo

Reputation: 39380

You can archive this in two way:

1) callback validator (validated by a class method)

2) With a class constraint validator

I suggest the second way, so you must configure/set the validator to class scope like:

/**
 * @Annotation
 */
class MyCitizenshipNumber  extends Constraint {

...

    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }

} 

so you can access to all class field member

Remember to put the validator on top of the class definition like:

/**
 *@CustomAssert\MyCitizenshipNumber()
 */ 
 Class SubjectSegment{ 

 private $citizenshipNumber; 

 /**
 *@CustomAssert\MyDate()
 */ 
 private $citizenshipNumberIssuedDate;
}

Hope this help

Upvotes: 3

Related Questions