Forms 2.0

Page Last Updated: June 2015

Forms 2.0 empowers Marketers to create beautiful, stable, and flexible web forms without programming knowledge. Forms can reside on Marketo landing pages and also be embedded on any page of your website. The core functionality of a Marketo web form can be extended using Forms 2.0 JavaScript API.

 Jump to: Examples or API Reference

Getting Started


1. Create a form using Form Editor 2.0 from within Marketo Lead Management form designer

Create new Marketo form

2. Approve the form

Approve form

3. Right click the form in the tree menu and select "Embed Code"

Embed form code

4. You will be given a script block like this one:

<script src="//app-sjqe.marketo.com/js/forms2/js/forms2.js"></script>
<form id="mktoForm_621"></form>
<script>
MktoForms2.loadForm("//app-sjqe.marketo.com", "718-GIV-198", 621);
</script>

 5. We'll start by editing the loadForm function call and add a callback parameter that allows us to get access to the form object.  All further script examples shown in this document will take place inside of this script block. 

<script>
MktoForms2.loadForm("//app-sjqe.marketo.com", "718-GIV-198", 621, function(form) {
    // From here we have access to the form object and can call its methods
});
</script>

Using the Forms2 JS API from Landing Pages.

While all of the below examples use embedded forms, the same APIs are available on Marketo Landing Pages as well.

Usually, you'll want to add a script that gets some reference to the form object. To do this, first add your form to the landing page, then add a new HTML block to your landing page. Then you can add a script block to the page:

<script>
MktoForms2.whenReady(function (form) {
    // Put your code that uses the form object here
});
</script>

 

Examples


1. Hide the form after successful submission.  Does not take the visitor to the follow up page or reload the current page.  View Example

MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function(form) {
    // Add an onSuccess handler
    form.onSuccess(function(values, followUpUrl) {
        // Get the form's jQuery element and hide it
        form.getFormElem().hide();
        // Return false to prevent the submission handler from taking the lead to the follow up url
        return false;
    });
});

2. Take the visitor to a URL determined by JavaScript after successful submission, instead of the configured thank you page.  View Example

MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function(form) {
    //Add an onSuccess handler
    form.onSuccess(function(values, followUpUrl) {
        // Take the lead to a different page on successful submit, ignoring the form's configured followUpUrl
        location.href = "https://google.com/?q=marketo+forms+v2+examples";
        // Return false to prevent the submission handler continuing with its own processing
        return false;
    });
});

3. Set form field values.  View Example

MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function(form) {
    // Set the value of the Phone and Country fields
    form.vals({ "Phone":"555-555-1234", "Country":"USA"});
});

4. Read form field values on form submit.  View Example

MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function(form) {
    // Add an onSubmit handler
    form.onSubmit(function(){
        // Get the form field values
        var vals = form.vals();
        // You may wish to call other function calls here, for example to fire google analytics tracking or the like
        // callSomeFunction(vals);
        // We'll just alert them to show the principle
        alert("Submitted values: " + JSON.stringify(vals));
    });
}); 

5. Submit a form based on a click event on some other element or event that is not part of the form.  View Example

// Load the form normally
MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057);

// Find the button element that you want to attach the event to
var btn = document.getElementById("MyAlternativeSubmitButtonId");
btn.onclick = function() {
    // When the button is clicked, get the form object and submit it
    MktoForms2.whenReady(function (form) {
        form.submit();
    });
};

6. Prevent a user from submitting a form. For the purpose of this example, you must click the click counter button at least three times before the submit button on the form will function.  View Example

MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function (form) { 
    // Check if the form is submittable
    if (form.submittable()) {
        // Set it to be non submittable
        form.submittable(false);
    }
});

var clickCount = 0;
// Wire up the click counter button
var clickCounterBtn = document.getElementById("ClickCounter");
clickCounterBtn.onclick = function() {
    clickCount++;
    // Update the buttons's text
    clickCounterBtn.innerHTML = "Click Counter Button ("+clickCount+")";

    if (clickCount >= 3) {
        // Get the form and set it to be submittable
        MktoForms2.whenReady(function (form) {
            form.submittable(true);
        });
    }
};

7. Set values on hidden fields on the form.  View Example

MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function (form) { 
    // Set values for the hidden fields, "userIsAwesome" and "enrollDate"
    // Note that these fields were configured in the form editor as hidden fields already
    form.vals({"userIsAwesome":"true", "enrollDate":"2014-01-01"});
});

8. Show the form in a lightbox style dialog if the url contains a parameter lightboxForm=true.  View Example

MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function (form) { 
    if (location.href.indexOf("lightboxForm=true") != -1) {
        MktoForms2.lightbox(form).show();
    }
});

9. Show a custom error message on submit based on custom business logic.  View Example

MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function (form) { 
    //listen for the validate event
    form.onValidate(function() {
        // Get the values
        var vals = form.vals();
        //Check your condition
        if (vals.Country == "USA" && vals.vehicleSize != "Massive") {
            // Prevent form submission
            form.submittable(false);
            // Show error message, pointed at VehicleSize element
            var vehicleSizeElem = form.getFormElem().find("#vehicleSize");
            form.showErrorMessage("All Americans must have a massive vehicle", vehicleSizeElem);
        }
else { // Enable submission for those who met the criteria form.submittable(true); } }); });

API Reference


There are two main objects that you will interact with using the Forms 2.0 API. The MktoForms2 object and the Form object.  The MktoForms2 object is the top level publicly visible namespace for Forms2 functionality and contains functions to create, load and fetch Form objects.

MktoForms2 Methods

.loadForm(baseUrl, munchkinId, formId [,callback])

Loads a form descriptor from Marketo servers and creates a new Form object.

returns undefined

baseUrl Type: String 
URL to the Marketo server instance for your subscription

munchkinId Type: String
Munchkin ID of the subscription

formId Type: String or Number
The form version id (Vid) of the form to load

callback Type: Function (optional)
A callback function to pass the constructed Form object to once it has been loaded and initialized.

.lightbox(form [,opts])

Renders a lightbox style modal dialog with the Form object in it.

returns  A lightbox object with .show() and .hide() methods.

form Type: Form Object
An instance of a Form object that you want to have rendered in a lightbox.

opts Type: Object (optional)
An object of options passed to the lightbox object

  • onSuccess  Type: Function
    A callback that will be triggered when the form is submitted.
  • closeBtn Type: Boolean default true
    Controls if a close button (X) is displayed on the lightbox dialog. 

.newForm(formData [,callback])

Creates a new Form object from a Form Descriptor JS object

returns undefined

formData Type: Form Descriptor Object 
A form descriptor object, as created by the Marketo Forms V2 Editor

callback Type: Function
A callback function that will be called once all stylesheets and known lead information has been fetched and the Form object has been created.
This callback will be called with a single argument, a newly created instance of Form object. 

.getForm(formId)

Gets a previously created Form object by form identifier

returns  Type: Form Object

formId  Type: Number or String

Form Vid Identifier. 

.allForms()

Fetches an array of all form objects that have been previously constructed on the page.

returns Type: Array of Form Object 

.getPageFields()

Gets a JS object containing data from the url and referrer that may be interesting for tracking purposes.

returns Type: Object

.whenReady(callback)

Adds a callback that will be called exactly once for each form on the page that becomes "ready". Readyness means that the form exists, has been initially rendered and had its initial callbacks called.

The callback is passed a single argument, a form object.

If there is already a form that is ready at the time this function is called, the passed callback will be called immediately.

returns

Object Type: MktoForms2

.onFormRender(callback)

Adds a callback that will be called every time any form on the page renders. Forms are rendered when initially created, then again every time that visibility rules alter the structure of the form.  

The callback will be passed a single argument, the form object of the form that was rendered.

returns

Object Type: MktoForms2

.whenRendered(callback) 

Like onFormRender, this adds a callback that will be called every time a form is rendered. Additionally, this will also call the callback immediately for all forms that have already been rendered.

The callback will be passed a single argument, the form object of the rendered form. 

returns

Object Type: MktoForms2

 

Form Methods

.render([formElem])

Renders a form object, returning a jQuery object wrapping a form element that contains the form.  If passed a formElem, it will use that as the form element, otherwise it will create a new one.

returns Type: jQuery Object
A jQuery wrapped form element containing the rendered form. 

formElem Type: jQuery Object
A jQuery wrapped form element into which to render. 

.getId()

Gets the id of the form.

returns Type: Number

The id of the form object that this form represents.

.getFormElem()

Gets the jQuery wrapped form element of a rendered form.

returns Type: jQuery Object 

A jQuery wrapped form element or null if the form has not been rendered with the render() method yet.

.validate()

Forces the form to validate, highlighting any errors that may exist and returning the result.  Does not submit the form.

returns Type: Boolean

true if all the validators on the form passed, false otherwise. 

.onValidate(callback)

 Adds a validation callback that will be called anytime validation is triggered.

returns Type: Form Object 
The same form object on which the method was called, for chaining purposes. 

callback Type: Function 
A callback that will be triggered any time that validation occurs.  
The callback will be passed one parameter, a boolean stating if the validation had succeeded.

 

.submit()

Triggers the form's submit event. This will start the from submit flow, performing validation, firing any onSubmit events, submitting the form, and firing any onSuccess events if form submission was successful. 

returns Type: Form Object 

The same form object on which the method was called, for chaining purposes. 

.onSubmit(callback)

Adds a callback that will be called when the form is submitted.  This is fired when the submission begins, before the success/failure of the request is known.

returns Type: Form Object 

The same form object on which the method was called, for chaining purposes. 

callback Type: Function
A function that will be called when the form is submitted.   This callback will be passed one argument, this Form object.

.onSuccess(callback)

Adds a callback that will be called when the form has been successfully submitted but before the lead is forwarded to the follow up page.  Can be used to prevent the lead from being forwarded to the follow up page after successful submission.

returns Type: Form Object 
The same form object on which the method was called, for chaining purposes. 

callback Type: Function

A function that will be called when the form has been successfully submitted.  This callback will be passed two arguments. A JS Object containing the values that were submitted and a String url of the follow up page that the user will be forwarded to, or null or empty string if there is no configured follow up page.

Special behavior: If this callback returns a false (measured using ===)  then the visitor will NOT be forwarded to the follow up page and the page will NOT be reloaded.  This allows the implementor to do extra processing to the follow up url, or to take action on page using JavaScript instead of leaving the page.

.submittable([canSubmit])
also available as:
.submitable([canSubmit])

Gets or sets whether the form can be submitted. If called with no arguments, it gets the value, if called with one argument it sets the value.This can be used to prevent a form from being submitted while other criteria outside of the normal form need to be fulfilled.

returns  Type: Boolean or Form Object.

If called with no arguments, returns a boolean indicating if the form is submittable.  If called with one argument, returns this Form Object for chaining purposes.

canSubmit  Type:Boolean
Sets the form to be submittable or non submittable.

 .allFieldsFilled()

Returns true if all the fields in the form have non-blank values set.

returns Type: Boolean 

True if all fields have non-blank/empty/unset/null values, false otherwise.

.setValues(vals)

Sets values on one or more fields in the form.

returns undefined 

vals Type: Object
A JS Object.  For each key/value pair in the object, the form field named key will be set to value.

.getValues()

Gets all the values of all the fields in the form.

returns 
A JS Object containing key/value pairs representing the names and values of the fields in the form.

.addHiddenFields(values)

Adds input type=hidden fields to the form.

returns

values 
Type: Object
A JS Object containing key/value pairs representing the names and values of the hidden fields to add to the form.

.vals([values])

jQuery style .vals() setter/getter.  If called with no arguments, is equivalent to calling getValues().  If called with one argument, is equivalent to calling setValues() 

returns

values 
Type: Object

.showErrorMessage(msg [,elem])

Shows an error message, pointing at elem.

returns this Form object, for chaining.

msg Type: String of HTML
A string containing the text of the error you want to show.

elem Type: jQuery Object
The element for the error to point to.  If unset, the form's submit button is used.