Save Action Code Example

This is a basic WFFM Save Action that can be extended so it better meets your business requirements (usually around record validation and duplicate prevention in Salesforce).

using System;
using System.Collections.Generic;
using Sitecore.Data;
using Sitecore.Form.Submit;
using Sitecore.Form.Core.Client.Data.Submit;
using Sitecore.Form.Core.Controls.Data;
using FuseIT.Sitecore.Salesforce;
using FuseIT.Sitecore.SalesforceConnector;
using FuseIT.Sitecore.SalesforceConnector.Services;
using FuseIT.Sitecore.SalesforceConnector.Entities;
using System.Globalization;
 
namespace FuseIT.Sitecore.Demo
{
    /// <summary>
    /// This is the custom Web Forms for Marketers Save Action example that will take the submitted Web Form input data and save it to Salesforce
    /// using S4S connector.
    /// </summary>
    public class SubmitToSalesforceContacts : ISaveAction
    {
        /// <summary>
        /// Submit method to loop through submitted form fields and extract the data
        /// </summary>
        /// <param name="formid">The form Id on the page</param>
        /// <param name="fields">The fields in the form</param>
        public virtual void Submit(ID formid, AdaptedResultList fields)
        {
            try
            {
                AdaptedControlResult emailField = fields.GetEntryByName("Email");
                AdaptedControlResult idField = fields.GetEntryByName("ContactId");
                AdaptedControlResult userNameField = fields.GetEntryByName("User Name");
 
                ContactService contactService = new ContactService(this.GetSalesforceSession);
 
                Contact contact = null;
                if (emailField != null && GetContact(contactService, emailField.Value, "Email", out contact))
                {
                    Logging.DebugFormat(this, "WebForm SubmitToSalesforceContacts found Contact using value : Email {0}", contact.Email);
                }
                else if (idField != null && GetContact(contactService, idField.Value, "ContactId", out contact))
                {
                    Logging.DebugFormat(this, "WebForm SubmitToSalesforceContacts found Contact value : Id {0}", contact.Id);
                }
                else if (userNameField != null && GetContact(contactService, userNameField.Value, "SitecoreUsername__c", out contact))
                {
                    Logging.DebugFormat(this, "WebForm SubmitToSalesforceContacts found Contact value : SitecoreUsername__c {0} ", userNameField.Value);
                }
                else
                {
                    Logging.Debug(this, "WebForm SubmitToSalesforceContacts found not find Contact using Email, ID or UserName");
                    //Add code to create new Contact
                    return;
                }
 
                //Loop through submitted fields to match them with a Contacts Internal Fields
                foreach (AdaptedControlResult formField in fields)
                {
                    string fieldName = formField.FieldName.Replace(" ", ""); //Remove spaces from input field names
                    string fieldValue = formField.Value;
 
                    Logging.DebugFormat(this, "WebForm Submitted values : Name {0} - Value {1}", fieldName, fieldValue);
                   
 
                    //Check if it the input field is a date
                    if (fieldName.IndexOf("Date") > 0 && fieldValue.IndexOf("T") > 6)
                    {
 
                        DateTime date;
                        fieldValue = fieldValue.Substring(0, fieldValue.IndexOf('T'));
 
                        Logging.DebugFormat(this, "DateTime string = {0}", fieldValue);
 
                        string[] formats = { "yyyyMMdd", "dd/MM/yyyy" };
 
                        if (DateTime.TryParseExact(fieldValue, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out date))
                        {
                            fieldValue = date.ToString("yyyy-MM-dd");
                        }
                        else
                        {
                            fieldValue = string.Empty;
                            Logging.Debug(this, "DateTime string is null");
                        }
 
                        Logging.DebugFormat(this, "DateTime string now = {0}", fieldValue);
                    }
 
                    if (contact.InternalFields.Contains(fieldName))
                    {
                        contact.InternalFields[fieldName] = fieldValue;
                        Logging.DebugFormat(this, "Contact {0} fields updated : Name {1} - Value {2}", contact.Name, fieldName, fieldValue);
                    }
 
 
                }
 
                contactService.SaveContact(contact);
            }
            catch (Exception ex)
            {
                Logging.Error(this, "Error saving web form data to Salesforce contact", ex);
            }
 
        }
 
        /// <summary>
        /// Get the Salesforce Contact with the given username.
        /// </summary>
        /// <param name="userName">The UserName stored in the Salesforce field with the name specified in UserNameFieldName</param>
        /// <param name="session">Salesforce Session</param>
        /// <param name="requiredFields">The fields to retrieve</param>
        /// <param name="contact">The contact if found, else null</param>
        /// <returns>True if the contact was found.</returns>
        private bool GetContact(ContactService contactService, string value, string field, out Contact contact)
        {
            List<Contact> contacts = contactService.GetByFieldEquals(field, value);
 
            if (contacts != null && contacts.Count > 0)
            {
                contact = contacts[0];
                return (contact != null);
            }
 
            contact = null;
            return false;
           
        }

        /// <summary>
        /// Get the saved Salesforce Session needed to connect to Salesforce using the UI Salesforce connection string from
        /// the ConnectionStrings.config
        /// </summary>
        public FuseIT.Sitecore.SalesforceConnector.SalesforceSession GetSalesforceSession
        {
            get
            {
                return new FuseIT.Sitecore.SalesforceConnector.SalesforceSession("S4SConnStringUI");
            }
        }
    }
}


See also, an example of code using S4S to submit to Salesforce from a custom MVC form.

Next Step

Using a Custom Save Action DLL

Steps