Reply to topic
Need some help deleting from a list.
Ennio


Joined: 17 Nov 2006
Posts: 98
Location: Scotch Plains, NJ
Reply with quote
I have a list that I'm using to store a shopping cart, buf it the user enters 0 in the quantity I want to remove the itens in the list that has 0 quantity.

If I try to delete the last item in the list, it works, but when I try to delete the first item or any other item not the last it does not work. Here is the code.
Code:

    <cfloop from="1" to="#ListLen(CLIENT.CartMerchList)#" index="i">
      <cfset ThisMerchID = ListGetAt(CLIENT.CartMerchList, i)>
       <cfif isDefined('Form.Quant_#ThisMerchID#')>
           <cfset NewQuant = Form["Quant_#ThisMerchID#"]>
            <cfif NewQuant EQ 0>
               <cfset CLIENT.CartMerchList = ListDeleteAt(CLIENT.CartMerchList, i)>
                <cfset CLIENT.CartQuantList = ListDeleteAt(CLIENT.CartQuantList, i)>
            <cfelse>
               <cfset CLIENT.CartQuantList = ListSetAt(CLIENT.CartQuantList, i, NewQuant)>
            </cfif>
        </cfif>
   </cfloop>
cfsearching


Joined: 27 Jul 2008
Posts: 4
Reply with quote
cfloop will only evaluate the listLen value once (example: cfloop from 1 to 7).

...
<cfset CLIENT.CartMerchList = "1,2,3,4,5,6,7">
<cfloop from="1" to="#ListLen(CLIENT.CartMerchList)#" index="i">
....

When you delete elements, the list length changes. Say you delete two elements, the new list length = 5. So at a certain point, an error is thrown because the code is trying to delete elements that no longer exist. Example


Code:

<cfset myList = "1,2,a,4,a,6,a">
<cfoutput>
list length = #listLen(myList)#<br>
<cfloop from="1" to="#listLen(myList)#" index="x">
   <cfif x mod 3 eq 0>
      <cftry>
         <cfset myList = listDeleteAt(myList, x)>
         <cfcatch><!--- ignore ---></cfcatch>
      </cftry>
   </cfif>
   pos=[#x#]
   <cfif x lte listLen(myList)>
      #listGetAt(myList, x)#
   <cfelse>
      error, this element no longer exists
   </cfif>
   <br>
</cfloop>
</cfoutput>



The solution is to traverse the list in reverse. So the list positions will always exist.

Code:

<cfloop from="#ListLen(CLIENT.CartMerchList)#" to="1" step="-1" index="i">
....
</cfloop>



That said, IMO lists are not the best choice for this scenario. Most list functions ignore empty elements, which could lead to an incorrect shopping cart total or result in wrong items being ordered. A stray comma in the values could do the same thing. IMO arrays are a better choice.
Need some help deleting from a list.
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
All times are GMT  
Page 1 of 1  

  
  
 Reply to topic