Add a html5 number field in a drupal 8 or 9 form

The form API in core is great, but without contributed modules it lacks a bit of sweetness for html 5. This snippet shows you how:

$form['price'] = array(
    '#type' => 'textfield',
    '#attributes' => array(
        ' type' => 'number', // Note the space!
    ),
    '#title' => 'Price',
    '#required' => true,
    '#maxlength' => 3
);

 

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!