Discussions

Simple shopping cart summary

Hi all

I'm just trying to show the following items of the cart:

  • total content count
  • current total price
  • View cart link

In the shopping cart block view the footer (Commerce Line Item: Line item summary) basically does exactly what I want. I just don't want to show the list of items. I can't simply remove or exclude all the fields that make up the item list because Views complains about that. I could probably just hide the line items using CSS but thats a bit hackish to me. My knowledge on views is a little thin though. I'd like to be able to call something like get_cart_total_cost() and get_cart_item_count() so I could easily create a themed output. If someone could explain how to produce such a result in views that would be fine anyway.

I looked at commerce_cart.module and it does define 'commerce_cart_block' in hook_theme() and does appear to call it in commerce_cart_block_view() but does not appear to define the theme. Which seems a bit odd. Is that just left over from earlier development?

Apologies if this has been answered already but I have been unable to find the answer for myself.

Posted: Sep 7, 2011

Comments

UserFriendly on September 7, 2011

Hi. Coincidentally, I was about to post a new topic on this myself.

I have created a Block to show a line item summary when people have items in their cart. I'm using the following code (thanks to this thread):

<?php
global $user;
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_total = $wrapper->commerce_order_total->value();
?>


You have items in your <a href="cart">shopping cart</a>. Your order total is <?php print commerce_currency_format($order_total['amount'], $order_total['currency_code']); ?>. <a href="checkout">Checkout</a>.

What we need now is to alter this code to also include the number of items (and obviously, "item" or "items" depening one whether it's 1 or more).

If anyone could help I'd appreciate it.

Thanks.

Richard

magicmyth on September 8, 2011

Thanks Richard. That looks spot on. And thanks for the link as well. FYI the thread link is a tad broken. It has a ')' on the end.

I'll let you know how I get on with it. Have to poke at what the commerce_order entity contains.

As for changing the plural on 'item'. Once the item count is known I would simply do something like:
$item = $order_count > 1 ? t('items') :  t('item');
And print that in the HTML.

You may want to tweak that code sample to use the l() function instead of hard coding the links to shopping cart and checkout. That way it would work with sub-directory Drupal installs and with aliases.

Thanks.

Adam

magicmyth on September 8, 2011

I've figured out a way to count the items. Continuing on from UserFriendly's code You have two options.

If you are all right with knowing only the total number of different products in the basket you can simply call:
$quantity = $wrapper->commerce_order_total->value();

If you want to know the real total including counting each quantity of the items you need to loop though and build the total as so:

$quantity = 0;
foreach ($wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  $quantity += $line_item_wrapper->quantity->value();
}
echo "You have $quantity items in your cart."

By the way I figured part of this out from looking at [commerce_order_calculate_total](http://api.drupalcommerce.org/api/Drupal%20Commerce/sites--all--modules-...). It doesn't show anything on the line item quantity but I took a guess and it worked. Hooray for consistent API :)

A little off topic but does anyone know why Commerce stores the quantity as floats and not ints? Is it possible in some cases to sell a fraction of a product?

Thanks.

Adam

stickywes on September 19, 2011

It's worth noting that this will include all line items added to the order, so if you add non-product line items like taxes or shipping they'll get caught up in the quantity, too.

nwolff on October 9, 2011

Hi,

I had the exact same need and was happy to find your post. By mixing the code of commerce_line_item_handler_area_line_item_summary.inc into yours I was able to get the exact same display as the summary of the existing commerce cart (only consider products, currency, rounding, localization, etc.)

<?php
global $user;
$order = commerce_cart_order_load($user->uid);
if (empty(
$order)) {
    return
t('Your shopping cart is empty.');
} else {
   
$wrapper = entity_metadata_wrapper('commerce_order', $order);
   
$line_items = $wrapper->commerce_line_items;
   
$quantity = commerce_line_items_quantity($line_items, commerce_product_line_item_types());
   
$total = commerce_line_items_total($line_items);
   
$currency = commerce_currency_load($total['currency_code']);   
   
$links = array();
    foreach (
commerce_line_item_summary_links() as $name => $link) {
        if (
$link['access']) {
           
$links[str_replace('_', '-', 'line-item-summary-' . $name)] = $link;
        }
    }
   
$variables = array(
       
'links' => theme('links', array('links' => $links, 'attributes' => array('class' => array('links', 'inline')))),
       
'quantity_raw' => $quantity,
       
'quantity_label' => format_plural($quantity, 'item', 'items'),
       
'quantity' => format_plural($quantity, '1 item', '@count items'),
       
'total_raw' => number_format(commerce_currency_round($total['amount'], $currency), $currency['decimals']),
       
'total_label' => t('Total:'),
       
'total' => commerce_currency_format($total['amount'], $total['currency_code']),
    );
    return
theme('commerce_line_item_summary'$variables);
}
?>

kiwimind on December 15, 2011

Thanks for this, it gets me most of the way there...
For some reason it would seem that $order is never empty as I never just get the line of text saying "Your shopping cart is empty.". I've always got the shopping cart summary, even when there are no products present. This does look a little weird with a View cart and Checkout button...
Any help very much appreciated.
Thanks.

stephenevans on December 4, 2011

Yes I was having the same problem. I think it looks ugly that it shows every product as a line item. I have it as a header too. So it grows bigger and bigger. I don't want to scare them away with the price either as they are shopping. They might mentally buy less I think. I mean you could hide the price but that still makes it big in the header. I mean you could make the number of items 1 but that's inaccurate. You still need one field which makes it grow and grow. But I tried deleted or hiding all the fields and it wouldn't let me do it. I think this should be updated/upgraded as a normal function for the shopping cart block. I just want Shopping Cart, # of total items, link to view cart and link to checkout. I like the block just not the mandatory line items.

I don't really understand the code or know how to manipulate it. I guess I'll have to look into it as you guys find a work around. Is the code going to break with an update?

Once again if you look at Amazon.com they just have the number of items when you add it to the cart. This would be cool. Can we put in for a issue or something?

scottml on January 15, 2012

For anyone who is unsure what to do with the code, you need to:

1. Enable the PHP filter core module.
2. Go to structure -> blocks.
3. Click on add block.
4. Give the block a title to be shown to users (e.g. shopping cart) and a description (e.g. simple shopping cart) for your benefit.
5. Paste the PHP code in the block body, and select the text format PHP code.
6. Select the region where you would like the cart to be, and click on save block.

If you change line 4 of nwolff's code:
if (empty($order)) {
to:
if (empty($order) || empty($order->commerce_line_items)) {
the shopping cart will display the empty shopping cart text as expected.

timodwhit on January 16, 2012

Scottml- Thanks for the help with block placement and all. I appreciate it. Using your instructions and some small edits, you are able to get a the link to function as others have requested.

To answer the above question about how to make a Cart ($quantity) link, it is actually quite simple.

Here is the code I used, I editted nwolfs code down quite substantially.

<?php
global $user;

$order = commerce_cart_order_load($user->uid);
if (empty(
$order) || empty($order->commerce_line_items)) {
    return
l(t('Cart (0)'), 'cart');
}
else {
   
$wrapper = entity_metadata_wrapper('commerce_order', $order);
   
$line_items = $wrapper->commerce_line_items;
   
$quantity = commerce_line_items_quantity($line_items, commerce_product_line_item_types());
  
print
l("Cart( " . $quantity . " )", 'cart');
}
?>

Here is another version that includes Checkout: $0.00


<?php
global $user;

$order = commerce_cart_order_load($user->uid);
if (empty(
$order) || empty($order->commerce_line_items)) {
    return
l(t('Cart (0)'), 'cart');
}
else {
   
$wrapper = entity_metadata_wrapper('commerce_order', $order);
   
$line_items = $wrapper->commerce_line_items;
   
$total = commerce_line_items_total($line_items);
   
$currency = commerce_currency_load($total['currency_code']);
   
$quantity = commerce_line_items_quantity($line_items, commerce_product_line_item_types());
  
print
l("Cart( " . $quantity . " )", 'cart'). " | " . l("Checkout:" . commerce_currency_format($total['amount'], $total['currency_code']) , 'checkout');
}
?>

I'm not trained in php so if there is a better way of going about it, feel free to comment.

Hope this helps.

bennos on February 5, 2012

Quick an easy way, with a lot of advantages like multiple currency and multiple languages support,
Install the module summarize table.

Set the new views style plugin.
set for the fields, you want wo see the totals.
check the box" Show only the summarized results".

Voila, you have the normal cart in an summarized version without any custom code.
It's a better solution, because a block with PHP code does not get cached.

polmaresma polmaresma on April 19, 2013

Hello, your method works great, but causes an error on anonymous users:

EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityDrupalWrapper->set() (line 744 of /var/www/vhosts/domain.com/httpdocs/profiles/commerce_kickstart/modules/contrib/entity/includes/entity.wrapper.inc).
I searched and seems that this error is solved some time ago but I still have it.

Any idea? Thank's for all your work.

polmaresma polmaresma on April 29, 2013

Hi, I solved the entity.wrapper Error controlling if the cart is empty this way. Any better idea?
Thank's for all your work.

<?php
global $user;
$order = commerce_cart_order_load($user->uid);
if (isset(
$ordre->order_number)){
 
$wrapper = entity_metadata_wrapper('commerce_order', $order);
 
$order_total = $wrapper->commerce_order_total->value();
 
$quantity = 0;
  foreach (
$wrapper->commerce_line_items as $delta => $line_item_wrapper) {
   
$quantity += $line_item_wrapper->quantity->value();
  }

echo
' <a href="/cart" class="basket">YOUR BASKET: '.commerce_currency_format($order_total['amount'], $order_total['currency_code']).' ( '.$quantity.'ITEMS)</a>';

}else{
echo
'<span class="basket">YOUR BASKET IS EMPTY</span>';

}
?>

cigocf on April 29, 2013

I think that you have an issue with the variable $order on this line: if (isset($ordre->order_number)), I mean, to change $ordre by $order

cigocf on April 29, 2013

regarding this useful code, I think that there is an issue related with this line:

<?php return l(t('Cart (0)'), 'cart'); ?>

..I mean, to me the return is breaking the rendered page (only is rendered elements before this), so changing return by print was solved the issue (maybe the snippet is a piece of a function that returns the line, but I think that as snippet isolated will have the issue).

timodwhit on February 18, 2012

Or Make a Block. Turn on Aggregation. Set-up a CONTEXTUAL FILTER -> Default value: Customer's current order.

Set fields as you please. and you're all set.

PHP did cause some issues.

Hope this helps

ivanhelguera on April 29, 2013

If the php code includes the line

$wrapper = entity_metadata_wrapper('commerce_order', $order);

I get tthe error
EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. w EntityDrupalWrapper->set() . line 744 of  /profiles/commerce_kickstart/modules/entity/includes/entity.wrapper.inc)

Anyone has any ideas as to what could be wrong?

drupalcommerce Check out the #Drupal Commerce 2.x Roadmap to see where you can get involved: http://t.co/WAc3jmXY2a
drupalcommerce A new blog discussing the new showcase listing http://t.co/FHOzhAg3tl http://t.co/J5C87imjhb
drupalcommerce RT @drupalcon: Thanks @CommerceGuys and @CommerceJohn for your support, and for #CommerceKickstart! Take the tour http://t.co/ivKEYH7k0o
drupalcommerce Updating our extensions directory: 665 new or updated modules, distributions, sandboxes, & themes. http://t.co/6NMMofYo12 #weloveyouguys