In my last post, I showed how simple it is to post a list item to a SharePoint list from Coldfusion 9.  In this post, I want to expand a bit, showing how to add an attachment to a newly created list item.  I also thought it would be a bit more fun to use form data, rather than hardcoding everything…so here goes 🙂

<cfif isDefined('FORM.submit')>
     <cfsavecontent variable="xml">
          <Batch OnError='Return'>
               <Method ID='1' Cmd='New'>
                    <Field Name='ID'>New</Field>
                    <Field Name='Title'>#FORM.title#</Field>
                    <Field Name='Favorite_x0020_Color' #FORM.color#</Field>
     <cfset newItem = xmlParse(xml)>
     <!---Be sure to get the actual field name from the URL, not from the display in SharePoint--->                                    <cfsharepoint action="updatelistitems"
     <cfset theID = theresult.result[2].ows_ID />
     <cfset attach = filereadbinary(FORM.myfile)>
          <cfsharepoint action="addattachment"
<cfform name="myform" method="post" enctype="multipart/form-data" target="addlistwithattachment.cfm">
Title:    <cfinput type="text" name="title" /><br />
Fav Color:  <cfinput type="text" name="color" /><br />
Filename:  <cfinput type="text" name="filename" /><br />
File:  <cfinput type="file" name="myfile" id="myfile" /><br />
<cfinput type="submit" name="submit" value="Submit" /></cfform>

So really, here we have another easy bit of code.  The insert method (updatelistitems) is unchanged, except that I’ve tied the field values to actual form data.

Once the item is created, you can access it’s SharePoint ID from the “Result” structure that SharePoint returns from the updatelistitems method.  Here, you’re looking for the “ows_ID” key–this contains the index ID of the new list item.

Note:  Depending on how you’ve set up the Batch object, the result structure will change.  For example, with a single Method for the Batch, the returned structure looks like:


For multiple Methods, however, the structure changes slightly:


Obviously, this is not hard to check for, but just an FYI 🙂

Once you have this ID, you can invoke the “addattachment” method.  As with the others, it’s super easy to use.  Start by converting the file to a binary object by running “filereadbinary” on the actual file.  Now that this is done, you pass the listName (from before), the listItemID (this is the index ID of the new list item), the name of the file, and the binary object that contains the file.

That’s it!  With just a few lines of code, we’ve established a whole process for creating new list items with attachments.  Obviously, this is a very simple example–in the real world, I should do some checking to see if a file has been submitted, that the result structure is correct, and many other things…However, I think this gives a pretty good start and shows really how simple interacting with SharePoint from ColdFusion 9 actually is.

Have fun 🙂