foreach loop

Les Girvan asked on April 26, 2021 18:51

Hi Guys,

We have a script to pass values of the current basket into a service. This includes all the items in the basket by using a 'foreach' loop using the following:

[{% foreach(cartItem in ECommerceContext.CurrentShoppingCart.CartProducts) { %} 
  "Product Name:{% cartItem.SKU.SKUName#%}", 
  "Item Price:{% cartItem.UnitPrice#%}", 
  "Quantity: {% cartItem.SKUUnits#%}", 
  "Row Total:{% cartItem.TotalPrice#%}", 
  "Image Path:{% GetAbsoluteUrl(ECommerceContext.CurrentShoppingCart.ContentTable[0].SKUImagePath) %}", 
  "Product URL:{% string.GetProductAbsoluteURL(ECommerceContext.CurrentShoppingCart.CartProducts[0].SKUID) #%}", {%} #%}

However, for the image URL and the Product URL, it is just replicating the first item details as the result:

  "Items": [ 
  "Product Name:Lipari Lady Sandal: NATURAL - 40", 
  "Item Price:95.99", 
  "Quantity: 1", 
  "Row Total:95.99", 
  "Image Path:", 
  "Product URL:",  
  "Product Name:Softie Elite 5 MG: MIL.GREEN - LH", 
  "Item Price:110.25", 
  "Quantity: 1", 
  "Row Total:110.25", 
  "Image Path:", 
  "Product URL:", 

Can you advise/suggest the alterations please?

Regards Les

Correct Answer

Dmitry Bastron answered on April 26, 2021 19:10


Your code is always taking the first element from the array (note this [0] element). Therefore, instead of these macros:

{% GetAbsoluteUrl(ECommerceContext.CurrentShoppingCart.ContentTable[0].SKUImagePath) %}
{% string.GetProductAbsoluteURL(ECommerceContext.CurrentShoppingCart.CartProducts[0].SKUID) %}

try something like these:

{% GetAbsoluteUrl(cartItem.SKU.SKUImagePath) %}
{% string.GetProductAbsoluteURL(cartItem.SKU.SKUID) %}
0 votesVote for this answer Unmark Correct answer

Recent Answers

Les Girvan answered on April 27, 2021 12:48

Hi Dmitry,

Many thanks for that, the alteration for the GetProductAbsoluteURL works fine, however the SKUImagePath suggestion does not work.

I have tried adding SKUID, removing the SKU, changing to CartProducts, plus many other variations, none of which work?

As the 'contenttable[0]' works, in pulling the first item, is there maybe a method that will pull in ALL the items, for example is something like this valid?

{% GetAbsoluteUrl(ECommerceContext.CurrentShoppingCart.ContentTable(SKU.SKUImagePath)) #%}

Obviously have tried but this fails!

Regards Les

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.