Adobe ColdFusion 8

Creating an update action page with cfupdate

The cfupdate tag is the easiest way to handle simple updates from a front-end form. The cfupdate tag has an almost identical syntax to the cfinsert tag.

To use the cfupdate tag, you must include the primary key fields in your form submittal. The cfupdate tag automatically detects the primary key fields in the table that you are updating and looks for them in the submitted form fields. ColdFusion uses the primary key fields to select the record to update (therefore, you cannot update the primary key value itself). It then uses the remaining form fields that you submit to update the corresponding fields in the record. Your form only needs to have fields for the database fields that you want to change.

  1. Create a ColdFusion page with the following content:
    <html>
    <head>
        <title>Update Employee</title>
    </head>
    <body>
    <cfif not isdefined("Form.Contract")>
        <cfset form.contract = "N">
    <cfelse>
        <cfset form.contract = "Y">
    </cfif>
    
    <cfupdate datasource="cfdocexamples" tablename="EMPLOYEE">
    
    <h1>Employee Updated</h1>
    <cfoutput>
    You have updated the information for #Form.FirstName# #Form.LastName# in the employee
        database.
    </cfoutput>
    
    </body>
    </html>
    

  2. Save the page as update_action.cfm.
  3. View update_form.cfm in your web browser by specifying the page URL and an Employee ID; for example, enter the following: http://localhost/myapps/update_form.cfm?Emp_ID=3

    The current information for that record appears:

  4. Enter new values in any of the fields, and click Update Information.

    ColdFusion updates the record in the Employee table with your new values 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"> <cfelse> <cfset form.contract = "Y"> </cfif>

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

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

Updates the record in the database that matches the primary key on the form (Emp_ID). Updates all fields in the record with names that match the names of form controls.

<cfoutput> You have updated the information for #Form.FirstName# #Form.LastName# in the employee database. </cfoutput>

Informs the user that the change was made successfully.