1

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?

1

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);
3

You can use a literal field reference (SObjectField):

Sobject[] records = new Account[] { new Account(Name='Test',Industry='Technology',ExtId__c='12345')};
SObjectField field = Account.ExtId__c;
Database.upsert(records, field);

You can't use a normal String field, because it doesn't exist as an option.

  • Sorry maybe my question was worded wrong, I'm trying not to use hard coded object and field names. Where my Account and Name values are will be dynamically populated. – Deployment Failure Aug 15 '18 at 16:11
  • 1
    @DeploymentFailure Yes, it's possible to do so. There are ways to get SObject and SObjectField references using the appropriate Schema.getGlobalDescribe and Schema.SObjectType.getDescribe methods. – sfdcfox Aug 15 '18 at 16:12
  • Thats exactly what what I needed ^ – Deployment Failure Aug 15 '18 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.