我有一个带有字段的表单是一个集合,这个集合必须有固定数量的元素。我怎么验证这个?
答案 0 :(得分:0)
为拥有该集合的实体编写自定义回调验证程序。
例如,如果你有购物车实体和产品系列,你应该这样做:
...............
use Symfony\Component\Validator\Constraints as Assert;
...............
* @Assert\Callback(
* methods={"hasCorrectNumberOfProducts"}
* )
class Cart
{
...........
public function hasCorrectNumberOfProducts(ExecutionContext $context)
{
$propertyPath = $context->getPropertyPath();
$correct = 666;
if(!count($this->getProducts()) == $correct) {
$context->setPropertyPath($propertyPath . '.products');
$context->addViolation('Incorrect number of products!', array(), null);
}
}
......