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