Adobe ColdFusion 8

Creating an insert action page with cfinsert

The cfinsert tag is the easiest way to handle simple inserts from either a cfform or an HTML form. This tag inserts data from all the form fields with names that match database field names.

  1. Create a ColdFusion page with the following content:
    <html>
    <head> <title>Input form</title> </head>
    
    <body>
    <!--- If the Contractor check box is clear, 
        set the value of the Form.Contract to "No" --->
    <cfif not isdefined("Form.Contract")>
     <cfset Form.Contract = "N">
    </cfif>
    
    <!--- Insert the new record --->
    <cfinsert datasource="cfdocexamples" tablename="EMPLOYEE">
    
    <h1>Employee Added</h1>
    <cfoutput> You have added #Form.FirstName# #Form.Lastname# to the employee database.
    </cfoutput>
    
    </body>
    </html>
    

  2. Save the page as insert_action.cfm.
  3. View insert_form.cfm in your web browser and enter values.

Note: You might want to compare views of the Employee table in the cfdocexamples data source before and after inserting values in the form.

  1. Click Submit.

    ColdFusion inserts your values into the Employee table and displays a confirmation message.

Reviewing the code

The following table describes the code and its function:

Code

Description

<cfif not isdefined("Form.Contract")> <cfset Form.Contract = "N"> </cfif>

Sets the value of Form.Contract to No if it is not defined. If the Contractor check box is unchecked, no value is passed to the action page; however, the database field must have some value.

<cfinsert datasource="cfdocexamples" tablename="EMPLOYEE">

Creates a row in the Employee table of the cfdocexamples database. Inserts data from the form into the database fields with the same names as the form fields.

<cfoutput>You have added #Form.FirstName# #Form.Lastname# to the employee database. </cfoutput>

Informs the user that values were inserted into the database.

Note: If you use form variables in cfinsert or cfupdate tags, ColdFusion automatically validates any form data it sends to numeric, date, or time database columns. You can use the hidden field validation functions for these fields to display a custom error message. For more information, see Introduction to Retrieving and Formatting Data.