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


symfony validates if another field is specific value

如果另一个字段(3)是选项"a",我正在尝试为一个字段(1)编写验证,如果另一个字段(3)是"b",则另一个字段(2)。 我该怎么做呢?

编辑:它适用于实体。 我将发布我正在尝试的示例。

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

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

您可以使用验证约束: 表达式

例:

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

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