Coldfusion 8: IsDefined('URL.variable') and is not ""?
16,352
Solution 1
<cfif structKeyExists(url, 'affiliateID') and trim(url.affiliateID) neq "">...</cfif>
Solution 2
You can simplify the logic a bit as well by using <cfparam> to ensure that the URL variable always exists. Then rather than having 2 conditions, you just need 1.
<cfparam name="URL.affiliateId" type="string" default="" />
<cfif trim( URL.affiliateId ) is not "">
do stuff here
</cfif>
Solution 3
To ignore most white space
<cfif IsDefined('URL.affiliateId') and len(trim(URL.affiliateId))>
value is defined and not empty
</cfif>
... or alternately
<cfif IsDefined('URL.affiliateId') and len(trim(URL.affiliateId)) gt 0>
value is defined and not empty
</cfif>
Author by
dcolumbus
Updated on June 26, 2022Comments
-
dcolumbus over 1 year
I'm trying to find out if a url variable exists, and if it doesn't, make sure that it's not empty.
This does not work:
<cfif IsDefined('URL.affiliateId') and is not ""> // </cfif>
-
Stephen Moretti about 13 yearsAs Leigh says: no #'s are requires, plus if you know the scope and variable name you should always use structkeyexists() as shown by scrittler
-
Harrison about 13 yearsyeah I know that #s are required, it's just one of those habits.
-
Leigh about 13 yearsGood point about structKeyExists(). Either works, but it is a bit more precise.
-
Leigh about 13 yearsI think they have a CF support group for that .. ;)
-
Leigh about 13 yearsAh, much better. (I am always amazed how many ways you can write this kind of thing ;-)
-
Leigh about 13 yearsTrue. If the variable's existence does not negatively effect existing code (I was not sure), then cfparam can simplify things
-
Leigh about 13 yearsNo there are perfectly valid use cases for all of the above. Personal preference, on the other hand, is a different matter.
-
abdev about 13 yearsAlso it's been proven the sturctKeyExists is more efficient than IsDefined.
-
Uphill_ What '1 about 13 yearsYes, they are valid but not needed.
-
Stephen Moretti about 13 yearsJust so you know why StructKeyExists is more efficient; StructKeyExists() looks for a single variable in a single structure. isDefined() will scan every scope in a prescribed order until it find the variable, even if you specify the scope for the variable in the function call. eg. isDefined("session.userid") will still scan the variables, URL, Form etc scopes until it finds it in the session scope.
-
Leigh about 13 yearsWhile there are similarities in behavior, there are also differences. So a blanket statement that they are never needed is inaccurate. They do not all provide identical functionality.