Justin Treher asks: "Yo, Adrian. I see that you are using autonumber for your tables. Whenever you run the CREATE method in the DAO you are just returning true. How does the application get the ID?"

He continues:

"For instance, if I do:

view plain print about
1contactDAO.create(contact);

contact.getContactID() will be 0 both before and after create.

It seems like you would want:

view plain print about
1arguments.contact.setContactID(newContactID);

in the create method.

I'm used to using UUID, but needed to use autonumber. A google search later landed me on your blog for an example. I read and reread, but couldn't find joy."

This is a very good question. The answer is simple, but somehow you've missed the obvious: do exactly what you just outlined.

What's your workflow?

The application that I've touched on through this series has a basic workflow:

  1. List data in table
  2. Create new data in a form
  3. Save new data to a table
  4. List data in a table (now contains new record)

The workflow you have might look like this:

  1. List data
  2. Create new data in a form
  3. Save new data to a database
  4. Work with newly created data

Programming your workflow

So let's take a look again at the Create() method I outlined in part 7.3.

ContactDAO.cfc - create()
view plain print about
1<cffunction name="create" access="public" output="false"
2    returntype="boolean">
<!--- [1] --->
3
4    <!--- [2] --->
5    <cfargument name="contact" required="true"
6        type="contact" hint="Contact bean" />

7
8    <!--- [3] --->
9     <cfset var qCreateContact = "" />
10    <cfset var qNewContact = "" />
11    <cfset var newContactID = 0 />
12    <cfset var categoryIDArray = arrayNew(1) />
13    <cfset var x = 0 />
14    <cfset var qCreateContactCategory = "" />
15
16    <!--- [4] --->
17    <cftransaction action="begin">
18
19        <!--- [5] --->
20        <cftry>
21
22            <!--- [6] --->
23            <cfquery name="qCreateContact"
24                datasource="#variables.DSN#">

25                INSERT INTO CONTACTS
26                (
27                    FIRST_NAME,
28                    LAST_NAME
29                )
30                VALUES
31                (
32                    <cfqueryparam
33                        value="#arguments.contact.getFirstName()#"
34                        cfsqltype="cf_sql_varchar" />,
35                    <cfqueryparam
36                        value="#arguments.contact.getLastName()#"
37                        cfsqltype="cf_sql_varchar" />
38                )
39            </cfquery>
40
41            <!--- [7] --->
42            <cfquery name="qNewContact"
43                datasource="#variables.DSN#">

44
45                SELECT LAST_INSERT_ID() AS NEW_ID
46
47            </cfquery>
48
49            <cfset newContactID = qNewContact.NEW_ID />
50
51            <!--- [8] --->
52            <cfset categoryIDArray = arguments.contact.getCategoryIDArray() />
53
54            <!--- [9] --->
55            <cfloop index="x"
56                from="1"
57                to="#arrayLen( categoryIDArray )#">

58
59                <cfquery name="qCreateContactCategory"
60                    datasource="#variables.DSN#">

61                    INSERT INTO CONTACT_CATEGORIES
62                    (
63                        CONTACT_ID,
64                        CATEGORY_ID
65                    )
66                    VALUES
67                    (
68                        <!--- [10] --->
69                        <cfqueryparam
70                            value="#newContactID#"
71                            cfsqltype="cf_sql_integer" />,
72                        <!--- [11] --->
73                        <cfqueryparam
74                            value="#categoryIDArray[x]#"
75                            cfsqltype="cf_sql_integer" />
76                    )
77                </cfquery>
78
79            </cfloop>
80
81            <!--- [12] --->
82            <cfcatch type="database">
83                <!--- [12.1] --->
84                <cftransaction action="rollback" />
85     <!--- [12.2] --->
86     <cfreturn false />
87            </cfcatch>
88
89        </cftry>
90
91    <!--- [13] --->
92    </cftransaction>
93
94    <!--- [14] --->
95    <cfreturn true />
96
97</cffunction>

Let's just hit the high points:

  1. The function returns a boolean value.
  2. The function takes a single argument of the Contact bean
  3. The Contact bean is passed by reference into Create()
  4. We create a single record in the CONTACTS table
     
  5. ***** We get the ID of the new Contact record so we can associate it to records in another table
     
  6. We loop over the associated CategoryIDs and create a record in the table CONTACT_CATEGORIES for each one.

***** <Elle Driver>Now, you should listen to this, 'cause this concerns you.</Elle Driver>

We return true if everything inserted correctly or false if something went wrong. We do this so that the process that called create() knows if it created or not. We could return a struct with a key that's boolean and a key that's a string with an error message. We could do a lot of things, but this basic function only returns true or false.

So let's alter Create() to populate the Contact bean's CONTACT_ID property with our new ID.

Getting the new ID

When we created a record in the CONTACTS table, we retrieved the new ID using the MySQL function LAST_INSERT_ID(). Each database has its own function or process for retrieving a new ID after INSERT. I outlined many of them here: Please stop using SELECT MAX(id).

If you're using ColdFusion 8, the CFQUERY tag has been updated to automatically return the new ID as part of the returned data. The only downside is that the variable's name differs based on your database.

The next thing we have to remember is that for the sake of this Primer, the Contact bean has private setters. This means that we cannot call them from outside the bean. Only public methods inside the bean can call its private methods.

So you have two options:

  1. Make setContactID() public
  2. call the init() method and pass all the bean's properties back into itself

If you choose option 1, the updated Create() looks like:

view plain print about
1<!--- [12] --->
2            <cfcatch type="database">
3                <!--- [12.1] --->
4                <cftransaction action="rollback" />
5     <!--- [12.2] --->
6     <cfreturn false />
7            </cfcatch>
8
9        </cftry>
10
11    <!--- [13] --->
12    </cftransaction>
13
14    <!--- [14] --->
15    <cfset arguments.contact.setContactID( newContactID ) />
16
17    <!--- [15] --->
18    <cfreturn true />
19
20</cffunction>

If you choose option 2:

view plain print about
1<!--- [12] --->
2            <cfcatch type="database">
3                <!--- [12.1] --->
4                <cftransaction action="rollback" />
5     <!--- [12.2] --->
6     <cfreturn false />
7            </cfcatch>
8
9        </cftry>
10
11    <!--- [13] --->
12    </cftransaction>
13
14
15    <!--- [14] --->
16    <cfset arguments.contact.init(
17        CONTACT_ID = newContactID,
18        CATEGORY_ID_ARRAY = arguments.contact.getCategoryIDArray(),
19        FIRST_NAME = arguments.contact.getFirstName(),
20        LAST_NAME = arguments.contact.getLastName()
21        ) /
>

22
23    <!--- [15] --->
24    <cfreturn true />
25
26</cffunction>

If the INSERTs failed, then we return false (12.2) and exit the function without updating CONTACT_ID. Otherwise, the CONTACT_ID property gets updated and we return true (15).

What about the calling process?

So let's use this updated code in our presentation layer. Assume we have these files:

  1. contact_list.cfm
  2. contact_create.cfm
  3. contact_process.cfm
  4. contact_view.cfm

On contact_list.cfm, we have a link to create a new contact.

On contact_create.cfm, we have a form that submits to the processing page.

The contact_process.cfm page could then look something like this:

view plain print about
1<cfset contact = createObject("component", "Contact").init(
2    CONTACT_ID = form.CONTACT_ID,
3    CONTACT_ID_ARRAY = listToArray(form.CATEGORY_ID),
4    FIRST_NAME = form.FIRST_NAME,
5    LAST_NAME = form.LAST_NAME
6    ) /
>

7
8<cfset contactDAO = createObject("component", "ContactDAO").init( DSN = application.DSN ) />
9
10<cfif contactDAO.create( contact )>
11    <cflocation url="contact_view.cfm?CONTACT_ID=#contact.getContactID()#" />
12<cfelse>
13    <cflocation url="contact_list.cfm?error=true" />
14</cfif>

When Create() returns true, the contact bean's CONTACT_ID property should be populated, so we can use it as part of the querystring in the cflocation tag. When it returns false, we can redirect back to the list page and display an error. Alternately, we could also return to the form page and pre-populate the form fields using the data from the bean via session or URL variables.

Moving on (I hope)

Justin, I hope this clears up your question. I know the most obvious answer can often seem like the wrong one. I've spent the last few weeks learning Flex and trust me, I've hit the "obvious" wall almost daily.

To everyone, please let me know if anything else here is unclear and I'll do my best to reply via e-mail or on the site. I hope to have the post on the Collection object online in the very near future.