如何强制 symfony 表单只显示和接受正整数?

How to force symfony form to only display and accept positive integers?

我有以下代码:

use Symfony\Component\Validator\Constraints\Positive;

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('x', IntegerType::class, [
            'mapped' => false,
            'required' => false,
            'constraints' => [new Positive()]
            ])
}

树枝形式如下:

{{ form_widget(form.x, { 'attr': {'class': 'form-control'} }) }}

但是,呈现的表单 (HTML) 仍然允许用户输入带负号的值。 我该如何更改它,使呈现的表单禁止减号并在箭头输入处停在 1 处?

您必须为此添加 HTML5 min attribute,您可以在表单字段的定义中添加:

use Symfony\Component\Validator\Constraints\Positive;

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('x', IntegerType::class, [
            'mapped' => false,
            'required' => false,
            'constraints' => [new Positive()],
            'attr' => [
                'min' => 1
            ]
        ])
}