Ask a Jedi: Creating a list of product options

Andrew asks:

I have an application im programming and am stuck on this one section. I have system for product options. i let the user create different options like this:
Color:green,red,brown
Size:S.M,L,XL,XXL

Now I'm able to read each as a list and loop through to get the options and save each to database. I want to now go ahead and create a list of all possible combinations.
s,green
m,green
l,geen

You get the idea. Now each has an ID number so I could use combo numbers like:
1,2
1,3
1,4

Have any how this could be done in coldfusion? I have tried arrays and havent got a solution yet.

There are probably multiple ways to skin this cat, but lets take a simple approach. As long as we know for sure what our options are, we can simply do a loop with a loop. Consider the following simple code:

<cfset colorList = "green,red,brown,blue,yellow,purple,white"> <cfset sizeList = "S,M,L,Xl,XXL,XXXL">

<cfset comboList = ““> <cfloop index=”c” list=”#colorList#”> <cfloop index=”s” list=”#sizeList#”> <cfset comboList = listAppend(comboList, c & “ “ & s)> </cfloop> </cfloop>

<cfdump var=”#listToArray(comboList)#”> </code>

This code simply loops over the color list and the size list. For every instance of the color list we loop over the complete size list. I store the result in a list and just dump the value at the end. You can see how it looks below.

If your color and sizes are from database tables, then I could have stored the IDs values as well. You could imagine storing X,Y as the value, and on display, simply converting each primary key to their proper value.

As long as you know the combinations you support, this is probably the best solution (and since I said that, someone is going to prove me wrong!). If you have a dynamic set of combinations, then then the logic gets more complex.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments