Drupal Delete Users Cart

Written by Josh Fabean

13. October 2015

I just pushed up my first Drupal module, though it’s currently only a sandbox module. It’s also up on GitHub in case you don’t want to look around awhile to find where Drupal hides it’s code for sandboxed modules.

This is a module that I’m sure only one other person in the history of the world has ever needed, but I’m excited nonetheless. The description of the module is as follows:

In rare instances you need to delete everything out of your cart, unfortunately there is no great way to do this out of the box, that’s what this module tries to remedy. Once installed you need to create a link for the user that goes to /cart/$user_id/delete this will then redirect them to whatever page you configure.

The instance I ran into where we need this is someone will be on the phone with a customer placing the order for them as a reseller. Then that user is like “oh nevermind”, but they’ve already gotten far enough they don’t want to go back a bunch of time and change all the fields so they just push this button. The biggest issue we were running into is we are using Auth.net hosted CIM which uses email and ID to create a new customer, so if you get to the last page of checkout then they change their mind you’ve already created them in Auth.net which we cannot let happen.

This is the main magic that happens:

<?php

function commerce_delete_cart_menu() {
  $items = array();
  $items['cart/%/delete'] = array(
    'title' => 'Delete Commerce Cart',
    'page arguments' => array(1),
    'page callback' => 'commerce_delete_cart_main',
    'access callback' => TRUE,
  );
  return $items;
}

function commerce_delete_cart_main($uid) {
  db_delete('commerce_order')
    ->condition('uid', $uid)
    ->condition('status', 'checkout_%', 'LIKE')
    ->execute();
  db_delete('commerce_order')
    ->condition('uid', $uid)
    ->condition('status', 'cart')
    ->execute();
  $redirect_url = variable_get('commerce-delete-cart-redirect', $defaults['commerce-delete-cart-redirect']);
  drupal_goto($redirect_url);
}

When you go to /cart/$user_id/delete it runs the function commerce_delete_cart_main which then goes and deletes straight out of the db all entries it could be. I need to combined those two db_delete into one, but the Drupal documentation on that didn’t click for me in under 5 seconds so I skipped it.

One of the cooler things I did for this was making it user configurable which is pretty much required when you’re looking to pass something off to the community.

I hope someone finds this module and it helps them, as I sure would have liked to find this last week.

:wq