ColdFusion isDefined

孤人 提交于 2019-12-19 03:16:50

问题


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>

回答1:


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">



回答2:


You're almost there:

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



回答3:


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)>



回答4:


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>


来源:https://stackoverflow.com/questions/19851641/coldfusion-isdefined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!