9

I'm trying to write a validation for a field(1) to be required if another field(3) is option 'a', and a different field(2) if 3 is 'b'. How would I go about doing that?

EDIT: It is for an Entity. I'll post a sample of what I'm trying.

/**
*@Assert\Collection(
*fields = { aName = @Assert\NotBlank(),
*           aAmount = @Assert\NotBlank() }
*/
protected $1;

/**
*@Assert\Collection(
*fields = { bName = @Assert\NotBlank(),
*           bAmount = @Assert\NotBlank() }
*/
protected $2;

/**
*@Assert\NotBlank()
*/
protected $3;

I need $1 to be required if $3 == 'a', and $2 if $3 =='b'.

0

2 Answers 2

18

You can use validation constraint: Expression

Example:

/**
* @Assert\Expression(
 *     "not (this.getThird() == 'a' and this.getFirst() == null)",
 *     message="If third = 'a', first should be not null"
 * )
 */
protected $first;

/**
 * @Assert\Expression(
 *     "not (this.getThird() == 'b' and this.getSecond() == null)",
 *     message="If third = 'b', second should be not null"
 * )
 */
protected $second;

protected $third;

public function getFirst()
{
     return $this->first;   
}

public function getSecond()
{
     return $this->second;   
}

public function getThird()
{
     return $this->third;   
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could try with a Callback constraint : http://symfony.com/doc/current/reference/constraints/Callback.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.