ColdFusion 9 Developer Tutorial
上QQ阅读APP看书,第一时间看更新

Improving page flow

The page was refreshed and showed us an update. But it might not be obvious that an update was made. There is also an issue that it does not appear as if the data was updated because we pulled the data object details before the update was made. Also when we saved our edit page data, it would be nice if we were sent back to the list page. Let us take a look at the redirect tag in ColdFusion,<cflocation>. After an insert or update, the browser will be returned back to the list page. We will also pass a message to the page so that the user will see the updates. First, we will create a message in each of our insert and action code segments. Then, we will push the page back to the list page by passing the message with it:

<cfif structKeyExists(attributes,"submit")>
<cfif attributes.id EQ 0>
<cfquery datasource="cfb" name="qryInsert">
INSERT INTO product( name , description , price ) VALUES( <cfqueryparam value="#attributes.name#"> , <cfqueryparam value="#attributes.description#"> , <cfqueryparam value="#attributes.price#"> )
</cfquery>
<cfset returnMessage = "Your product has been added.">
<cfelse>
<cfquery datasource="cfb" name="qryUpdate">
UPDATE product SET name = <cfqueryparam value="#attributes. name#"> , description = <cfqueryparam value="#attributes. description#"> , price = <cfqueryparam value="#attributes.price#"> WHERE ID = <cfqueryparam value="#attributes.id#">
</cfquery>
<cfset returnMessage = "Your product (#attributes.name#) has been updated.">
</cfif>
<cflocation url="product_list.cfm?message=#returnMessage#">
</cfif>

You can see that we tacked the message to the end location of our target page. We need to add a<cfparam> tag to the calling page, so it will be able to handle calls where the URL variable is not available. Then we can add a little section of the page to show the messages, when they exist. Let us edit the product_list.cfm page as follows:

<!--- Example: product_list.cfm --->
<!--- Processing --->
<cfparam name="url.message" default="">
<cfscript>
objProduct = createObject("component","product").init(dsn="cfb");
rsProducts = objProduct.getRecordset();
</cfscript>
<!--- Content --->
<cfif url.message NEQ "">
<div>
<cfoutput>#url.message#</cfoutput>
<hr />
</div>
</cfif>
<h3>Select a product to edit.</h3>
<ul>
<cfoutput query="rsProducts">
<li>
<a href="product_edit.cfm?id=#rsProducts.id#">#rsProducts.name#
</li>
</cfoutput>
</ul>

This is how the page looks, when we submit our form: