JavaScript SDK for headless Optimizely Forms
Use JavaScript SDK
To use the JavaScript SDK, install @episerver/form-sdk
(required) and @episerver/form-react
(optional) if you are rendering with React. Then, add the Form
component imported from @episerver/form-react
along with the form key and base URL to render the form:
<Form
key={formKey}
formKey={formKey}
language={language ?? "en"}
baseUrl={process.env.REACT_APP_HEADLESS_FORM_BASE_URL ?? "/"}
identityInfo={identityInfo}
history={history}
currentPageUrl={pageUrl}
/>
Form SDK
Properties of models.
-
Form
container model properties:Key
– The GUID to identify the formProperties
– Contains form-setting properties such asTitle
,Description
,Success message
, and so on.FormElements
– Contains a list of form elements.
-
Element
block model properties:Key
– The GUID to identify the element block.ContentType
– Describes the type of element,TextboxElementBlock
,SubmitButtonElementBlock
, and so on.Properties
– Contains other element properties such asLabel
,Placeholder
,PredefinedValue
,Validators
(a list of validators to validate the element's input data), and so on.
-
Validator
model properties:Type
– The type ofValidator
,RequiredValidator
,RegularExpressionValidator
,EmailValidator
, and so on.Message
– A notification message when the data is not satisfied.
-
FormLoader
class – This is an API client used to call the Headless Form API. The only parameter that needs to pass when initializingFormLoader
isBaseUrl
, which is the root link to the API endpoint; for example:http://example.com
. -
FormValidator
class – A class that pre-defines methods to validate data, based onValidator
types, and the corresponding validation methods are called to validate the input data and return true or false values.
Form React SDK
FormContext
is implemented from ReactContext
to store FormState
. FormState
includes the following components:
FormSubmission
– Saves the values of elements when the user enters them.FormValidation
– Saves data validation results.FormContainer
– Saves form metadata.
React components are elements (TextboxElementBlock.tsx
, TextareaElementBlock.tsx
, and so on) and forms (Form.tsx
, FormContainerBlock.tsx
) that receive form metadata to render forms, input, select, textarea, and so on, as HTML.
FormAuthenticate
FormAuthenticate
is an API client service that authenticates headless Optimizely Forms API when the form does not allow anonymous submission.
Method
login
– Function to login with the given username and password and return an access token string.
Usage
//init config option
var config = {
clientId: "name\_of\_client",
grantType: "password",
authBaseUrl: "<http://yourdomain.com/api/episerver/connect/token>
}
//get token
var formAuthenticate = new FormAuthenticate(config);
formAuthenticate.login("username", "password").then((tokenString) =\> {
//your login here
});
FormCache
FormCache
is a helper class that gets, sets, or removes data from sessionStorage
or localStorage
of a browser. The default storage is sessionStorage
.
Methods
get\<T>
– Loads data items that are saved in storage.set\<T>
– Saves data items into storage.remove
– Removes data items that are saved in storage.
Usage
//init
var formCache = new FormCache();
//in-case you want to save to localStorage
// var formCache = new FormCache(window.localStorage);
//save data to cache
formCache.set("key", "value");
//receive data from cache
formCache.get("key");
//remove data from cache
formCache.remove("key");
FormDependConditions
FormDependConditions
checks conditions for an element dependent on another element. The main function checkConditions()
returns a Boolean: true if all conditions are satisfied and otherwise false.
Method
checkConditions
– Determines whether an element's dependent conditions are satisfied.
Usage
//init
var formDependConditions = new FormDependConditions(formElement);
// The parameter **element** is a form element that is a child of the current **FormContainer**.
//check if satisfy the conditions
var isSatisfied = formDependConditions.checkConditions(formSubmissions);
// The parameter **formSubmissions** is an array of form element values that are inputted by user. For example: [{elementKey: "", value: ""}];
FormLoader
FormLoader
is an API client service that gets a form by formKey
. The getForm()
function returns an object of type FormContainer
.
Method
getForm
– Gets a form with GUID key and returns a promise with a form.
Usage
//init
var formLoader = new FormLoader({
baseUrl: “http: //yourdomain.com/”});
//receive a form
var form = formLoader.getForm(formKey, formLanguage);
// formKey is a GUID identifier of form
// formLanguage is locale of form. For example: en, sv, …
StepBuilder
StepBuilder
is a helper class that arranges elements by step. The buildForm()
function causes FormContainer
to be an array of step
that contains the elements of the step.
Method
buildForm
– Arranges elements by step and returns a form with property steps that is updated.
Usage
//init
var stepBuilder = new StepBuilder(formContainer);
// formContainer parameter is a form that was received from API.
//get form that arranged elements by step
var form = stepBuilder.buildForm();
FormStorage
FormStorage
is a helper class that saves, loads, or removes an array of FormSubmission
from sessionStorage
of a browser.
Methods
saveFormDataToStorage
– Function to save form data submission in storage.loadFormDataFromStorage
– Function to load form data submission from storage.removeFormDataInStorage
– Function to remove form data submission from storage.
Usage
//init
var formStorage = new FormStorage(formContainer);
//save data to storage
formStorage.saveFormDataToStorage(formSubmissions);
//load data from storage
var formSubmissions = formStorage.loadFormDataFromStorage();
//remove data from storage
formStorage.removeFormDataInStorage();
FormSubmitter
FormSubmitter
is an API client service class that posts a collection of FormData
to headless Optimizely Forms API.
Methods
doSubmit
– Submits form data submission to the API and returns a promise resolve with an objectFormSubmitResult
, or a reject with an objectProblemDetail
.doValidate
– Validates form data submissions and returns the list of validation results.
Usage
//init
var formSubmitter = new FormSubmitter(formContainer, baseUrl);
//validate data before submit
var validationResult = formSubmitter.doValidate(formSubmissions);
//submit form to API
var formSubmitModel = {
formKey: formContainer.key
locale: formContainer.locale,
isFinalized: true
partialSubmissionKey: "partialSubmissionKey",
hostedPageUrl: "/",
submissionData: formSubmissions,
accessToken: "accessToken",
currentStep: 0
};
//logic to handle result
formSubmitter.doSubmit(formSubmitModel).then((result) = \ > {
//logic to handle exception
}).catch((error) = \ > {
});
FormValidator
FormValidator
validates the input value of the form element by validators defined in the form element's metadata. These are basic validators: RequiredValidator
, EmailValidator
, RegularExpressionValidator
, and so on. The main function validate()
returns true (valid) or false (not valid).
Methods
validateRequired
– Validate the required element.validateRegex
– Validate the element with a RegEx pattern.validateFileExtension
– Validate the file extension of file input.validateFileSize
– Validate the file size of the file input.validateNumeric
– Validate the numeric elements.validate
– Validate the input value of the element that combines the above functions in a switch scope and returns the list of validation results.
Usage
//init
var formValidator = new FormValidator(formElement);
//validate input value
var result = formValidator.validate(value);
StepDependCondition
StepDependCondition
is a helper class that finds the next or previous step. If the step depends on the form element value, the class checks whether the step satisfies the dependent conditions. If it is satisfied, the step index is returned as a result. Otherwise, it attempts to find another one.
Methods
isSatisfied
– Check whether the step is satisfying the dependent condition.findNextStep
– Recursive finding next step to display in the form.findPreviousStep
– Find the previous step to display in the form.isStepValidToDisplay
– Check whether the step index is valid to display.getInactiveStepsIndex
– Get an array of inactive step indexes by dependent conditions.
Usage
//init
var stepDependCondition = new StepDependCondition(dependencyInactiveElements);
// The parameter **dependencyInactiveElements** is an array of form element keys that are inactive, since they are not satisfying the depend conditions. This parameter will need to check satisfy the depend conditions for step.
//find next step index
var nextStepIndex = stepDependCondition.findNextStep(currentStepIndex);
//find previous step index
var previousStepIndex = stepDependCondition.findPreviousStep(currentStepIndex);
StepHelper
StepHelper
is for step function helpers.
Methods
isAllStepsAreNotLinked
– Verify the form has all steps not attached to any page.isMalFormSteps
– Check whether a form has steps each attached to a page.getCurrentStepIndex
– Get the current step index depending on the current page URL.isInCurrentStep
– Check whether the element is in step.getFirstInvalidElement
– Get the firstelementKey
in the list elements that are invalid values.isNeedCheckDependCondition
– Check whether a step is needed to check the dependent condition.
Usage
//init
var stepHelper = new StepHelper(formContainer);
//get current step index
var stepIndex = stepHelper. getCurrentStepIndex(currentPageUrl);
Other util functions
getDefaultValue
– Get a default value of the element. The value can bepredefinedValue
, the first value of autofill data or values of items are checked.initFormState
– InitializeFormState
object based onFormContainer
.
List of Models
Element base types
FormElementBase
– Base type for elements of forms.ValidatableElementBase
– Base type for elements that can be applied with the validator.DataElementBlockBase
– Base type of elements support validating and field-mapping to another system.InputElementBase
– Base type for the input elements.SelectionBase
– Base type for a selection of elements such as radios, checkboxes, dropdown, and listbox.ButtonBase
– Base type for button-type elements.HiddenElementBase
– Base type for hidden form elements.
Element types
Textbox
– Input and display a single line of text.Textarea
– Input and display multiple lines of text within a defined area.SubmitButton
– Submit the form.Selection
– Can be rendered as Combobox or Listbox, based onSelectionBase
'sallowMultiSelect
property.ResetButton
– Note that the Reset button must be in a "form tag" to be functional.Range
– Select an integer value within a specified range.PredefinedHidden
– Hidden with a predefined value.ParagraphText
– Rich text (with placeholder).Number
– Input numeric values.ImageChoice
– Select from a set of images.FormStep
– Indicates a form step has ended.FileUpload
– Select files to be included in a form submission.Choice
– Can be rendered as Radio or Checkbox, based onSelectionBase
'sallowMultiSelect
property.Url
– Input and display a URL.VisitorDataHidden
– Collects visitor data (IP, geo, browser, and so on) using a hidden input.
Condition type
Condition
– Determines whether the element should be displayed or hidden based on a given condition.ConditionProperties
– Block that is displayed or hidden based on a given condition.
Enum types
ConditionCombinationType
– Combine results of all conditions satisfied.ConditionFunctionType
– Enum represents a dependent condition operator (in the rule to evaluate dependent value).FormConstants
– The list of constants is the keyword used for cached values.SatisfiedActionType
– The action when the condition is satisfied.SubmitButtonType
– Enum represents the type name of step navigation.ValidatorType
– The list of validator types.
State types
FormState
– Type of object that is the form context.FormSubmission
– Type of object that is form submission.FormValidationResult
– Type of object that is form validation result.ElementValidationResult
– Type of object that is the element validation result.
Other types
FormContainer
– The form is rendered as a hidden container.IdentityInfo
– Type of object that is identity information.ProblemDetail
– Type of API exception.
Updated 2 months ago