Zawołanie funkcji JavaScript przy przesyłaniu formularza Sitecore Forms

In Sitecore 9 we can easily 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 and back buttons as well:

All the source code from this article is available on Github.

Implementation

First we need a field, where we can enter our custom JavaScript code. Let’s start with creating a new template with Form Submit Script multi-line text field, in /sitecore/templates/Foundation/Forms Custom Script/Custom Scripts:

Then go to /sitecore/templates/System/Forms/Fields/Button and assign Custom Scripts template to the base templates:

Next we need to extend a view model class representing submit button in Sitecore Forms. We create a new class inheriting from Sitecore.ExperienceForms.Mvc.Models.Fields.ButtonViewModel and add support for our new field:

After deploying our code to Sitecore, we can use new class in Sitecore Forms setting item: /sitecore/system/Settings/Forms/Field Types/Structure/Submit Button in Model Type field:

Finally we need to modify the view file responsible for rendering the button in Sitecore Forms \Views\FormBuilder\FieldTemplates\Button.cshtml:

In our js code, first we get the submit button and its form element and check if we are not in Sitecore Forms Editor mode (we don’t want to call our js while editing). Then check, if a form submission was triggered by correct button (important for forms with multiple pages and buttons). Finally we attach handler to the form submit event, which executes JavaScript code, loaded from the Sitecore field.

If we want to call js function from external file in our Form Submit Script field, we can reference this file in the form item in Scripts field (the file needs to be copied to \sitecore modules\Web\ExperienceForms\scripts\ folder):

Odnośniki
  • vasukreddy

    Hi
    Great article and thank you for sharing.

    So in this case your new script is getting injected first and then doing the action we define and then at the end its calling the submit action defined by the sitecore forms ? or is this purely intercepting the original submit and replaced with the new one ?
    I am trying to add a google captcha invisible v3 token and having an issue with intercepting the original submit because captcha takes about 200 ms to come back and by the time i receive a response its already submitted.

  • Bassel Issa

    Hi, i was looking into the source code and i found that you are executing the custom script in the onSubmit
    $formEl.on("submit", function () {
    if ($inputEl.attr('clicked')) {
    @Html.Raw(Model.FormSubmitScript)
    }
    });

    but that will be executed even if the form failed or successes