cfselect, binding, and selectedvalues

ColdFusion's cfselect doesn't support the selectedvalue argument when using binding. I don't like the JavaScript solutions out there, so here's a simple SQL solution.

If you have a cfselect like this one that makes a call to a remote CFC then the selectedvalue is completely ignored when the field is populated:

Remote.cfc:

<cfif 0="" is="" val(arguments.state_id)=""> <cfset cityname")="" rs='QueryNew("ID,'> <cfset queryaddrow(rs)=""> <cfset "id",="" 0)="" querysetcell(rs,=""> <cfset "choose="" "cityname",="" a="" first...")="" querysetcell(rs,="" state=""> SELECT ID , CityName FROM City (NOLOCK) WHERE State_ID = ORDER BY CityName

I've seen JavaScript solutions from Ray Camden and others to make this work, but it always just seemed like too much work, or involved changing/overriding core cfajax files. So why not just have the result you want be the first value returned from the query? With a simple CASE statement we can bubble our desired value to the top of the list so that when the select is populated it's the first (and by default selected) element. I just need to change my binding call and my function:

Remote.cfc:

<cfif 0="" is="" val(arguments.state_id)=""> <cfset cityname")="" rs='QueryNew("ID,'> <cfset queryaddrow(rs)=""> <cfset "id",="" 0)="" querysetcell(rs,=""> <cfset "choose="" "cityname",="" a="" first...")="" querysetcell(rs,="" state=""> SELECT ID , CityName FROM ( SELECT ID , CityName , CASE WHEN ID = THEN 0 ELSE 1 END AS Sort FROM City (NOLOCK) WHERE State_ID = ) d ORDER BY Sort, CityName

Now when the query is returned, the ID that was passed as the selectedvalue argument will have a sort value of 0, and every other row will have a sort value of 1. Our ORDER BY statement then bubbles the first result to the top of the list.