2
votes

I have tried to get an input with the type "number" for the HTML5 frontend support.

My form class:

class MyType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('a', NumberType::class); // i want <input type="number" ...>
        $builder->add('b', EmailType::class); // <input type="email" ...> works
        $builder->add('c', TextareaType::class);
    }
}

The NumberType does not produce an <input type="number"> tag in the twig template with {{ form(myForm) }} like the EmailType <input type="email">.

I couldn't find an option to set the required html attribute value. 'attr' settings does not change it.

I'm using Symfony 3.

kr sebastian

2

2 Answers

3
votes

You should try IntegerType::class and don't forget the use Symfony\Component\Form\Extension\Core\Type\IntegerType; You can find a lo of help here : http://symfony.com/doc/current/reference/forms/types.html

2
votes

If you want to have the type="number" on your html you should do as @tompte answer says, but it won't render any step attribute. If you want to render the extra attributes you should add the form like so:

$builder->add('a', IntegerType::class, array('scale' => 2, 'attr' => array('step' => 0.01))); 

If you read the source code for the number_widget block you'll see this comment:

{%- block number_widget -%}
    {# type="number" doesn't work with floats #}
    {%- set type = type|default('text') -%}
    {{ block('form_widget_simple') }}
{%- endblock number_widget -%}

So that's why it's not rendering as a number when you use the NumberType class.