如何设置表单中字段的最小值?

时间:2019-05-29 07:59:22

标签: symfony symfony3.x

我有一个带有整数字段的表格-价格。

$builder->add('list',
            CollectionType::class,
            [
                'required' => false,
                'allow_add' => true,
                'error_bubbling' => true,
            ])
            ->add('price',
            IntegerType::class,
            [
                'required' => false,
                'error_bubbling' => true,
            ]);

例如,如何设置以进行验证,我需要价格等于或大于0的最小值?

我尝试了这个,但是不起作用:

'constraints' => [
new GreaterThanOrEqual(50)
 ],

感谢所有帮助。

控制器动作

 public function getProductAction(Request $request)
    {
        $variables = $request->get('list');

        $price = $request->get('price');

        $form = $this->createForm(ProductForm::class, null, ['csrf_protection' => false, 'allow_extra_fields' => true]);

        $form->submit(['variables' => $variables, 'prices' => $price]);

        if(!$form->isValid()) {

            $errors = '';

            foreach ($form->getErrors() as $error) {
                $errors = $error->getMessage();
            }

            return new JsonResponse([
                'errors' => $errors
            ],Response::HTTP_BAD_REQUEST);
        } else {

            $product = $this->getDoctrine()
                ->getRepository(Product::class)
                ->findByListAndPrice($list, $price);

            if (!$product) {
                return new JsonResponse([
                    'errors' => 'Product not found.'
                ],Response::HTTP_BAD_REQUEST);
            }

            return new JsonResponse($product);
        }
    }

$ form-> isValid()=== true

,表单未通过验证,也不显示错误

2 个答案:

答案 0 :(得分:1)

根据https://github.com/symfony/symfony/issues/3533,即使文档中未提及,您也可以将minmax一起使用。

IntegerType

答案 1 :(得分:1)

您可以使用RangeType代替IntegerType。

use Symfony\Component\Form\Extension\Core\Type\RangeType;
// ...

$builder->add('list',
    CollectionType::class,
    [
        'required' => false,
        'allow_add' => true,
        'error_bubbling' => true,
    ])
    ->add('price',
    RangeType::class,
    [
        'required' => false,
        'error_bubbling' => true,
        'min' => 0,
        'max' => 50
    ]);