【问题标题】:How can I validate a form collection must have X number of elements?如何验证表单集合必须有 X 个元素?
【发布时间】:2012-01-30 13:55:35
【问题描述】:

我有一个表单,其中的字段是一个集合,这个集合必须有固定数量的元素。我如何验证这一点?

【问题讨论】:

    标签: validation symfony


    【解决方案1】:

    为拥有该集合的实体编写自定义回调验证器。

    例如,如果您有一个 Cart 实体和一个 Products 集合,您应该这样做:

    ...............
    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);
        }
    }
    ......
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 2014-08-05
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多