Skip to main content

Form Methods

Forms are a good way to interact with visitors in an Experience. Often forms require dynamically set data, or even dynamically defined fields. Using the Experience JS SDK it is possible to set form field values and show or hide form fields. The methods bellow all work on Forms in one way or another.

Setting Values

Often times a value needs to be set in an Experience, this can be a specific ID, or the value of a form field. The following functions allow these values to be set programmatically.

External User Id

The Wyng platform provides several different ways to identify users, however to better integrate with other systems it can be useful to use a non-Wyng User Id. Wyng provides the possibility to do so through the setUserId() function. Any string or numeric value can be used as an Id. To make forms aware of the External User Id, a field of "Hidden Value: External User ID" can be added to the form. This field will be hidden from the user, and will be populated with the string or numeric value that is set through the setUserId() function.

Examples

Setting a User Id from custom code

The user Id can be set using any type of code. This example shows how to set the user Id using some custom code that produces the user Id

function customFunctionGetUserId() {
// custom javascript code to get the user Id in a variable called userId
return userId
}

window.wyng['_WYNG_ID_'].setUserId(customFunctionGetUserId());
Setting a User Id from a URL parameter

This example shows how to set the user Id that is passed in using a URL parameter. In this example, the URL parameter is userId

function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

window.wyng['_WYNG_ID_'].setUserId(getUrlParameter('userId'));

Setting form fields

Forms are a big part of most Experiences. Often times the fields in forms need to be dynamically set. Fields can be set dynamically using the setField (for one field at a time) and setFields (multiple fields at once) functions.

Fields types with non-string values

Most form fields will expect a string as the value. However there are a few form field types that expect a different data type for the value. See the examples listed by the setAndValidateFormField method for all the different field types their possible formats.

In the examples listed below, we have tried to incorporate some non-string type examples. However we refer back to the setAndValidateFormField section for all possible examples. Unless otherwise indicated, the setField and setFields methods use the same formats as setAndValidateFormField to set Values.

Examples

Setting a single field value

The following code will set the value for a field named email_address_7615019884892 to john.smith@my-email.com

window.wyng['_WYNG_ID_'].setField('email_address_7615019884892', 'john.smith@my-email.com');
Setting multiple values at once

The following code will set multiple values in one call. It will set email_address_7615019884892 to john.smith@my-email.com, first_547245235432 to John and last_356363463634 to Smith It will also check the checkboxes for "Choice 2", and "Choice 4" in the mult-select field multi_select_543216449245, while unchecking all of its other fields. For the date field date_9876543210 is will set the value to January 25, 2014. The calendar date field calendar_date_56798723424987 will be set to August 7,1993

window.wyng['_WYNG_ID_'].setFields({
email_address_7615019884892: 'john.smith@my-email.com',
first_547245235432: 'John',
last_356363463634: 'Smith',
multi_select_543216449245: ["Choice 2", "Choice 4"],
date_98776543210: {
monthValue: '1',
dayValue: '25',
yearValue: '2014',
},
calendar_56798723424987: new Date("1993-08-07"),

});

Normalized field names

Wyng form fields are given names that are made up out of a part identifying the field type, and a randomly generated integer. While it is possible to rename most fields to something else, this is almost never done. Because it can be tedious to have to find the exact field Id, the setField and setFields functions have been written to allow for normalized field names to be set. Utilizing this feature also increases the ease of use when reusing code from different experiences.

caution

When using the normalized field names, it is important to realize that the setField and setFields functions will set ALL matching fields in all components in the experience. If an experience has multiple components that have form fields that match, all those fields will be set. However if a single component has multiple fieds that could match the normalized name, a warning will be thrown which can be found in the console.

Examples

Set a single field value

The same examples are used as described above. A field named email_address_7615019884892 will be set to john.smith@my-email.com

window.wyng['_WYNG_ID_'].setField('email_address', 'john.smith@my-email.com');
Setting multiple values at once

Again the same example as above. The following code will set multiple values in one call. It will set email_address_7615019884892 to john.smith@my-email.com, first_547245235432 to John and last_356363463634 to Smith

window.wyng['_WYNG_ID_'].setFields({
email_address: 'john.smith@my-email.com',
first: 'John',
last: 'Smith',
multi_select: ["Choice 2", "Choice 4"],
date: {
monthValue: '1',
dayValue: '25',
yearValue: '2014',
},
calendar: new Date("1993-08-07"),
});

Validating values

Wyng forms have validation functions built in for different types of data types. The Experiences JS SDK exposes these validation functions in a way that they can be used outside of forms as well.

validate

Arguments:

ArgumentTypeDescription
typestring - requiredThe type of data to validate for.
valuestring - requiredThe value to validate.

The validate method will validate the value given against the Wyng validator function for the type you have specified. It will return true when the value is valid, and false when it is invalid.

Examples

window.wyng['_WYNG_ID_'].validate('email', 'john.smith@my-email.com');

Submitting Forms

Normally forms get submitted by the user when clicking the Submit button, however it is possible to submit a form using the SDK. When a form is submitted only through the SDK the form can be configured in the builder to be hidden. This is done by setting the toggle "Hide form" on.

submitForm

Arguments:

ArgumentTypeDescription
formIdstring - requiredThe componentId of the form that should get submitted.
fieldsobject - optionalAn object containing key value pairs of field values to be submitted

To submit the form, the submitForm method is called. The second optional argument contains any form field values that need to be submitted. For any field value that is not provided in the fields object the current value that is set in the form will be used to submit the form.

note

Submitting forms is an asynchronous action. The submit method does not return a value, or any results of the form submission. To handle the result of the submission see Form Component Events on how to register event listeners to handle form submissions.

Examples

This example will submit the form with componentId sign_up_436366175206.

window.wyng['_WYNG_ID_'].submitForm('sign_up_436366175206');

formHasErrors

Arguments:

ArgumentTypeDescription
formIdstring - requiredThe componentId of the form for which we want to know if it has errors.

Check to see if a specific form has errors

if (window.wyng['_WYNG_ID_'].formHasErrors('sign_up_436366175206')) {
// Handle the errors in the form
console.log('The form "sign_up_436366175206" has errors that need to be addressed before being able to submit');
}
note

This method is meant to be used only before the form gets submitted. After the form is submitted, to handle errors after submitting the form see Form Submit Error on how to register an event listener to handle form submission errors.

formErrors

Arguments:

ArgumentTypeDescription
formIdstring - requiredThe componentId of the form for which we're trying to get the errors.

Get the actual errors in the form

console.error(window.wyng['_WYNG_ID_'].formErrors('sign_up_436366175206');
note

This method is meant to be used only before the form gets submitted. After the form is submitted, to handle errors after submitting the form see Form Submit Error on how to register an event listener to handle form submission errors.

Form Status

formLimitReached

This method is used to check the status of the total submission limit of a specific form. The method will return true when the participation limit has been reached, and false when it has not yet been reached.

Arguments:

ArgumentTypeDescription
formIdstring - requiredThe componentId of the form for which we want to know if the participation limit has been reached
window.wyng['_WYNG_ID_'].formLimitReached('sign_up_436366175206');

Multiple Choice Options

Several Wyng form fields are multiple choice fields that give the user a pre-configured list of choices to pick the answer from. The list of choices can be configured in the form, however sometimes it is necessary to dynamically change the choice list. The following methods can be used to get the current list of choices, clear the list, add a new option, and/or define an entire new list of choices.

getChoices

Arguments:

ArgumentTypeDescription
fieldIdstring - requiredThe fieldId of the field to get the choices from.
componentIdstring - requiredThe componentId of the form that the field is in

Get the list of choices that are set for a specific field. The choices are returned in same the format as they are stored in memory. Different field types have different formats. The format that the choices are returned in can be used directly as an argument in the setChoices method.

This example will get the choices from the field form_field_12345 in the form with component ID sign_up_436366175206.

const choices = window.wyng['_WYNG_ID_'].getChoices('form_field_12345', 'sign_up_436366175206');
console.log(choices);

setChoices

Arguments:

ArgumentTypeDescription
choices`array of mixed (stringobject)` - required
fieldIdstring - requiredThe fieldId of the field to set the choices for.
componentIdstringThe componentId of the form that the field is in

Set the list of choices for a specific field. componentId is an optional argument, should there be multiple fields within the experience with the same fieldId, all fields will have the choices set to the value of choices.

The choices array expects a different format depending on the field type that the choices are set for. With the exception of the "Multiple Choice with Groups" field, all fields do accept an array of strings with the strings being the choices offered. However the "Multiple Choice" field also allow for the value that is displayed to the user to be different from the value that is actually submitted. The Multiple Choice field can also accept an array of objects where the object is structured as { "choice": "Display Value", "value": "actual submitted value" } for cases when setting a display value different from the submitted value is important.

window.wyng['_WYNG_ID_'].setChoices(
[
{
choice: 'Choice 1',
value: 'choice_1'
},
{
choice: 'Choice 2',
value: 'choice_2',
}
],
'multiple_choice_with_values_9898280071405',
'sign_up_436366175206'
);

appendChoice

Arguments:

ArgumentTypeDescription
choicemixed (string|object) - required
fieldIdstring - requiredThe fieldId of the field to add the choice to.
componentIdstringThe componentId of the form that the field is in

Add one choice to the end of the already existing choices in a field.

Notice

The appendChoice method does not work on the Multiple Choice with Groups field.

window.wyng['_WYNG_ID_'].appendChoice(
{
choice: 'Choice 1',
value: 'choice_1'
},
'multiple_choice_with_values_9898280071405',
'sign_up_436366175206'
);

clearChoices

Arguments:

ArgumentTypeDescription
fieldIdstring - requiredThe fieldId of the field to clear the choices from.
componentIdstringThe componentId of the form that the field is in.

Remove all choices that are currently set for the field with the given fieldId in the component with the given componentId. If the componentId is not given, any field in the experience that matches the fieldId will have all of its choices removed.

This example will remove all choices from any form field with the fieldId form_field_12345

window.wyng['_WYNG_ID_'].clearChoices('form_field_12345');

Hiding Fields

Fields can be defined in the Form, but under certain circumstances the field might not be needed. In that case, the field needs to be hidden. This can be done with either the hideFields or the hideField method. Both methods do the same thing. The only difference being that hideField will only hide one field at a time, while hideFields allow multiple fields to get hidden in one function call.

When fields get hidden using the SDK the fields will be removed from the front-end completely. Please be advised that fields that have been marked as Required in the Experience Builder will not be allowed to be hidden. If a field is marked as required and it matches the hideField or hideFields call, an error will be printed in the console about that specific field, and the specific field will not get hidden.

hideFields

Arguments:

ArgumentTypeDescription
fieldsarray of strings - requiredAll field ID's that need to get hidden. Values can be normalized
componentIdstringThe componentId of the form that the fields are in

Hide multiple form fields at once. The argument componentId is optional. If it is not provided, all matching form fields in all forms in the experience will get hidden.

The form fields are normalized

This example will hide all form fields named form_field_123456 as well as form fields starting with first_ (normalized). Form fields named first will also get hidden.

window.wyng['_WYNG_ID_'].hideFields([ 'form_field_123456', 'first' ]);

hideField

Arguments:

ArgumentTypeDescription
fieldstring - requiredField ID of the field that will get hidden. Values can be normalized
componentIdstringThe componentId of the form that the fields are in (optional)

Hide a form field. The argument componentId is optional. If it is not provided, all fields that having a matching Field ID on all forms in the experience will get hidden.

The form fields are normalized

This example will hide all form fields named form_field_123456. No componentId is specified, so matching fields in all forms in the experience will get hidden.

window.wyng['_WYNG_ID_'].hideField('form_field_123456');

Showing Fields

revealFields

Arguments:

ArgumentTypeDescription
fieldsarray of strings - requiredAll field ID's that need to get shown. Values can be normalized
componentIdstringThe componentId of the form that the fields are in

Show multiple hidden form fields at once. The argument componentId is optional. If it is not provided, all matching form fields in all forms in the experience will get hidden.

The form fields are normalized

This example will show all form fields named form_field_123456 as well as form fields starting with first_ (normalized). Form fields named first will also get revealed.

window.wyng['_WYNG_ID_'].revealFields([ 'form_field_123456', 'first' ]);

revealField

Arguments:

ArgumentTypeDescription
fieldstring - requiredThe field ID that need to get shown. Values can be normalized
componentIdstringThe componentId of the form that the field is in (optional)

Show multiple hidden form fields at once. The argument componentId is optional. If it is not provided, all matching form fields in all forms in the experience will get hidden.

The form fields are normalized

This example will show all form fields named form_field_123456.

window.wyng['_WYNG_ID_'].revealField('form_field_123456');

Making Fields Required

Making fields be required dynamically can be done using these methods. Please be advised that while this will add the verification to the front end, the back end will not do any additional validations. If it is important that the backend does a validation, the required checkbox in the Form Edit Modal in the Experience Builder should be used.

requireFields

Arguments:

ArgumentTypeDescription
fieldsarray of strings - requiredArray of field IDs that need to be made required. Values can be normalized
componentIdstringThe componentId of the form that the field is in (optional)

Make multiple form fields required at once. The argument componentId is optional. If it is not provided, all matching form fields in all forms in the experience will become required.

The form fields are normalized

This example will make form fields named form_field_123456 required as well as all form fields that normalize to last.

window.wyng['_WYNG_ID_'].requireFields(['form_field_123456', 'last']);

requireField

Arguments:

ArgumentTypeDescription
fieldstring - requiredField ID of the field that will be made required. Values can be normalized
componentIdstringThe componentId of the form that the field is in (optional)

Make a form field required. The argument componentId is optional. If it is not provided, all matching form fields in all forms in the experience will become required.

The form field can be a normalized value

This example will make form field named form_field_123456 required.

window.wyng['_WYNG_ID_'].requireField('form_field_123456');

Making Fields Optional

These methods can be used to make fields optional. To use this method, the form field configuration in the experience must also be set to optional. If the required checkbox in the form configuration is checked, this method will not work, due to backend validations that will continue to be enforced.

makeFieldsUnrequired

Arguments:

ArgumentTypeDescription
fieldsarray of strings - requiredArray of field IDs that need to be made optional. Values can be normalized.
componentIdstringThe componentId of the form that the field is in (optional)

Make multiple form fields optional at once. The argument componentId is optional. If it is not provided, all matching form fields in all forms in the experience will become optional.

The form fields are normalized

This example will make form fields named form_field_123456 optional as well as all form fields that normalize to last.This assumes that all of the target fields are already set as optional in the form configuration in Wyng.

window.wyng['_WYNG_ID_'].makeFieldsUnrequired(['form_field_123456', 'last']);

makeFieldUnrequired

Arguments:

ArgumentTypeDescription
fieldstring - requiredField ID of the field that will be made optional. Values can be normalized
componentIdstringThe componentId of the form that the field is in (optional)

Make a form field optional. The argument componentId is optional. If it is not provided, all matching form fields in all forms in the experience will become optional.

The form field can be a normalized value

This example will make form field named form_field_123456 optional. This assumes that the target fields are already set as optional in the form configuration in Wyng.

window.wyng['_WYNG_ID_'].makeFieldUnrequired('form_field_123456');

Resetting Fields

To reset fields to their default state or values, you can use either the resetFields or resetField method. Both methods achieve the same result, with the difference being that resetField resets one field at a time, whereas resetFields allows multiple fields to be reset in a single function call.

resetFields

Arguments:

ArgumentTypeDescription
fieldsarray of strings - requiredAll field IDs that need to get reset. Values can be normalized
componentIdstringThe componentId of the form that the fields are in

Reset multiple form fields at once. The argument componentId is optional. If it is not provided, all matching form fields in all forms in the experience will get reset.

The form fields are normalized

This example will reset all form fields named form_field_123456 as well as form fields starting with first_ (normalized). Form fields named first will also get reset.

window.wyng['_WYNG_ID_'].resetFields([ 'form_field_123456', 'first' ]);

resetField

Arguments:

ArgumentTypeDescription
fieldstring - requiredField ID of the field that will get reset. Values can be normalized
componentIdstringThe componentId of the form that the fields are in (optional)

Reset a form field. The argument componentId is optional. If it is not provided, all fields that having a matching Field ID on all forms in the experience will get reset.

The form fields are normalized

This example will reset all form fields named form_field_123456. No componentId is specified, so matching fields in all forms in the experience will get reset.

window.wyng['_WYNG_ID_'].resetField('form_field_123456');