Search code examples
javascriptformsmarketo

Marketo Hidden Field update


How should I update the value of a hidden field of Marketo?

What I have tried

form.setValues({"Results_PDF_URL__c":"assignedCampaignID"});

form.vals({"Results_PDF_URL__c":"assignedCampaignID"});

Both of the above options don't work.

So I checked the id, if I am using the right id, when I tried to get the id it retured blank (nothing) for hidden marketo fields.

While I can get the id for input text Marketo fileds (like FirstName, Comapany..) - I am not able to get the id of any hidden Marketo fields.

Any idea what I should set to get this to work?


Solution

  • Either of those, as long as they're used in the right scope, should work. The form object is not global.

    MktoForms2.whenReady( function (form) { 
        form.vals({"Results_PDF_URL__c":"assignedCampaignID"});
    });
    

    You'll first want to make sure the MktoForms2 API is available so you don't get an error.

    if( typeof MktoForms2 != "undefined" ) {
        MktoForms2.whenReady( function (form) { 
            form.vals({"Results_PDF_URL__c":"assignedCampaignID"});
        });
    }
    

    In Marketo, you can get the field names under Admin > Field Management > Export Field Names. (Requires Marketo admin access.) This will download a CSV of all the field names. You will want to use the field names shown in the REST API column.

    For a quick check, I usually just add the fields I want to a form and inspect them to get the correct field IDs.

    Also, you can use .addHiddenFields() instead of .vals() to ensure that the fields are a) on the form b) as hidden fields and c) have the correct values that you want to pass into Marketo. If the fields already exist, this function will detect the fields and only set the values. Very handy.

    if( typeof MktoForms2 != "undefined" ) {
        MktoForms2.whenReady( function (form) { 
            form.addHiddenFields({"Results_PDF_URL__c":"assignedCampaignID"});
        });
    }
    

    Finally, you may want to add a brief delay to ensure that the Marketo forms library has ample time to load and that the form will be available on the page when you look for it. It's unlikely that someone will submit the form in the first two seconds on the page, so it is probably okay to delay for two seconds before adding the field/value to the form.

    setTimeout( function(){
        if( typeof MktoForms2 != "undefined" ) {
            MktoForms2.whenReady( function (form) { 
                form.addHiddenFields({"Results_PDF_URL__c":"assignedCampaignID"});
            });
        }
    }, 2000 ); // two-second delay
    

    Resources:

    1. Marketo forms API Reference
    2. Marketo forms API Examples