Integrate Sitecore form with Sitecore Send to send data

In this blog, I will give you a walkthrough on how we can connect Sitecore form to our new marketing automation friend Sitecore send to submit data.

Create a Sitecore send account before going ahead. You can choose from different plans available with different features at different prices or you can also use the trail/free version for one month to explore. However, all features are not available in the free version for one month.

If you already have Sitecore send account. Lets start by following below steps:

1. Create a Email List in Sitecore send

Create a Email List from email list option available under audience menu option(refer below image). It is really easy to create and add members with just few clicks. By default, there are Name, Mobile and Email fields for each member in Email list. Email is the mandatory field here. You can also add custom fields if required and perform computations. We will discuss that in another blog.

2. Create a Sitecore form

Create a Sitecore form with email as mandatory field, name and few other fields if required(refer below for an example)

For more details, refer https://doc.sitecore.com/xp/en/users/93/sitecore-experience-platform/creating-forms.html

3. Create a Sitecore custom submit action

a. Create a submit action item under /sitecore/system/Settings/Forms/Submit Actions and add the Submit Action class to the model type field.

b. Then, add the custom submit action to the form’s submit button.

c. Create a custom submit action class

First copy the IDs of email list and Sitecore Send API Key from Sitecore Send(refer below images) that we will use while making a call to Sitecore send:

API Key:

Email List ID

d. Now inherit the SubmitActionBase and override Execute method to add a code snippet by which a POST request is made to the Uri(refer below code) asynchronously. You will get a Boolean response from the API call about status.

using Newtonsoft.Json;
using Sitecore.Diagnostics;
using Sitecore.ExperienceForms.Models;
using Sitecore.ExperienceForms.Mvc.Models.Fields;
using Sitecore.ExperienceForms.Processing;
using Sitecore.ExperienceForms.Processing.Actions;
using System;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using static Demo.Foundation.SitecoreExtensions.Models.SitecoreSendModel;

namespace Demo.Foundation.SitecoreExtensions.Actions
{
    public partial class SitecoreSend : SubmitActionBase<string>
    {
        private readonly Uri baseAddress = new Uri("https://api.moosend.com/v3/");
        private readonly string emailListID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"; // Add email list ID here, refer above images
        private readonly string SitecoreSendApiKey = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"; // Add sitecore send api key here, refer above images

        public SitecoreSend(ISubmitActionData submitActionData) : base(submitActionData)
        {
        }

        protected override bool TryParse(string value, out string target)
        {
            target = string.Empty;
            return true;
        }

        protected override bool Execute(string data, FormSubmitContext formSubmitContext)
        {
            Assert.ArgumentNotNull(formSubmitContext, "formSubmitContext");
			var txtFirstName = GetFieldValue(this.GetValue(formSubmitContext.Fields.FirstOrDefault(f => f.Name.Equals("FirstName"))));
            var txtLastName = GetFieldValue(this.GetValue(formSubmitContext.Fields.FirstOrDefault(f => f.Name.Equals("LastName"))));
			var emailAddress = GetFieldValue(this.GetValue(formSubmitContext.Fields.FirstOrDefault(f => f.Name.Equals("Email"))));
            var mobile= GetFieldValue(this.GetValue(formSubmitContext.Fields.FirstOrDefault(f => f.Name.Equals("Mobile"))));
            var SitecoreSendModel = new SitecoreSendData
            {
                Name = txtFirstName +" "+ txtLastName,
                Email = emailAddress,
                Mobile = mobile
            };
            Task<bool> executePost = Task.Run(async () => await ExecuteCall(JsonConvert.SerializeObject(SitecoreSendData)));
            return executePost.Result;
        }

        private async Task<bool> ExecuteCall(string data)
        {
            try
            {
                using (var httpClient = new HttpClient { BaseAddress = baseAddress })
                {
                    httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");

                    using (var content = new StringContent(data, Encoding.Default, "application/json"))
                    {
                        using (var response = await httpClient.PostAsync($"subscribers/{emailListID}/subscribe.json?apiKey={SitecoreSendApiKey}", content))
                        {
                            string response = await response.Content.ReadAsStringAsync();
							if(!string.IsNullOrEmpty(response))
							{
								return true;
							}
							else
							{
								return false;
							}
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message.ToString(), "ExecuteCall");
                return false;
            }
        }

        private string GetFieldValue(IViewModel field)
        {
                if (field != null && field is ListViewModel)
				{
					PropertyInfo property = field.GetType().GetProperty("Value");
                    string str = (object)property != null ? property.GetValue(field, (object[])null)?.ToString() : (string)null;
                    return str;
			}
        }
    }
    public partial class SitecoreSendModel
    {
            public string Name { get; set; }
            public string Email { get; set; }
            public string Mobile { get; set; }
    }
}

For more details, refer https://doc.sitecore.com/xp/en/developers/90/sitecore-experience-manager/walkthrough–creating-a-custom-submit-action.html

4. Submit form

After submitting the data successfully, you will be able to see that the one with source as API integration are submissions via API from Sitecore form and others were done manually into email list.

Hope you like this blog! 🙂

Sitecore send – a composable offering for Email automation and marketing

Sitecore is moving towards a SaaS-based platform offering for enterprise solution and a composable digital experience platform (DXP) centered around content. Sitecore has acquired in May 2021 with the effort of adding best of the breed to the class of composable offerings.

Moosend is microservices-based, API-first and cloud-native marketing platform that offers greater personalization and customer engagement with AI-powered analytics and reporting. Moosend has been working with around 2500+ small to large and massive organizations like hewlett packard enterprise, Forbes, NASA, CITYAM, Tedx, health organizations like UNICEF, etc. All these organizations are using moosend for different business cases and marketing needs for market automation, newsletter, better website experience, etc.

It simplifies the way we execute email marketing and customer engagements by providing :

  1. Complete SaaS Platform
  2. Holistic Customer database
  3. Omnichannel digital experience
  4. AI driven Email Experience
  5. Campaign management
  6. Advanced list segmentation
  7. Reduce developer dependency
  8. Simple marketing automation workflows
  9. Powerful real time reporting and analytics
  10. Fast and real time customer journeys

If you like to use Sitecore send, you will get package starting from $10/month that includes up to 2,000 subscribers and an enterprise plan with custom pricing. Sitecore also offer trial version of 1 month to explore Sitecore send however, you may not be able to explore all in trial version.

Prefill Sitecore form fields with query parameters using custom value provider

Recently we had a requirement that if some user wants to buy the same product again on site then he/she can scan the QR code provided to him/her in the first purchase. By scanning the QR code, user will be navigated to form with prefilled fields

After Sitecore 9.3 version, we have Value Providers for pre filling the data in Sitecore form fields. These can be found in Sitecore at location – /sitecore/system/Settings/Forms/Value Providers.

By default, we can prefill your Sitecore Form with contact data from the xDB profile. However, prefilling the fields from query string needs custom value providers.

Following are the steps to accomplish this:

Create custom value provider:

  1. You may create a folder ValueProviders.
  2. In that folder, you may create your custom value provider classes and inherit from the IFieldValueProvider class.
  3. Implement the GetValue method to return an object of any type. You can pass any type of parameters and then parse it to be using in custom class.

    Following is the example of code for pre filling first name from query string parameter ‘shiptoname
using Sitecore.ExperienceForms.ValueProviders;
using System.Web;

namespace Demo.Classes.ValueProvider
{
    /// <summary>
    /// Defines the "FirstNameQueryString" />.
    /// </summary>
    public class FirstNameQueryString : IFieldValueProvider
    {
        public FieldValueProviderContext ValueProviderContext { get; set; }

        public object GetValue(string parameters)
        {
            HttpContext httpContext = System.Web.HttpContext.Current;
            string fName = HttpUtility.ParseQueryString(httpContext.Request.Url.Query).Get(parameters);

            if (string.IsNullOrWhiteSpace(fName))
            {
                return string.Empty;
            }

            return fName;
        }
    }
}

Create corresponding value provider items and link the custom methods:

  1. In /sitecore/system/Settings/Forms,  create a separate folder for query string value providers.
  2. Create value provider items from /sitecore/templates/System/Forms/Value Provider template. Add model class details on the item in field Model Type.
  3. Save the item.

Link the value provider to Sitecore form fields:

  1. Click the Name field, and in the Form elements pane, in the Advanced settings section, in the Value provider field, select the custom provider you have created.
  2. In the Value provider parameters field, enter shiptoname.
  3. Save the form.

Similarly, any type of logic can be used Custom value provider to autofill fields based on the requirement.

Leave a comment