I would like to add two buttons to add or substract quantity in the same form. I use the next code. The button is shown and I push it but nothing happens. I use xdebug and I see that submit and callback are never fired. I don't know if there is some lock by this module:

/**
 * 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) {
    // Botones para añadir/eliminar cantiddes    
    $form['quantity']['widget']['0']['#prefix'] = '<div id="quantity-wrapper">';
    $form['quantity']['widget']['0']['#suffix'] = '</div>';    
    
    $form['actions']['add_qty'] = [
      '#type' => 'submit',
      '#value' => t('+1'),
      '#submit' => ['_sbmt_add_one_callback'],
      '#ajax' => [
        'callback' => '_add_one_callback',
        'wrapper' => 'quantity-wrapper',
      ],
    ];
  }
}

function _add_one_callback(array &$form, FormStateInterface $form_state) {
  return $form['quantity-wrapper'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function _sbmt_add_one_callback(array &$form, FormStateInterface $form_state) {
  $cantidad = $form_state->get('quantity');
  $cantidad = $cantidad + 1;
  $form_state->set('quantity', $cantidad);
  $form_state->setRebuild();
}

Comments

briantes created an issue. See original summary.

subhojit777’s picture

please double check if your submit element is not getting overridden by this https://git.drupalcode.org/project/dc_ajax_add_cart/-/blob/8.x-1.x/src/F...

briantes’s picture

Thanks for your help. I have run more tests, but I have the same problem. Now, my button is shown and if I push it the callback is fire, but the quantity is not updated. I have followed this documentation (#Render Array). This is my new attempt:

/**
 * 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) {

    $id = str_replace('commerce_order_item_dc_ajax_add_cart_form_', '', $form_id);
    $form['quantity']['widget']['0']['#prefix'] = '<div id="quantity-wrapper-'.$id.'">';
    $form['quantity']['widget']['0']['#suffix'] = '</div>';    
    
    $form['add_qty'] = [
      '#type' => 'button',
      '#value' => t('+1'),
      '#ajax' => [
        'callback' => '_add_one_callback',
        'wrapper' => 'quantity-wrapper-'.$id,
      ],
    ];

  }
}

/**
 * Submit handler for the "add-one-more" button.
 *
 */
function _add_one_callback(array &$form, FormStateInterface $form_state) {
  $valores = $form_state->getValues();
  $cantidad = $valores['quantity'][0]['value'] + 1;  
  $form['quantity']['#value'] =  $cantidad;
  // $form_state->setValue('quantity', $cantidad);
  return $form['quantity'];
}
NWOM’s picture

Category: Support request » Feature request
Status: Active » Closed (duplicate)