Drupal Commerce extending reorder module

Submitted by swim on Tue, 11/05/2013 - 04:09

Below is a very simple bit of code which extends Drupal Commerce reorder module. The code places an AJAX form on all commerce order entities allowing users to reorder from the order details page. This form functions exactly like the module button but with no redirect after the reorder has been triggered. One could easily add this in with a $form_state['redirect'].


/**
 * Implements hook_entity_view().
 */
function MODULE_commerce_entity_view($entity, $type, $view_mode, $langcode) {
  // If entity is an order, attach reorder form.
  if ($type == 'commerce_order') {
    $order_id = $entity->order_id;

    $entity->content['commerce_reorder'] = array(
      '#type' => 'markup',
      '#markup' => render(drupal_get_form('MODULE_commerce_reorder_details_form', $order_id)),
    );
  }
}

/**
 * Ajax form to handle reorders from the details page.
 */
function MODULE_commerce_reorder_details_form($form, $form_state) {
  $form['actions'] = array(
    '#type' => 'container',
  );
  $form['actions']['reorder'] = array(
    '#type' => 'submit',
    '#value' => t('Reorder'),
    '#ajax' => array(
      'callback' => 'MODULE_commerce_reorder_status_message',
    ),
  );

  return $form;
}

/**
 * Ajax callback, trigger status messages.
 */
function MODULE_commerce_reorder_status_message($form, $form_state) {
  $commands = array();
  $message = drupal_set_message(t('Yay, reorder triggered.'));

  $commands[] = ajax_command_prepend('div#messages', theme('status_messages', $message));
  return array('#type' => 'ajax', '#commands' => $commands);
}

/**
 * Form submit handler, reorder line items using previous order id.
 */
function MODULE_commerce_reorder_details_form_submit($form, $form_state) {
  if (is_numeric($form_state['build_info']['args'][0])) {
    $order = commerce_order_load($form_state['build_info']['args'][0]);
    commerce_reorder_helper($order);
  }
}