Custom submit action for Sitecore Forms

I know there are many documentations on this already and wanted to thank the Sitecore Documentation team for a detailed document page on this topic. Please read the official document here.

We had a request of having a registration form where once the user submits the form, the user must be created in the Sitecore User Manager so that user can login to the front end site.

I can’t share the exact code but can share the hardcoded code for testing purpose.

  1. Create a Registration Form using Sitecore Forms.
  2. The fields which are expected are (Full Name, Email, Password, Confirm Password, Comments).
  3. Now we have Save Data as submit action but it won’t help hence we need to create custom submit action.
  4. Create a class file and copy the below code. The execute method is the main method to write your business logic.
using System.Linq;
using Sitecore.Diagnostics;
using Sitecore.ExperienceForms.Models;
using Sitecore.ExperienceForms.Processing;
using Sitecore.ExperienceForms.Processing.Actions;
using static System.FormattableString;
using Sitecore.Configuration;
using Sitecore.Security.Accounts;
using System.Web.Security;
using System;

namespace IAS.Feature.Content.Repositories
{
    /// <summary>
    /// Executes a submit action for logging the form submit status.
    /// </summary>
    /// <seealso cref="Sitecore.ExperienceForms.Processing.Actions.SubmitActionBase{TParametersData}" />
    public class CustomSubmitAction : SubmitActionBase<string>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="LogSubmit"/> class.
        /// </summary>
        /// <param name="submitActionData">The submit action data.</param>
        public CustomSubmitAction(ISubmitActionData submitActionData) : base(submitActionData)
        {
        }

        public void AddUser(string domain, string fullName, string password, string email, string comment)
        {
            string userName = fullName.Replace(" ", "");
            userName = string.Format(@"{0}\{1}", domain, userName);

            //string password = Membership.GeneratePassword(10, 3);

            try
            {
                if(!User.Exists(userName))
                {
                    Membership.CreateUser(userName, password, email);

                    //Edit Profile
                    User user = User.FromName(userName, true);
                    Sitecore.Security.UserProfile userProfile = user.Profile;
                    userProfile.FullName = fullName;
                    userProfile.Comment = comment;

                    userProfile.SetPropertyValue("ProfileItemId", "");

                    userProfile.Save();
                }
            }
            catch(Exception ex)
            {
                Log.Error("Addition of User failed: " + ex.Message, this);
            }
        }

        /// <summary>
        /// Tries to convert the specified <paramref name="value" /> to an instance of the specified target type.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="target">The target object.</param>
        /// <returns>
        /// true if <paramref name="value" /> was converted successfully; otherwise, false.
        /// </returns>
        protected override bool TryParse(string value, out string target)
        {
            target = string.Empty;
            return true;
        }

        /// <summary>
        /// Executes the action with the specified <paramref name="data" />.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="formSubmitContext">The form submit context.</param>
        /// <returns>
        ///   <c>true</c> if the action is executed correctly; otherwise <c>false</c>
        /// </returns>
        protected override bool Execute(string data, FormSubmitContext formSubmitContext)
        {
            Assert.ArgumentNotNull(formSubmitContext, nameof(formSubmitContext));

            if (!formSubmitContext.HasErrors)
            {
                string fullName = formSubmitContext.Fields.Where(x => x.Name.Equals("FullNameText")).FirstOrDefault()?.GetType().GetProperty("Value")?.GetValue(formSubmitContext.Fields.Where(x => x.Name.Equals("FullNameText")).FirstOrDefault(), null)?.ToString();
                string email = formSubmitContext.Fields.Where(x => x.Name.Equals("EmailText")).FirstOrDefault()?.GetType().GetProperty("Value")?.GetValue(formSubmitContext.Fields.Where(x => x.Name.Equals("EmailText")).FirstOrDefault(), null)?.ToString();
                string password = formSubmitContext.Fields.Where(x => x.Name.Equals("PasswordText")).FirstOrDefault()?.GetType().GetProperty("Value")?.GetValue(formSubmitContext.Fields.Where(x => x.Name.Equals("PasswordText")).FirstOrDefault(), null)?.ToString();
                string role = formSubmitContext.Fields.Where(x => x.Name.Equals("RoleText")).FirstOrDefault()?.GetType().GetProperty("Value")?.GetValue(formSubmitContext.Fields.Where(x => x.Name.Equals("RoleText")).FirstOrDefault(), null)?.ToString();
                Log.Info(Invariant($"Form {formSubmitContext.FormId} submitted successfully."), this);
                AddUser("Extranet", fullName, password, email, role);
            }
            else
            {
                Log.Warn(Invariant($"Form {formSubmitContext.FormId} submitted with errors: {string.Join(", ", formSubmitContext.Errors.Select(t => t.ErrorMessage))}."), this);
            }

            return true;
        }
    }
}
using System.Linq;
using Sitecore.Diagnostics;
using Sitecore.ExperienceForms.Models;
using Sitecore.ExperienceForms.Processing;
using Sitecore.ExperienceForms.Processing.Actions;
using static System.FormattableString;
using Sitecore.Configuration;
using Sitecore.Security.Accounts;
using System.Web.Security;
using System;

namespace IAS.Feature.Content.Repositories
{
    /// <summary>
    /// Executes a submit action for logging the form submit status.
    /// </summary>
    /// <seealso cref="Sitecore.ExperienceForms.Processing.Actions.SubmitActionBase{TParametersData}" />
    public class CustomSubmitAction : SubmitActionBase<string>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="LogSubmit"/> class.
        /// </summary>
        /// <param name="submitActionData">The submit action data.</param>
        public CustomSubmitAction(ISubmitActionData submitActionData) : base(submitActionData)
        {
        }

        public void AddUser(string domain, string fullName, string password, string email, string comment)
        {
            string userName = fullName.Replace(" ", "");
            userName = string.Format(@"{0}\{1}", domain, userName);

            //string password = Membership.GeneratePassword(10, 3);

            try
            {
                if(!User.Exists(userName))
                {
                    Membership.CreateUser(userName, password, email);

                    //Edit Profile
                    User user = User.FromName(userName, true);
                    Sitecore.Security.UserProfile userProfile = user.Profile;
                    userProfile.FullName = fullName;
                    userProfile.Comment = comment;

                    userProfile.SetPropertyValue("ProfileItemId", "");

                    userProfile.Save();
                }
            }
            catch(Exception ex)
            {
                Log.Error("Addition of User failed: " + ex.Message, this);
            }
        }

        /// <summary>
        /// Tries to convert the specified <paramref name="value" /> to an instance of the specified target type.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="target">The target object.</param>
        /// <returns>
        /// true if <paramref name="value" /> was converted successfully; otherwise, false.
        /// </returns>
        protected override bool TryParse(string value, out string target)
        {
            target = string.Empty;
            return true;
        }

        /// <summary>
        /// Executes the action with the specified <paramref name="data" />.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="formSubmitContext">The form submit context.</param>
        /// <returns>
        ///   <c>true</c> if the action is executed correctly; otherwise <c>false</c>
        /// </returns>
        protected override bool Execute(string data, FormSubmitContext formSubmitContext)
        {
            Assert.ArgumentNotNull(formSubmitContext, nameof(formSubmitContext));

            if (!formSubmitContext.HasErrors)
            {
                string fullName = formSubmitContext.Fields.Where(x => x.Name.Equals("FullNameText")).FirstOrDefault()?.GetType().GetProperty("Value")?.GetValue(formSubmitContext.Fields.Where(x => x.Name.Equals("FullNameText")).FirstOrDefault(), null)?.ToString();
                string email = formSubmitContext.Fields.Where(x => x.Name.Equals("EmailText")).FirstOrDefault()?.GetType().GetProperty("Value")?.GetValue(formSubmitContext.Fields.Where(x => x.Name.Equals("EmailText")).FirstOrDefault(), null)?.ToString();
                string password = formSubmitContext.Fields.Where(x => x.Name.Equals("PasswordText")).FirstOrDefault()?.GetType().GetProperty("Value")?.GetValue(formSubmitContext.Fields.Where(x => x.Name.Equals("PasswordText")).FirstOrDefault(), null)?.ToString();
                string role = formSubmitContext.Fields.Where(x => x.Name.Equals("RoleText")).FirstOrDefault()?.GetType().GetProperty("Value")?.GetValue(formSubmitContext.Fields.Where(x => x.Name.Equals("RoleText")).FirstOrDefault(), null)?.ToString();
                Log.Info(Invariant($"Form {formSubmitContext.FormId} submitted successfully."), this);
                AddUser("Extranet", fullName, password, email, role);
            }
            else
            {
                Log.Warn(Invariant($"Form {formSubmitContext.FormId} submitted with errors: {string.Join(", ", formSubmitContext.Errors.Select(t => t.ErrorMessage))}."), this);
            }

            return true;
        }
    }
}

5. To make the above code you might need to add Sitecore.ExperienceForms NuGet package.
6. Once the code is built and published, go to Sitecore Content Editor.
7. Go to /sitecore/system/Settings/Forms/Submit Actions.
8. Add a new Custom Submit Action under it.

9. Publish the setting item.
10. Go to the Launchpad >> Forms.
11. Open the Registration Form and click on the Submit button.
12. Expand the Submit actions section and should be able to see the new Custom Submit action.

This should help you to create custom submit actions based on your custom requests.

Thank you.. Keep Learning.. Keep Sitecoring.. 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s