0

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();
}
  • without success it's broad, be more specific on, what exactly its not succesful. Does the button appear? – No Sssweat May 21 at 15:59
  • The button appears. I push it but the call back function is never fired and then I can't increment the quantity. I don't know if this is the right way to do it. Thanks. – briast May 21 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.