user2967577
user2967577

Reputation: 79

ColdFusion isDefined

I am trying to check to see if data exist in my form If data does not exist I want to assign it to O. How can I do this.

<cfif not isDefined("FORM.Age")>
 cfset FORM.Age = "0"
<cfif>

Upvotes: 5

Views: 17211

Answers (4)

Dan Bracuk
Dan Bracuk

Reputation: 20804

There are actually two things you want to to ensure. First, make sure this page was arrived at by submitting the proper form. Next, ensure you have a numeric value for the form.age variable. Here is an example of how you might want to code this:

<cfif StructKeyExists(form, "age") and cgi.http_referrer is what it should be>
    <cfif IsNumeric(form.age) and form.age gt 0>
        <cfset AgeSubmitted = int(form.age)>
    <cfelse>
        <cfset AgeSubmitted = 0>
    </cfif>
    ...more code to process form
<cfelse>
    ...code for when page was not arrived at properly
</cfif>

Upvotes: 0

Leigh
Leigh

Reputation: 28873

Technically what you have is fine once you enclose the cfset in tags < and >. Assuming that omission is just a typo, could it be you are trying to use it with a text field?

Text fields always exist on submission. The value may be an empty string, but the field itself still exists, so IsDefined will always return true. If that is the case, you need to examine the field length or value instead. Then do something if it is empty according to your criteria. For example:

 <!--- value is an empty string --->
 <cfif NOT len(FORM.age)>
     do something 
 </cfif>

 ... OR 

 <!--- value is an empty string or white space only --->
 <cfif NOT len(trim(FORM.age))>
     do something 
 </cfif>

 ... OR 

 <!--- convert non-numeric values to zero (0) ---> 
 <cfset FORM.Age = val(FORM.Age)>

Upvotes: 3

Andrew Myers
Andrew Myers

Reputation: 658

Generally the best practice is considered to be to avoid isDefined. This is because isDefined will search all scopes until it finds a matching variable. So it's more efficient to use structKeyExists, eg:

<cfif NOT structKeyExists(form, "age")>
   <cfset form.age = 0>
</cfif>

Also, another way to achieve this is to use cfparam, and specify 0 as the default:

<cfparam name="form.age" default="0">

Upvotes: 18

user2967613
user2967613

Reputation: 71

You're almost there:

<cfif not isDefined("FORM.Age")>
<cfset Form.Age = 0>
</cfif>

Upvotes: 7

Related Questions