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.
Sitecore Stack Exchange is a question and answer site for developers and end users of the Sitecore CMS and multichannel marketing software. It only takes a minute to sign up.
Sign up to join this communityThere 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
});