• No results found

Process the results in the SaveResult[] object to verify whether the objects have been successfully updated

In document apex api (Page 164-170)

See Also:

5. Process the results in the SaveResult[] object to verify whether the objects have been successfully updated

Sample Code—Java

public void updateAccountSample() {

// Create an array of SObjects to send to the update method Account[] updates = new Account[2];

// This account could also be from the results of a retrieve or query call Account updateAccount = new Account();

updateAccount.setId("001x0000002kuk2AAA");

updateAccount.setShippingPostalCode("94105");

updates[0] = updateAccount;

Account updateAccount2 = new Account();

updateAccount2.setId("001x0000002kuk1AAA");

updateAccount2.setWebsite("www.website.com");

updates[1] = updateAccount2;

// Invoke the update call and save the results try {

SaveResult[] saveResults = binding.update(updates);

}

catch (Exception ex) {

System.out.println("An unexpected error has occurred." + ex.getMessage());

getUserInput ("\nUpdate failed. Press return to continue...");

return;

}

getUserInput ("\nUpdate done. Press return to continue...");

}

Sample Code—C#

private void update() {

//You would typically retrieve an SObject, modify its properties, // and then send the objects up in an array. For this sample, // we create a new contact object to update by setting // the id to a valid contact id

Contact contact = new Contact();

contact.Id = ""; // This should be a valid ID contact.MailingCity = "new city";

contact.MailingPostalCode = "98776";

// Invoke the update call, saving the results in SaveResult SaveResult[] sr = binding.update(new sObject[]{contact});

//The SaveResult should never be empty for (int i=0;i<sr.Length;i++)

{

// Determine whether the row update succeeded if (sr[i].success)

{

// Get the ID of the updated row

update

System.Diagnostics.Trace.WriteLine(sr[i].id);

} else {

// Iterate through the errors Error[] errors = sr[i].errors;

for (int j=0;j<errors.Length;j++) {

System.Diagnostics.Trace.WriteLine(errors[j].message);

} } } } Arguments

Description Type

Name

Array of one or more objects (maximum of 200) to update.

sObject[]

sObjects

Response SaveResult[]

Faults

InvalidSObjectFault UnexpectedErrorFault

See Also:

Understanding API Calls

http://www.sforce.com/us/resources/soap/sforce60/sforce_API_messages_update.html

SaveResult

The update call returns an array of SaveResult objects. Each element in the SaveResult array corresponds to the sObject[]

array passed as the sObjects parameter in the update call. For example, the object returned in the first index in the SaveResult array matches the object specified in the first index of the sObject[] array.

A SaveResult object has the following properties:

Description Type

Name

ID of an sObject that you successfully updated. If this field contains a value, then the object was updated successfully. If this field is empty, then the object was not updated and the Apex Web service returned error information instead.

ID id

Indicates whether the update call succeeded (true) or not (false) for this object.

boolean success

If an error occurred during the update call, an array of one or more Error objects providing the error code and description.

Error[]

errors

update

upsert

Creates new objects and updates existing objects; uses a custom field to determine the presence of existing objects. In most cases, we recommend that you use upsert instead of create to avoid creating unwanted duplicate records (idempotent). Available in the API version 7.0 and later.

Syntax

UpsertResult[] = sfdc.upsert(String externalIdFieldName, sObject[] sObjects);

Usage

Upsert is a merging of the words insert and update. The upsert call is available for objects that can be updated by the update call and the object has an external ID field.

The upsert call uses an indexed custom field called an external ID to determine whether to create a new object or update an existing object. (For more information about custom fields designated as external ID fields, see Required Fields. For more information about adding custom fields to objects, see the “Adding Fields” topic in the Salesforce online help.)

Using this call can dramatically reduce how many calls you need to make, particularly when:

• You are integrating your organization’s Salesforce data with ERP (enterprise resource planning) systems such as accounting and manufacturing.

• You are importing data and want to prevent the creation of duplicate objects.

If you are upserting an object that has a custom field with both the External ID and Unique attributes selected (a unique index), you do not need any special permissions, because the Unique attribute prevents the creation of duplicates. If you are upserting an object that has the External ID attribute selected but not the Unique attribute selected, (a non-unique index) your client application must have the permission “View All Data” to execute this call. Having this permission prevents the client application from usingupsert to insert an accidental duplicate record because it couldn’t see that the record existed.

Note: Matching by external ID is case-insensitive only if the external ID field has the Unique attribute and the Treat

"ABC" and "abc" as duplicate values (case insensitive)) option selected. These options are selected in the Salesforce user interface during field creation. If this is the case, “ABC123” is matched with “abc123.” Before performing an operation, review your external IDs for any values that would be matched if case was not considered, if you have external ID fields without the case-insensitive option selected. If such values exist, you may want to modify them to make them unique, or select the case-sensitive option for your external ID fields. For more information about field attributes, see

"Custom Field Attributes in the Salesforce online help.

How Upsert Chooses to update or create

Upsert uses the external ID to determine whether it should create a new object or update an existing one:

• If the external ID is not matched, then a new object is created.

• If the external ID is matched once, then the existing object is updated.

• If the external ID is matched multiple times, then an error is reported.

• When batch updating multiple objects where the external ID is the same for two or more objects in your batch call, those records will be marked as errors in the UpsertResult. The objects will be neither created or updated.

Sample Code—Java

The following sample is for an upsert specifying the Salesforce object ID.

public void upsertAccountSample() {

// Create an array of SObjects to send to the upsert method

upsert

SObject[] upserts = new Account[2];

// This account is assumed to be existing.

// Could be from the results of a retrieve or query call.

Account upsertAccount = new Account();

upsertAccount.setWebsite("http://www.website.com");

// A custom field "External_Id" is used for "External ID" on Upsert upsertAccount.setExternal_Id__c("1111111111");

upserts[0] = upsertAccount;

// This account is meant to be new Account upsertAccount2 = new Account();

upsertAccount2 = new Account();

upsertAccount2.setName("My Company, Inc");

upsertAccount2.setExternal_Id__c("2222222222");

upserts[1] = upsertAccount2;

try {

// Invoke the upsert call and save the results.

// Use External_Id custom field for matching records

UpsertResult[] upsertResults = binding.upsert("External_Id__c", upserts);

for (UpsertResult result : upsertResults) { if (result.isSuccess()) {

System.out.println("\nUpsert succeeded.");

System.out.println((result.isCreated() ? "Insert" : "Update") + " was performed.");

System.out.println("The Account id: " + result.getIds(0).toString());

} else {

System.out.println("The Upsert failed because: " + result.getErrors(0).getMessage());

} }

} catch (RemoteException ex) {

System.out.println("An unexpected error has occurred." + ex.getMessage());

}

getUserInput("\nPress the RETURN key to continue...");

}

Sample Code—C#

The following sample is for an upsert specifying the Salesforce object ID (not the foreign key).

private void upsertSample() {

if (!loggedIn) {

if (!login())return;

}

//First, create a contact using the upsert call. The contact must have a custom //field that is designated as an external id. In this case it's called ExternalId__c sforce.Contact[] contact = new Contact[1];

contact[0] = new sforce.Contact();

contact[0].LastName = "External_Id";

contact[0].FirstName = "Test";

contact[0].ExternalId__c = "01010101";

sforce.UpsertResult ur = binding.upsert("ExternalId__c", contact)[0];

if (ur.success)

{ //Check out the created flag

Console.WriteLine("Value of created flag is: " + ur.created);

} else

{ //Report an error

Console.WriteLine("Error: \n" + ur.errors[0].message);

return;

}

upsert

contact[0].FirstName = "Joe";

contact[0].LastName = "Sampson";

ur = binding.upsert("ExternalId__c", contact)[0];

if (ur.success)

{ //Check out the create flag, should be false now

Console.WriteLine("Value of created flag is: " + ur.created);

} else

{ //Report an error

Console.WriteLine("Error: \n" + ur.errors[0].message);

return;

} }

upsert and Foreign Keys

You can use external ID fields as a foreign key, allowing you to access records in a single step instead of querying a record to get the ID first. To do this, specify the foreign key name and the external ID field value. For example:

Opportunity upsertOpportunity = new Opportunity();

upsertOpportunity.setStageName("Prospecting");

// Standard object ref

Account upsertParentAccountRef = new Account();

upsertParentAccountRef.setExternal_SAP1_ACCTID__c("SAP111111");

upsertOpportunity.setAccount(upsertParentAccount);

// Opportunity ref

upsertOpportunity.set_SAP1_OPPID__c("SAP222222");

UpsertResult[] upsertResults = binding.upsert("SAP1_OPPID__c", new SObject[] {upsertOpportunity});

Arguments

Description Type

Name

Contains the name of the field on this object with the external ID field attribute.

For more information, see Required Fields. Note that you can also use the field name "ID" to use the unique Salesforce ID instead of an external ID.

string ExternalIDFieldName

Array of one or more objects (maximum of 200) to create or update.

sObject[]

sObjects

Response UpsertResult[]

Faults

InvalidSObjectFault

upsert

UnexpectedErrorFault

See Also:

create update

Understanding API Calls

UpsertResult

The upsert call returns an array of UpsertResult objects. Each element in the array corresponds to the sObject[] array passed as the sObjects parameter in the upsert call. For example, the object returned in the first index in the UpsertResult array matches the object specified in the first index of the sObject[] array.

An UpsertResult object has the following properties:

Description Type

Name

If the call succeeded, the field contains the ID of the record that was either updated or created. If there was an error, the field is null. For more information, see ID Field Type.

ID id

Indicates whether the record was created (true) or updated (false).

boolean isCreated

Indicates whether the call succeeded (true) or not (false) for this object.

boolean success

If errors occurred during the call, an array Error objects, providing the error code and description, is returned.

Error[]

errors

upsert

Chapter 9

In document apex api (Page 164-170)