[SalesForce] Dynamic field for Database.Upsert

I am trying to use a dynamic field for my Database.Upsert command as follows:

String extField = objVariable + fieldVariable;
Database.UpsertResult[] up = Database.upsert(toUpsert, extField);

This however returns the following error:

Method does not exist or incorrect signature: void upsert(List, String)

How can I resolve this?

Best Answer

The signature of Database.upsert() is

public static Database.UpsertResult[] upsert(sObject[] recordsToUpsert, Schema.SObjectField externalIdField, Boolean allOrNone)

While the Boolean parameter is optional, you must provide a value of type Schema.SObjectField for the second parameter.

You can obtain such values dynamically via the Describe API given string input:

String myFieldName = 'Account';
String myObjectName = 'Name';

Schema.SObjectField f = Schema.getGlobalDescribe().get(myObjectName).getDescribe().fields.getMap().get(myFieldName);
Related Topic