2

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 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.