Forms

Create HTML forms in B2C Commerce using templates and controllers. Using form definitions, persist form data during a session and store it in system objects or custom objects.

Creating a Form 

Create a standard HTML form that uses AJAX for validation and error rendering. If you’re creating a simple form that doesn’t store data, is easily localized, and only requires client-side validation, this type of form is appropriate. Create a complex form that stores data, requires server-side validation, and has sophisticated localization requirements. Sophisticated localization can include adding, removing, or rearranging fields in the form or changing the data object you have to store with form data.

If you’re creating a complex form, use a B2C Commerce form definition. A form definition results in an in-memory object that persists during the session. Use this object with various platform features for localization, server-side validation, and data storage.

The following example uses a form definition. The form has a text field to input a nickname, a submit button, and a cancel button. After the form is submitted, another page is rendered that shows the nickname entered in the previous form.

Form Definition 

The first thing you create for a form is the form definition. The form definition describes the data you need from the form, the data validation, and the system objects you want to store the data in. This example only has one input field and two buttons. This form doesn’t validate or store data permanently.

SFRAFormDef.xml

1<?xml version="1.0"?>
2<form xmlns="http://www.demandware.com/xml/form/2008-04-19">
3	<field formid="nickname" label="Nickname:" type="string" mandatory="true" max-length="50" />
4	<action formid="submit" valid-form="true"/>
5	<action formid="cancel" valid-form="false"/>
6</form>

In-memory Form Object 

The form definition determines the structure of the in-memory form object. The in-memory form object persists data during the session, unless you explicitly clear the data.

In the Storefront Reference Architecture (SFRA), the first step to create a form is to create a JSON object to contain the form data. The server.getForm function uses the form definition to create this object. Data from the form is accessible in templates using the pdict variable. However, the form is available only if the server.getForm object is passed to the template by the controller.

Controller to Render the Form 

The controller in this example exposes a Start function that renders an empty form.

The Start function sets the actionURL that’s used to handle the submit action for the form and creates a JSON object based on the form definition.

SFRAForm.Js 

1/**
2 * A simple form controller.
3 *
4 */
5
6'use strict';
7var server = require('server');
8var URLUtils = require('dw/web/URLUtils');
9
10server.get(
11 'Start', server.middleware.http, function (req, res, next) {
12    var actionUrl = URLUtils.url('SFRAFormResult-Show'); //sets the route to call for the form submit action
13 var SFRAhelloform = server.forms.getForm('SFRAFormDef'); //creates empty JSON object using the form definition
14 SFRAhelloform.clear();
15
16   res.render('SFRAFormTemplate', {
17       actionUrl: actionUrl,
18       SFRAhelloform: SFRAhelloform
19   });
20 next();
21});
22
23module.exports = server.exports();

Form Template - SFRAFormTemplate.isml 

In this example, SFRAFormTemplate.isml is the empty form rendered for the user and the SFRAResultTemplate.isml shows data entered into the form.

The form action uses the actionUrl property passed to it by the controller.

The client-side JavaScript and css files are included using the assets.js module.

1<!--- TEMPLATENAME: helloform.isml --->
2 <!--- <isscript>
3var assets = require('*/cartridge/scripts/assets.js');
4assets.addCss('/css/helloform.css');
5assets.addJs('/js/helloform.js'); </isscript>--->
6
7<div class="hero slant-down login-banner">
8	<h1>SFRA Hello World Form</h1>
9</div>
10
11<!--- --->
12<div class="card">
13	<form action="${pdict.actionUrl}" class="login" method="POST"
14		name="SFRAHelloForm">
15
16		<div class="form-group required">
17			<label> Nickname: </label> <input type="input" id="nickname"
18				class="form-control" name="nickname">
19		</div>
20
21		<button type="submit" class="btn btn-block btn-primary">Submit</button>
22		<button type="submit" class="btn btn-block btn-primary">Cancel</button>
23	</form>
24</div>

Controller to Render Form Results - SFRAFormResult.Js 

After a form is submitted, data from the form is available as part of the req.form property. In the following example, the nickname entered in the original form is passed to a new template for rendering.

1/**
2 * Handles the simple form rendered by the SFRAForm.js controller.
3 *
4 */
5
6'use strict';
7var server = require('server');
8var URLUtils = require('dw/web/URLUtils');
9
10
11server.post('Show', server.middleware.http,
12  function(req, res, next) {
13
14  var nickname = req.form.nickname;
15
16  res.render('SFRAResultTemplate', {
17    nickname : nickname});
18   next();
19  });
20
21module.exports = server.exports();

Form Result Template - SFRAResultTemplate.isml 

This template prints the form field label and data stored from the form.

1<<!--- TEMPLATENAME: SFRAResultTemplate.isml --->
2<iscontent type="text/html" charset="UTF-8" compact="true" />
3<!doctype html>
4<head></head>
5<body>
6<h1>Hello World Form Result</h1>
7<p>Nice to meet you, ${pdict.nickname}.</p>
8</body>
9</html>

Hiding Form Fields 

Most SFRA forms are standard HTML forms, so use input type="hidden" to hide form fields in templates.

Reusing Form Definitions 

The form you create in your template can contain fields from multiple form definitions. The same fields can be reused in other forms as many times as required. This ability can be useful for prepopulating form data that the customer has already entered. For example, address or payment preference data.

Using Form Metadata 

Use the metadata entered for a custom or system object in Business Manager to determine form definition information. This manages data attributes in one place without having to change code. For example, if you wanted to let merchants change the labels on form fields, you could include label as a metadata attribute and reference it.

Dynamic, Multi-Part, Embedded, or Nested Forms 

SFRA doesn’t include dynamic forms.

However, if you want to create them, use the isdynamicform tag to generate dynamic forms. The dynamicform.isml template and the dynamicForm.js script control how code is generated using the isdynamicform tag.

SFRA doesn’t include multi-part, embedded, or nested forms. We don’t recommend them as a best practice.

Localizing a Form 

Change the structure of a form depending on the locale. For example, include different address fields, such as state or province, depending on the country. To localize the form structure, create different form definitions for each locale. These form definitions have the same name, but a different structure or different fields for different locales.

In your cartridge, create a forms/default folder for the standard locale and then separate folders that are named for each locale of the form. Store a different form definition in each locale folder. If a locale doesn’t have a separate folder, the default form definition is used.

1forms
2	default
3		billingaddress.xml
4	it_IT
5		billingaddress.xml
6	ja_JP
7	billingaddress.xml

Localizing Strings Within Simple Forms 

Use resource strings directly from a form. The following example is of the loginform.isml that logs customers into the site. In this case, the form uses the label.input.login.email resource string identifier.

1<form action="${pdict.actionUrl}" class="login" method="POST" name="login-form">
2    <div class="form-group required">
3        <label class="form-control-label" for="login-form-email">
4            ${Resource.msg('label.input.login.email', 'login', null)}
5        </label>
6        <input type="email" id="login-form-email" class="form-control" name="loginEmail" value="${pdict.userName}">
7        <div class="form-control-feedback"></div>
8    </div>

Depending on the locale, this resource identifier resolves to different values

In the English app_storefront_base/cartridge/templates/resources/login.properties file:

1label.input.login.email=Email

In the French app_storefront_base/cartridge/templates/resources/login_fr_FR.properties file:

1label.input.login.email=E-mail

Remember to add the country to select to your country selector and to configure the locale for the site in Business Manager.

Note

Localizing Strings Within Complex Forms 

All form strings can be replaced with resource strings. Resource strings for forms are located by default in the forms.properties file for your cartridge and referenced from the form definition file. Add files with the name forms_locale_.properties to add localized strings. For example, add a forms_it_IT.properties file for an Italian version of the same properties. Different fields for the form may be needed, depending on the locale. Make sure that the strings for those fields are included in the localized version of the properties files.

Example: Localizing Labels and Error Messages 

The following form definition file defines a form to enter contact information. This example doesn’t show the entire form definition, just some of the fields that use localized strings for labels and error messages. Find this file as the contactus.xml form in the SiteGenesis app_storefront_core cartridge.

1<?xml version="1.0"?>
2<form xmlns="http://www.demandware.com/xml/form/2008-04-19">
3
4	<field formid="firstname" label="contactus.firstname.label" type="string" mandatory="true" binding="firstName" max-length="50"/>
5	<field formid="lastname" label="contactus.lastname.label" type="string" mandatory="true" binding="lastName" max-length="50"/>
6	<field formid="email" label="contactus.email.label" type="string" mandatory="true"  parse-error="contactus.email.parse-error" />

The label and error strings in bold reference the properties set in the forms.properties file, which contains entries like the following for the default site locale:

1##############################################
2# Template name: forms/contactus
3##############################################
4contactus.firstname.label=First Name
5contactus.lastname.label=Last Name
6contactus.email.label=Email
7contactus.email.parse-error=The email address is invalid.

The form is localized in the forms_it_IT.properties file (along with the other locale-specific forms_locale_.properties files) with entries like the following:

1##############################################
2# Template name: forms/contactus
3##############################################
4contactus.firstname.label=Nome
5contactus.lastname.label=Cognome
6contactus.email.label=Email
7contactus.email.parse-error=L'indirizzo email non è valido.

Validating Form Data 

Server-side validation on form data is configured in the form definition. SFRA uses jQuery AJAX methods to render a page after server-side validation.

Validation by Attribute 

The attributes set on the form field are used for validation. In the following example, the mandatory attribute requires a value for the field. The regexp attribute determines the content of the field. And the max-length attribute sets the maximum length of the data for the field.

The max-length attribute is used only for validation of strings. For other field types, it’s used only to format the field length and not to validate data.

Note

1<field formid="email" label="contactus.email.label" type="string" mandatory="true" regexp="^[\w.%+-]+@[\w.-]+\.[\w]{2,6}$" max-length="50"/>

Errors shown for attribute validation:

  • Default error for form invalidation: value-error

  • Mandatory flag invalid: missing-error

  • Entered value invalid: parse-error

Validation by Function 

Use the validation attribute to specify a function to run to validate form data. Run these validations on container elements, such as form or group, or on individual fields.

1<field formid="password"
2       label="label.password"
3       type="string"
4       range-error="resource.customerpassword"
5       validation="${require('~/cartridge/scripts/forms/my_custom_script.ds').my_custom_validation(formfield);}"

Selectively invalidate form elements using the InvalidateFormElement pipelet in pipelines or the invalidateFormElement function in the FormModel or any model that requires it. If any element in a form is invalid, the entire form is invalid. However, in your form definition, create error messages that are specific to a field. See the example of range-error, which points to a resource string with a message for the customer on why the field is invalid.

Client-Side Validation Scripts 

Simple forms are standard HTML forms, so use any client-side validation method you choose. B2C Commerce uses default HTML5 validation for client-side validation. Find the client-side JavaScript for a page by identifying the script added by the assets.AddJs function.

B2C Commerce provides two utility scripts for validating form data:

  • form-validation: This script validates a specific field in the form. It uses the validation criteria set in the form definition and included in the attributes for the form JSON object. This script is required by the client-side JavaScript doing the validation for a specific form and is loaded at document.ready. This file is located in app_storefront_base/cartridge/client/js/default/components/form-validation.js.
  • client-side-validation: This script validates the entire form and clears a form for validation. This file is required by main.js. It’s located in app_storefront_base/cartridge/client/js/default/components/client-side-validation.js

Saving Form Data 

The route:BeforeComplete event is used to store form data. Different APIs are used to save data, depending on the type of form.

This example constructs an object that contains the relevant information from the form and saves it to the ViewData object, so it can be passed. This example can be seen in the Account.js SavePassword function.

1var profileForm = server.forms.getForm('profile');       //gets the profile form object
2var newPasswords = profileForm.login.newpasswords;
3...
4var result = {                                           //constructs an object containing the form result
5    currentPassword: profileForm.login.currentpassword.value,
6    newPassword: newPasswords.newpassword.value,
7    newPasswordConfirm: newPasswords.newpasswordconfirm.value,
8    profileForm: profileForm
9};
10
11if (profileForm.valid) {
12    res.setViewData(result);                         // adds form result to the ViewData object
13    this.on('route:BeforeComplete', function () { // creates the function to run before middleware completion
14        var formInfo = res.getViewData();            // creates object with data to save
15        var customer = CustomerMgr.getCustomerByCustomerNumber( //gets current customer
16            req.currentCustomer.profile.customerNo
17        );
18        var status;
19        Transaction.wrap(function () {                //saves the new customer password and returns status
20            status = customer.profile.credentials.setPassword(
21                formInfo.newPassword,
22                formInfo.currentPassword,
23                true
24            );
25        });

Clearing or Refreshing a Form 

In SFRA, you use the server.getForms function to get the form data structure from the relevant form definition and convert it into a JSON object. The object is then added to the data passed to the template, so that it’s available to the template via the pdict variable. To clear the form, you must manually call the clear method.

This example gets the profile form and clears it.

1function (req, res, next) {
2    var accountModel = getModel(req);
3    var profileForm = server.forms.getForm('profile'); //gets the profile form object
4    profileForm.clear();              //clears the form using a function from the server module forms.js

Prepopulating Form Data 

Prepopulate forms with information from system objects, custom objects, and form data.

To Get Data from System Objects 

Use the server module form.jscopyObjectToForm` method to get data from an existing form object. Use the metadata attributes for a system or custom object to prefill form data.

To Get Data from Other Forms 

Use the FormModel.js copyFrom function to get data from an existing form object. Usually, if you have used app.getForm to get a copy of a form model, it makes more sense to use the function. Transfer form data from one form to another directly. In the following example, if a customer decides to use the shipping address for billing, the values from one form are copied to the other.

1server.get(
2    'EditProfile',
3    server.middleware.https,
4    csrfProtection.generateToken,
5    userLoggedIn.validateLoggedIn,
6    function (req, res, next) {
7        var accountModel = getModel(req);
8        var profileForm = server.forms.getForm('profile'); //gets the profile.xml form definition and converts it to a JSON object.
9        profileForm.clear();                               //clears the JSON object
10        profileForm.customer.firstname.value = accountModel.profile.firstName;    //copies data from one field to another
11        profileForm.customer.lastname.value = accountModel.profile.lastName;
12        profileForm.customer.phone.value = accountModel.profile.phone;
13        profileForm.customer.email.value = accountModel.profile.email;
14        res.render('account/profile', {
15            profileForm: profileForm,                                          //adds the JSON object to the data for the template
16            breadcrumbs: [
17                {
18                    htmlValue: Resource.msg('global.home', 'common', null),
19                    url: URLUtils.home().toString()
20                },
21                {
22                    htmlValue: Resource.msg('page.title.myaccount', 'account', null),
23                    url: URLUtils.url('Account-Show').toString()
24                }
25            ]
26        });
27        next();
28    }
29    );

To Copy Values from One Object to Another 

To copy values from one custom object to another, don’t use the dw.web.FormGroup copyFrom() and copyTo() methods. The copyTo() method requires a form submit to set values in the custom object. Instead, use Javascript to directly copy the values, as in this example:

1let testObject = { name:"default name", subject:"default subject", message:"default message" };
2let output = {};
3Object.keys( testObject ).forEach( function( key ) {
4   output[key] = testObject[key];
5});

Converting Form Data to JSON Objects 

Prepopulate forms with information from system objects, custom objects, and in-memory form data. This data is available directly from the model you’re working with or from the ViewData object used for rendering the template. The server module in the modules folder includes a forms.js module that converts form data into JSON objects. For more information, see the following functions in the server-side JSDoc.

  • parseForm(Form)
  • copyObjectToForm(object, CurrentForm)
  • findValue(formGroup, name)
  • clearOptions(obj)

SFRA provides a forms module that abstracts the form definition into a JSON representation. If you want to work with JSON objects, use the modules and forms methods to get and store data.

Securing Forms 

Use the new CSRF (Cross-Site Request Forgery) framework to add fields that are protected from request forgery.

CSRF in SFRA is provided as middleware by B2C Commerce. CSRF checks are performed as the middleware step csrfProtection.validateAjaxRequest.

Example: CSRF check is made for login information. This example is available in the Account.js controller.

1server.post(
2    'Login',
3    server.middleware.https,
4    csrfProtection.validateAjaxRequest,
5    function (req, res, next) {
6        var data = res.getViewData();
7        if (data && data.csrfError) {
8            res.json();
9            return next();
10        }

For more information, see validateRequest and validateAjaxRequest in the JSDoc.