How to add some buttons to add to cart form

by briast   Last Updated May 21, 2020 16:07 PM

I would like to add some buttons to my add to cart form to alter the quantity input. I want two buttons for +1 and -1, and two other buttons for +12 and -12. This is the code I use in my .module to add the first button, but without success.

/**
 * Implements hook_form_alter()
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'commerce_order_item_dc_ajax_add_cart_form_') === 0) {        
    $form['quantity']['widget']['0']['#prefix'] = '<div id="quantity-wrapper">';
    $form['quantity']['widget']['0']['#suffix'] = '</div>';    

    $form['actions']['add_qty'] = [
    '#type' => 'button',
    '#value' => t('+1'),
    '#ajax' => [
      'callback' => '_add_one_callback',
      'wrapper' => 'quantity-wrapper',
     ],
    ];    
  }
}
/**
* Increments +1 and rebuild.
 */
function _add_one_callback(array &$form, FormStateInterface $form_state) {
  $quantity = $form_state->get('quantity');
  $quantity= $quantity + 1;
  $form_state->set('quantity', $quantity);
  $form_state->setRebuild();
}
Tags : 8 forms commerce


Related Questions




Change remove from cart button to an image button

Updated October 16, 2019 17:07 PM

Drupal commerce checkout form data-count

Updated December 09, 2016 08:03 AM

Checkout Pane form alter

Updated May 29, 2017 12:07 PM