Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Update Salesforce Objects with Server-Side JavaScript
<script type="text/javascript" runat="server">
Platform.Load("core", "1");
var debug = 1;
// detect form submission
if (Request.Method == "POST") {
// retrieve the input values from the form payload
var subscriberKey = Request.GetFormField("subscriberKey");
var email = Request.GetFormField("email");
var firstName = Request.GetFormField("firstName");
var lastName = Request.GetFormField("lastName");
// ensure the subscriberKey has a value
if (!isEmpty(subscriberKey)) {
try {
// update the SF object indicated by the subscriberKey
var updateSFResults = updateSF(subscriberKey,0,email,firstName,lastName);
if (debug) {
Write("<br>updateSFResults: " + updateSFResults);
}
} catch (e1) {
if (debug) {
Write("<br>e1: " + Stringify(e1));
}
} // of catch
} // of sk check
} // of post
function isEmpty(str) {
return (!str || 0 === str.length);
}
function updateSF(subscriberKey, HasOptedOutOfEmail, Email, FirstName, LastName) {
var results = 0;
var SFIDPattern = new RegExp("^[a-zA-Z0-9]{18}");
if (SFIDPattern.test(subscriberKey) == true) {
var fieldArr = [];
fieldArr.push('HasOptedOutOfEmail');
fieldArr.push(HasOptedOutOfEmail);
fieldArr.push('Email');
fieldArr.push(Email);
if (!isEmpty(FirstName)) {
fieldArr.push('FirstName');
fieldArr.push(FirstName);
}
if (!isEmpty(LastName)) {
fieldArr.push('LastName');
fieldArr.push(LastName);
}
// detect Contact or Lead
var sfObj = subscriberKey.substring(1,3) == "003" ? "Contact" : "Lead";
var updateSFObject = "";
updateSFObject += "\%\%[ ";
updateSFObject += "set @SFUpdateResults = UpdateSingleSalesforceObject('" + sfObj + "',";
updateSFObject += "'" + subscriberKey + "','"+ fieldArr.join("','") + "'";
updateSFObject += ") ";
updateSFObject += "output(concat(@SFUpdateResults)) ";
updateSFObject += "]\%\%";
try {
results = Platform.Function.TreatAsContent(updateSFObject);
} catch (e2) {
if (debug) {
Write("<br>e2: " + Stringify(e2));
}
}
}
return results
}
</script>
<!-- YOUR HTML AND FORM GOES HERE -->
@jdeblank

This comment has been minimized.

Copy link

jdeblank commented Jul 30, 2019

❤️ This is excellent. Jumping in to ampscript just for 1 function always makes me 😭

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.