Sort on Availability of Items (Catalog Template Coding)
Asked via the UltraCart forums:
I am wanting to sort my items for display within a Group to have items with inventory at the beginning of the list and those that are sold out to be at the bottom of the list.
There are a number of sort functions to use within the templates based on price, itemid etc but is there a way to do it so the sold out can be at the end of the list.
Possible Solution:
<html> <head> <style type='text/css'> *{font-family: tahoma, serif; font-size:10px;} .outofstock{color:red;} </style> </head> <body> ## get a list of all the items in the group #set($groupItems = $group.getItems()) ## create an empty list to hold the pseudo-sorted items #set($sortedItems = []) ## create an empty hash to hold a list of those out-of-stock items #set($outOfStock = {}) ## loop through and add all the items that are in stock #foreach($item in $groupItems) #if($item.getAvailableQuantity() > 0) IN STOCK: $item.getMerchantItemID()<br /> #set($dummy = $sortedItems.add($item)) #end #end ## second pass. loop through and add all the items that are out of stock. ## also, put their item ids in a hash for later lookup. #foreach($item in $groupItems) #if($item.getAvailableQuantity() <= 0) OUT OF STOCK: $item.getMerchantItemID()<br /> #set($dummy = $sortedItems.add($item)) ## assign to dummy since 'put' returns true/false and we don't want to print that in our page. #set($dummy = $outOfStock.put($item.getMerchantItemID(), true)) #end #end <hr /> Below is a list of items printed out:<br /> ## print out the items as you normally would. Add a class of 'outofstock' if it is ## this class could then be used to show an out of stock background image, etc. #foreach($item in $sortedItems) <span #{if}($outOfStock.containsKey($item.getMerchantItemID()))class="outofstock"#{end}>Item: $item.getDescription()</span><br /> #end </body> </html>
You'll notice the use of $dummy
alot. I'm using the underlying ArrayList and HashMap objects available through the Velocity Engine.
The methods like add()
and put()
return values like true/false, and I don't want those printing on my page.
So, I assign them to $dummy
which makes them disappear down a black hole.
Question? Comments? Here's a link to this forum question where you may continue the discussion.
Forum Question