Ambu
Ambu

Reputation: 194

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

I have the following code:

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()]
            ])
}

The twig form is as follows:

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

However, the rendered form (HTML) still allows users to input values with a minus sign. How do I change that, so the rendered form forbids minus sign and stops at 1 on the arrow input?

Upvotes: 3

Views: 2370

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39264

You will have to add the HTML5 min attribute for that, which you can add at the definition of your form field:

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
            ]
        ])
}

Upvotes: 6

Related Questions