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.
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.
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
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.
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.
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.
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.
This template prints the form field label and data stored from the form.
Hello World Form Result
Nice to meet you, ${pdict.nickname}.