2

I need to make a dataLayer.push({my_arguments_here}) whenever a form successfully goes to the next page/gets submitted. I know that some validation is happening on back-end, so I'm trying to find a JS code, which is checking if BE passed, before going to the next page. That's where I wanted to write my own code for dataLayer.push(). But I can't find any JS code which is doing that.

Any ideas where and/or how JS knows that BE passed validation successfully before going to the next form page? Or any other ideas on how to approach this?

I'm working on Sitecore 10.1.2

1

1 Answer 1

0

you can extend Sitecore Forms module to execute custom JavaScript code when the form, created in Sitecore is submitted by the users. This can work with multi-page forms with next buttons as well.

You need to write your dataLayer.push({my_arguments_here}) under custom js to submit it before going to next page or form submission.

Extend a view model class representing submit button in Sitecore Forms.

using Sitecore;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.ExperienceForms.Mvc.Models.Fields;
 
namespace Sc.FormsCustomScripts.Models
{
    public class CustomScriptButtonViewModel : ButtonViewModel
    {
        public string FormSubmitScript { get; set; }
 
        protected override void InitItemProperties(Item item)
        {
            Assert.ArgumentNotNull(item, nameof(item));
            base.InitItemProperties(item);
            FormSubmitScript = StringUtil.GetString((object)item.Fields["Form Submit Script"]);
        }
 
        protected override void UpdateItemFields(Item item)
        {
            Assert.ArgumentNotNull(item, nameof(item));
            base.UpdateItemFields(item);
            item.Fields["Form Submit Script"]?.SetValue(FormSubmitScript, false);
        }
    }
}

Modify the view file responsible for rendering the button in Sitecore Forms \Views\FormBuilder\FieldTemplates\Button.cshtml

@using Sitecore.ExperienceForms.Mvc.Constants
@model Sc.FormsCustomScripts.Models.CustomScriptButtonViewModel
 
@{
    var cssClass = Model.CssClass;
    if (Model.NavigationStep < 0)
    {
        var classes = Model.CssClass.Split(' ');
        if (!classes.Contains("cancel", StringComparer.OrdinalIgnoreCase))
        {
            if (!string.IsNullOrEmpty(Model.CssClass))
            {
                cssClass += " ";
            }
 
            cssClass += "cancel";
        }
    }
}
 
<input value="@Html.DisplayTextFor(t => Model.Title)" type="submit" class="@cssClass" name="@Html.Name(Model.ItemId)" data-sc-field-key="@Model.ConditionSettings.FieldKey" />
@Html.Hidden(AttributeNames.NavigationButtons, Model.ItemId)
@Html.Hidden(Model.ItemId, Model.NavigationStep)
 
<script type="text/javascript">
    (function ($) {
        var $inputEl = $("input[name='@Html.Name(Model.ItemId)']");
        var $formEl = $inputEl.closest('form');
        if ($inputEl.length == 0 || $formEl.length == 0) {
            return;
        }
        $inputEl.click(function () {
            $("input[type=submit]", $formEl).removeAttr("clicked");
            $(this).attr("clicked", "true");
        });
        @if (Sitecore.Context.Site.Name != "shell")
        {
            if (!string.IsNullOrWhiteSpace(Model.FormSubmitScript)) 
            { 
                <text>
                    $formEl.on("submit", function () {

                    //datalayer.push 
                      dataLayer.push({
                        'color': 'red',
                        'conversionValue': 50,
                        'event': 'customize'
                      });


                        if ($inputEl.attr('clicked')) {
                            @Html.Raw(Model.FormSubmitScript)
                        }
                    });
                </text>
            }
        }
    })(jQuery)
</script>

Reference: Call Custom JavaScript on Sitecore Forms Submit

Hope it helps!

4
  • Thanks for the tips, unfortunately it doesn't work as intended. I commented out the Model.FormSubmitScript for now, and added a console.log() after both ($formEl.on("submit", function () { and if ($inputEl.attr('clicked')) {, and I can see console log only fires after the first code, even if the validation of required field failed, but it never reached the second code block at all
    – Linas
    Commented Jan 5 at 12:15
  • My bad on the last comment. I realized we already had a custom Button.cshtml so I had to change input to button in the script. I see my JS is being called now, but it fires up even if the form failed from back-end side, e.g. a field was required, I see the error messages on the form, but the JS still fires
    – Linas
    Commented Jan 8 at 10:51
  • You can ask another question with necessary details and mark this answer accepted as it resolved your initial query. Commented Jan 8 at 11:25
  • Unfortunately it didn't resolve my initial query, as I need the JS to be called when form page moves successfully to the next page, while currently it is not. If backend validation fails (e.g., when a field is mandatory), it does not move to the next page and the JS is getting called, but it shouldn't.
    – Linas
    Commented Jan 10 at 8:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.