Drupal Commerce Responsive Checkout Tables

Submitted by swim on Fri, 06/06/2014 - 04:18

Providing a responsive checkout is an important feature of any eCommerce site. Drupal Commerce if themed correctly handles this fairly sweet; except for one element, tables.

Here is a quick solution which leverages stacktable.js. Automatically applying it to each views table instance during the checkout process. Simply add more form_id's to extend this functionality to other pages.


/**
 * @file
 * stacktable.module
 */

/**
 * Implements hook_form_alter().
 */
function stacktable_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_checkout_form_checkout':
    case 'commerce_checkout_form_review':
      $form['#attached']['library'][] = array('stacktable', 'stacktable.js');
      $form['#attached']['js'][] = drupal_get_path('module', 'stacktable') . '/js/stacktable.module.js';

      // We don't know if other view tables exist.
      $form['#attached']['js'][] = array(
        'data' => array('hivqld' => array(
          'table' => '.' . drupal_html_class($form_id) . ' .views-table'),
        ),
        'type' => 'setting',
      );
    break;
  }
}

/**
 * Implements hook_library().
 */
function stacktable_library() {
  $library = libraries_get_path('stacktable.js');

  $libraries['stacktable.js'] = array(
    'title' => 'Stacktable.js',
    'website' => 'http://johnpolacek.github.io/stacktable.js',
    'download url' => 'https://github.com/johnpolacek/stacktable.js/zipball/master',
    'version' => array(),
    'js' => array(
      $library . '/stacktable.js' => array(
        'scope' => 'header',
      ),
    ),
    'css' => array(
      $library . '/stacktable.css' => array(
        'type' => 'file',
        'media' => 'screen',
      ),
    ),
  );

  return $libraries;
}

 & the JavaScript which takes our form_id; applying to all child view tables.


/**
 * @file
 * stacktable.module.js
 */

(function($) {

  Drupal.behaviors.stacktable = {
    attach: function(context, settings) {
      var table = settings.hivqld.table;

      $(table).once("stacktable", function() {
        $(table, context).stacktable();
      });
    }
  };

}(jQuery));

Make sure you have the stacktable.js library located at, sites/all/libraries/stacktable.js/stacktable.js - yes the folder is called stacktable.js xD.

  • sites/all/libraries/stacktable.js/stacktable.js
  • sites/all/libraries/stacktable.js/stacktable.css

Finally here is an example of the above code in use. For me it really was a case of plug & play, stacktable.js is a fantastic library.