symfony 验证另一个字段是否为特定值

symfony validates if another field is specific value

如果另一个字段 (3) 是选项 'a',我正在尝试为一个字段 (1) 编写一个验证,如果 3 是 [=18=,则另一个字段 (2) 是必需的].我该怎么做?

编辑: 它适用于实体。我会 post 我正在尝试的示例。

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

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

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

如果 $3 == 'a',我需要 $1,如果 $3 =='b',我需要 $2。

您可以尝试使用回调约束:http://symfony.com/doc/current/reference/constraints/Callback.html

您可以使用验证约束:Expression

示例:

/**
* @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;   
}