Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bmunslow/a719eb828cae15bbd858e3b04970d5f9 to your computer and use it in GitHub Desktop.
Save bmunslow/a719eb828cae15bbd858e3b04970d5f9 to your computer and use it in GitHub Desktop.
Drupal 8 - Commerce 2.x - Transform quantity field in add to cart form into select list
<?php
/**
* hook_form_alter()
*
* Switch quantity field from input text to select in add_to_cart forms
* Supports both standard add_to_cart, as shipped in commerce framework
* as well as ajax add_to_cart forms implemented by dc_ajax_add_cart module
*
* It also supports quantity fields as they appear in view cart form, both with
* and without ajax functionality provided by dc_ajax_add_cart module
*
* @see https://www.drupal.org/project/commerce
* @see https://www.drupal.org/project/dc_ajax_add_cart
*/
function your_module_form_alter(&$form, $form_state, $form_id) {
$total_units_allowed = 9; // Customize this value according to site requirements
$select_options = [];
for ($i = 1; $i <= $total_units_allowed; $i++) {
$select_options[$i] = $i;
}
$add_to_cart_is_classic = strpos($form_id, 'commerce_order_item_add_to_cart_form') === 0;
$add_to_cart_is_dc_ajax = strpos($form_id, 'commerce_order_item_dc_ajax_add_cart_form') === 0;
$add_to_cart_is_views = strpos($form_id, 'views_form_mix_cart_form') === 0;
if ($add_to_cart_is_classic || $add_to_cart_is_dc_ajax) {
$form['quantity']['widget'][0]['value']['#type'] = 'select';
$form['quantity']['widget'][0]['value']['#options'] = $select_options;
}
elseif ($add_to_cart_is_views) {
$qty_key_name = 'edit_quantity';
if (isset($form['dc_ajax_add_cart_views_edit_quantity'])) {
$qty_key_name = 'dc_ajax_add_cart_views_edit_quantity';
}
$form[$qty_key_name][0]['#type'] = 'select';
$form[$qty_key_name][0]['#options'] = $select_options;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment