0
votes

I am new to ColdFusion. Anyone know why this code is not working. When I leave the form null it is not showing 100 in the database.

<cfif isdefined("FORM.Percentage")>
  <cfset Form.Percentage = #Form.Percentage#>
<cfelse>
  <cfset Form.Percentage = 100>
</cfif>

<cfquery name="percent" datasource ="abc">
Insert into Employees
  (Percentage)
Values
  (#Form.Percentage#)    
</cfquery>
1
Even tho the form is null it is still passed into the page. You should instead check if len( trim( form.percentage )) or isNumeric( form.Percentage ) instead of isDefined() which is why your form.percentage is never set to 100. - BKK
what is it showing in the database? Try surrounding the cfquery by <cfoutput> tags - DG3
@MattBusche: you are right - DG3
@DG3, cfquery has an implicit cfoutput tag. In other words, you don't need one. - Dan Bracuk
Do you know why now it always says a hundred and never the input number? - user2967577

1 Answers

14
votes

If you have a textbox it is submitted to the form even if it's left blank, so you want to check if the field was left blank. If it was then you can set the default.

You'll also want to do some server side validation that the value is a number and use cfqueryparam for inserting your value into the database.

<cfif NOT len(trim(FORM.Percentage))>
  <cfset Form.Percentage = 100>
<cfif>

<cfquery result="percent" datasource="abc">
Insert into Employees (Percentage)
Values (
  <cfqueryparam cf_sql_type="cf_sql_integer" value="#Form.Percentage#">
)
</cfquery>

When using cfquery with an INSERT the name attribute doesn't provide anything. Using result would allow you to view some data about the query if needed, but generally it shouldn't be used.

You could also have dumped form to the screen by using <cfdump var="#form#"> to see what it was returning. If you want to check that the key exists for a radio button or checkbox you can use structKeyExists(form,'myCheckbox') rather than using isDefined().