Use the Marketo Forms 2.0 API to populate fields

Occasionally we want to populate Marketo fields with values we calculate on our side. Perhaps advanced UTM handling, custom Salesforce fields, etc. The Marketo Forms 2.0 API makes this pretty easy. Most of what you need to know lives on this documentation page, but I will give you a couple tips you might not otherwise know.

You can populate UTM codes automatically...

...but think it through. You can have Marketo autopopulate your utm values from the query string in the URL, but what if a user navigates to another page? The utm code is lost. Marketo lets you pull the value from cookies instead, but the values you get might not be what you expect (depending on when the cookie gets set and when the Marketo forms code runs). For ultimate control, write some custom code that always gives you the utm codes you expect, and send those to your Marketo form using .setValues():

Fields DO need to exist on your form in order to be prepopulated... kind of.

There is a lot of confusion about how Marketo fields, hidden fields, and autopopulation work. Here is what you need to know:

  1. Form fields are arbitrary. If a field exists in Marketo, any form can submit a value to it (I think there are some exceptions here, but I don't know what they are and they aren't super important).
  2. A Marketo form doesn't need to have a form field designed into it in order to submit a value for that field.
  3. But, you must create that field in the form in order to prepopulate a value from your site

Here's an example. You have a field in Marketo, call it my_field. You create a "Contact Us" form, and you want to prepopulate that field with some value from your site. Do you need to add my_field to your Contact Us form? NO. The Marketo Forms 2.0 API .setValues() method has a hidden parameter they forgot to mention in the documentation: a callback called ifNotExistFn that executes when the field you try to set doesn't exist on the form you're trying to set it on. ifNotExistFn passes two parameters, name (the name of the field you're trying to set) and value (the value you're setting). So with a little haxx0ring, we can define a tiny anonymous function that calls addHiddenFields(), adding the (hidden) field to the form, and solving the problem:

So in sum, what this code does is try to set a field to a value, if the field exists. If the field doesn't exist, it creates the field as a hidden field, and populates it with the value.

Happy marketing!