Mike Robbins

Sitecore Developer Blog

Follow me on GitHub

Write to Web Forms Programmatically

Recently I had a requirement to capture a number of parameters from a users session and provide Sitecore administrators a way of reporting on this data and exporting the data to CSV for analysis.

The reporting within WFFM was exactly what I was looking to achieve. I wondered if I could tap into this programmatically and use WFFM as my analysis and exporting tool.

Form Reports

>Form Reports

The idea is to create a new Form within WFFM and instead of adding the form to the page, instead create an instance of the form in memory, complete form and post the data into the WFFM database.

Below is a code sample (commented) of completing the Form and posting the data back programmatically.

public void SubmitToWFFM(ID formID, string username, string anotherString)
  //Get form item by Item ID
  Sitecore.Forms.Core.Data.FormItem formItem = Sitecore.Forms.Core.Data.FormItem.GetForm(formID);

  //Get form fields of the WFFM
  FieldItem[] formFields = formItem.Fields;

  //Get all form fields of the form by name
  FieldItem usernameField = formFields .FirstOrDefault(x => x.FieldDisplayName == "Username");
  FieldItem anotherField = loggingFields.FirstOrDefault(x => x.FieldDisplayName == "AnotherField");
  //Populate fields with values
  ControlResult controlUsernameTerm = new ControlResult(usernameField.Name, username, null);
  ControlResult controlAnotherField = new ControlResult(anotherField.Name, anotherString, null);
  //Create collection of fields
  AdaptedControlResult[] acr = new AdaptedControlResult[2];
  acr[0] = new AdaptedControlResult(controlUsernameTerm, false);
  acr[1] = new AdaptedControlResult(controlAnotherField, true);
  AdaptedResultList arl = new AdaptedResultList(acr);
  //Save form
  SaveToDatabase dbSave = new SaveToDatabase();
    dbSave.Execute(formId, arl, null);
  catch (Exception ex)
    Sitecore.Diagnostics.Log.Error(ex.Message, ex, this);