UpdateSingleSalesforceObject with dynamic Field Value

ampscriptmarketing-cloud

My goal is to update all Salesforce CRM fields from a certain list with the same new value. My code runs on a Cloud Page which ist triggered by click on an email link:

SET @ContactId = AttributeValue("_subscriberkey")
SET @List = "AAA__c|BBB__c|CCC__c|DDD__c|EEE__c|FFF__c|GGG__c"
SET @Rowset = BuildRowsetFromString(@List,"|")
SET @Rowcount = rowcount(@Rowset)
 
FOR @i=1 TO @Rowcount DO
  SET @Rowname = row(@Rowset,@i)
  SET @Fieldname = field(@Rowname,1)
  SET @Fieldupdate = UpdateSingleSalesforceObject("Contact",@ContactId,@Fieldname,"NEW VALUE")
NEXT @i

Currently, I'm getting a 500 – Internal sever error message. It seems that the UpdateSingleSalesforceObject function generates the error as the value on position 3 (@Fieldname) is dynamic. When I try it with a static value like "AAA__c" the code works. Can anybody confirm that this generates the error? And do you know a way to avoid that?

Best Answer

To understand better what is wrong either run your AMPscript in the email or add a try-catch SSJS block on the CloudPage to get an error message. This way you will narrow down the problem.

UpdateSingleSalesforceObject AMPscript function can handle a variable in the 3rd parameter correctly, thus you get 500 error not because of that. Check whether the @ContactId value is actually existing in CRM, object and field names are correct, and all such stuff.

Once you would get rid of the 500 error, it still will not allow you to update the SFDC record within the loop because of the record-locking. Therefore, only the first field name from @List will be counted in.

To escape it, since @ContactId is static within the loop, you can execute the UpdateSingleSalesforceObject function once but dynamically populate its parameters based on the @Rowset you would build -

%%[
SET @ContactId = AttributeValue("_subscriberkey")
SET @List      = "AAA__c|BBB__c|CCC__c|DDD__c|EEE__c|FFF__c|GGG__c"
SET @Rowset    = BuildRowsetFromString(@List, "|")
SET @Rowcount  = RowCount(@Rowset)
 
FOR @i = 1 TO @Rowcount DO

  SET @Rowname   = Row(@Rowset, @i)
  SET @Fieldname = Field(@Rowname, 1)

  IF @i != @Rowcount THEN
     SET @FieldsToUpdate = Concat(@FieldsToUpdate, '"', @Fieldname, '", "NEW_VALUE", ')
  ELSE
     SET @FieldsToUpdate = Concat(@FieldsToUpdate, '"', @Fieldname, '", "NEW_VALUE"')
  ENDIF

NEXT @i

SET @DynamicFieldUpdate = TreatAsContent(Concat('%', '%[ SET @FieldUpdate = UpdateSingleSalesforceObject("Contact", "', @ContactId, '", ', @FieldsToUpdate, ')', ']%', '%'))
]%%

We need to use TreatAsContent and Concat to stitch everything together because otherwise UpdateSingleSalesforceObject will treat @FieldsToUpdate as 3rd parameter but not as pairs of fields and values.

Related Topic