Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, December 05, 2011

Save infopath 2010 form data to Sharepoint list programmatically

Save infopath 2010 form data to Sharepoint list programmatically
In continuation with my previous post where I created an application page and added the xmlformview control to the page, in this post i will show you how to save the data in the infopath form hosted inside the xmlformview control ( on our cutsom applictaion page) on OnSubmitToHost of the xmlformview.
In this post you will learn how to retrieve user submitted data in infopath form fields (fields are FirstName and LastName) and how to save the whole form in SharePoint library with the name created using FirstName and LastName fields.
Lets first modify the xmlformviewcontrol – Adding the OnSubmitToHost
<fv:XmlFormView ID=”formView” runat=”server” EditingStatus=”Editing” OnSubmitToHost=”FormView_SubmitToHost” Width=”700px”></fv:XmlFormView>
Code for submit to host
protected void FormView_SubmitToHost(object sender, SubmitToHostEventArgs e)
{
SPWeb web = SPContext.Current.Web;
web.AllowUnsafeUpdates = true;
// Load the XML and save it as a byte array
System.Xml.XPath.XPathNavigator navigator = formView.XmlForm.MainDataSource.CreateNavigator();
Byte[] formBytes = System.Text.Encoding.UTF8.GetBytes(navigator.OuterXml);
// Create XmlDocument from the form XML
XmlDocument doc = new XmlDocument();
XmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable);
nsm.AddNamespace(“my”, “http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-09-29T22:54:17″);
doc.LoadXml(navigator.OuterXml);
// Load name information from the XML
XmlNode nodeLastName = doc.SelectSingleNode(“/my:myform/my:UserInformation/my:LastName”, nsm);
string name = (nodeLastName != null) ? nodeLastName.InnerText : string.Empty;
XmlNode nodeFirstName = doc.SelectSingleNode(“/my:RoomBooking/my:UserInformation/my:FirstName”, nsm);
string firstname = (nodeFirstName != null) ?nodeFirstName.InnerText : string.Empty;
// Generate file name
string filename = String.Format(“{0}{1}_{2}.xml”, name, firstname, DateTime.Now.ToString(“yyyyMMdd”));
// Open library and save XML
SPFolder formLibrary = web.GetFolder(LIBRARY_NAME);
formLibrary.Files.Add(filename, formBytes);
web.AllowUnsafeUpdates = false;
}

No comments:

Post a Comment