Thursday, February 15, 2018

Sitecore 8.2 submit a WFFM form programatically

WFFM in Sitecore is great for allowing content authors to create and manage forms with a wide array of fields and save actions. It's of course possible to extend the module in many ways (custom validators, fields, save actions and so on). But one area where it lacks is on the user experience on the front end. Hence comes the requirement to submit a form programatically, which not only uses the save actions and fields the author created but also hooks into the reporting.

This simple example below, is a condensed example which shows the submission of a form with a single field called Email. Essentially we get the actual form item to have access to it's fields and save actions. This is then used to create the parameters required to submit the form.
var myEmail = "ryan.bailey@email.com";
Sitecore.Forms.Core.Data.FormItem formItem = Sitecore.Forms.Core.Data.FormItem.GetForm(ID.Parse("{7D47FECC-25DF-4561-A911-683F4F164FA7}")); // Get the form item
var emailField = formItem.Fields.Where(x => x.DisplayName == "Email").FirstOrDefault(); // Get a given field - should null check of course

var controlResults = new List<ControlResult>();
controlResults.Add(new ControlResult(emailField.ID.ToString(), emailField.Name, myEmail ,emailField.Parameters,false));

// Parse save actions
var saveActionXml = formItem.SaveActions;
var actionList = Sitecore.Form.Core.ContentEditor.Data.ListDefinition.Parse(saveActionXml);
var actionDefinitions = new List<ActionDefinition>();
actionDefinitions.AddRange(actionList.Groups.SelectMany(x => x.ListItems).Select(li => new ActionDefinition(li.ItemID, li.Parameters) { UniqueKey = li.Unicid }));

Sitecore.Forms.Core.Handlers.FormDataHandler handler = Sitecore.WFFM.Abstractions.Dependencies.DependenciesManager.Resolve<Sitecore.Forms.Core.Handlers.FormDataHandler>();
handler.ProcessForm(ID.Parse("{7D47FECC-25DF-4561-A911-683F4F164FA7}"), controlResults.ToArray(), actionDefinitions.ToArray()); // Submit form
There are older examples available online, but this one works for me on 8.2 and the reporting is there as well.

No comments:

Post a Comment