I am attempting to preselect items in a multiple select menu based on a DB query that has been converted to a pipe delimited ValueList. Everything is working except for one thorn in my side.
As I said, the list is pipe delimited but contains commas in some of the list items. (i.e. Communications (pagers, cell phones, etc.)
). When I perform a listContainsNoCase(), looking for matches everything works fine until a comma is encountered. What I expect would be a match does not come back as such. It is ignored. If I'm excluding commas as delimiters, why do they seem to not be ignored? See code sample below.
<!---All possible categories pulled from the category table--->
<cfset allCategories = valueList(catdata.memberCategory, "|")>
<!---All category results that exist for a specific user's record--->
<cfset currentUserCategories = valueList(getUserRecord.categories, "|")>
<!---Multi select menu:--->
<label class="select select-multiple">
<cfoutput>
<select multiple="multiple" name="categories" id="categoriesA" style="height:200px;">
<cfloop list="#allcategories#" index="i" delimiters="|">
<option value="#trim(i)#"
<cfif listcontainsnocase(currentUserCategories, i)>selected="selected"</cfif>>
#trim(i)#
</option>
</cfloop>
</select>
</cfoutput>
</label>
Screenshot (blue text is currentUserCategories output):
So my question is why is the menu item Communications (pagers, cell phones, etc)
being ignored and how do I get my code to include it?
It's because you're not specifying |
as delimiter for that function. So ListContainsNoCase is actually using its default: comma. You need to specify the delimiter as |
.
That said, it's probably not the correct function anyway. ListContainsNoCase() searches for partial matches, so you may get some false positives. Since you're trying to match the whole list element, you should be using ListFindNoCase():
<cfif ListFindNoCase(listToSearch, valueToFind , "|")>
Finally, if your table has a unique numeric ID for categories (it should), consider using the ID in related tables - and for the list value - instead of the text. That avoids this kind of delimiter issue. Also, storing id's minimizes inconsistencies that can occur when storing related text values in multiple tables.