3

I want to set an access callback on a menu item (primary links) for the shopping cart so that it only displays when there is something in the cart. However, I can't find an obvious function to to this, and I don't know where to start with my own code.

Any suggestion is appreciated.

3

Using the same technique as commerce_cart_block_view (thanks to Ryan Szrama for the assist!), you'll need to:

  1. Get the order using commerce_cart_order_load, then check to see if there are no line items.
  2. Apply the entity metadata wrapper to retrieve further wrappers for the entity properties
  3. Count line items in the cart, filtering for products only

For the access callback itself, take a look at Do you have an example of hook_menu() access callback? for several examples and links to documentation.

Therefore, the callback should be something like:

function MODULE_access_check() {
  global $user;
  if ($order = commerce_cart_order_load($user->uid)) {
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    return commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types()) > 0;
  }
  return FALSE;
}
  • 1
    Note that you can't do a simple count on the commerce_line_items field, because it may still contain a reference to a non-product line item. Check out commerce_cart_block_view() in commerce_cart.module to see how I determine if the cart is empty for the purposes of showing the empty cart block vs. the cart block view. – Ryan Szrama Oct 30 '13 at 4:21
  • 1
    Excellent point, much appreciated! I've updated my answer accordingly. Thanks for all your work on DC! – jonpeck Oct 30 '13 at 16:11
  • 1
    Thanks guys. I'm working on my first Commerce site and am super impressed at how it leverages all the goodness of Drupal that I (nearly) understand. – elb Nov 1 '13 at 9:05
1

Apply this patch here then you can call commerce_cart_is_cart_empty() from your code:

if (!commerce_cart_is_cart_empty()) {
  // your code
}
0

Actually you might want to check the args, to avoid presenting the user with an access denied page when they remove the last item from their cart:

function MODULE_access_check() {
  global $user;
  if ($order = commerce_cart_order_load($user->uid)) {
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    $items = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());
    return $items > 0 || arg(0) == 'cart';
  }
  return FALSE;
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.