Drupal developer

Allow decreasing or increasing of quantity in Drupal Commerce without Javascript

Posted on 20. October 2015 - 11:00 in category Drupal Commerce, Drupal 7

There are many ways how you can improve user experience. One of them is proper use of HTML5 elements. Unfortunatelly Drupal 7 was released before these elements were widely used. So these fields aren't in core (look forward for Drupal 8 because it will support them natively). But in Drupal world there is contrib module for almost everything and you can get support of them with Elements module. In an ideal world that was all, but we are not living in them.

This module just extends Form API to support new input types like url, email, search, tel, number or range. This means that do not download this modue unless some other module depends on it. Sadly, not many modules support them and rather stick with default fields. But with few lines of code it's possible to use them anyway and make UX much better.

How number field make it better?

Firstly, I must admit that number field has limited support in browsers. It is well supported in desktop browsers Chrome, Firefox, Opera or Safari. Support in mobile browsers is often limited to just show number keyboard on focus (but this also enhance UX a lot!).

If you are looking for bulletproof solution I'm afraid Javascript is your only option. There is contrib module for that Commerce Extra Quantity. But personally I'm not big fan of imitation form fields function with Javascript solutions, because it's really hard to get it right on different viewports and browsers. This is example of native number field from Safari 9 (it looks similar in other browsers):

Extend Drupal Commerce to support HTML5 number input field

Just paste this code to your custom module and everything works out of the box. Now you can change quantity in cart summary with plus or minus buttons. It's even possible to set min and max values.

<?php
function hook_form_alter(&$form, &$form_state, $form_id) {
  if(
$form_id === 'views_form_commerce_cart_form_default') {
    foreach (
$form['edit_quantity'] as $row_id => $row) {
      if(isset(
$form['edit_quantity'][$row_id]['#type'])) {
       
$form['edit_quantity'][$row_id]['#type'] = 'numberfield';
       
$form['edit_quantity'][$row_id]['#min'] = '1';
       
$form['edit_quantity'][$row_id]['#max'] = '999';
      }
    }
  }
}
?>

If you want, you can use same approach to get number field support to add to cart forms on product pages.

Comments