3

I need to execute custom JavaScript code on a successful form submit. Are there any events that can be attached to?

Using Sitecore 9.0.2 with Forms Extensions.

1 Answer 1

7

There are no built-in hooks or events, but by extending the RenderForm pipeline a JavaScript event can be emitted on success:

Config:

<pipelines>
   <forms.renderForm>        
    <processor type="MyProject.Pipelines.Forms.RenderForm.FormPostSuccessEvent, MyProject" resolve="true" 
               patch:after="processor[@type='Sitecore.ExperienceForms.Mvc.Pipelines.RenderForm.InitializeAjaxOptions, Sitecore.ExperienceForms.Mvc']"/>
  </forms.renderForm>
</pipelines>

Processor:

public class FormPostSuccessEvent : MvcPipelineProcessor<RenderFormEventArgs>
{
    public override void Process(RenderFormEventArgs args)
    {
        var attributes = args.Attributes["data-ajax-success"] as string;
        if (string.IsNullOrEmpty(attributes))
        {
            return;
        }

        args.Attributes["data-ajax-success"] = "document.dispatchEvent(new CustomEvent('sc-forms-submit-success', {'detail': '" + args.FormHtmlId + "'}));" + attributes;
    }
}

JavaScript:

document.addEventListener("sc-forms-submit-success", function(e) {
      var myForm = document.getElementById(e.detail);
      // do JS magic
});
1
  • I think your solution is awesome but it will always be data-ajax-success even when the form fails at server side. Mar 15, 2021 at 19:15

Your Answer

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

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