[SalesForce] Upsert query with only one record to insert/update

Is it possible to upsert only a single object? And return the ID of the inserted/updated record?

I have an Custom Contact Object which i want to insert into the standard Object from Salesforce. The custom contact object is:

global class CContact 
{
    public String changed {get; set;}
    public String contactId {get; set;}
    public String customerNumber {get; set;}
    public String email {get; set;}
    public String firstName  {get; set;}
    public String lastName {get; set;}
    public String phoneCountryCode {get; set;}
    public String phoneNumber {get; set;}
    public String pointBalance {get; set;}
    public String contactUrl {get; set;}
}

What am i doing wrong below?
My upsert logic:

Contact[] cts;
string searchQuery = 'SELECT id, firstName FROM contact WHERE Membership_number__c = 123456789';
cts = Database.query(searchQuery);
System.debug('Cts length: ' + cts.size()); (Returns 1)
cts[0] = new Contact(phone = '555', email = ''); //Just hardcoding a new value here!
Schema.SObjectField f = Contact.Fields.Membership_number__c;
Database.UpsertResult [] cr = Database.upsert(cts, f, false);
cr[0].getId(); //This returns the ID of inserted/updated record ((Returns null now)

My upsert logic 2:

Contact cts;
string searchQuery = 'SELECT id, firstName FROM contact WHERE Membership_number__c = 123456789 LIMIT 1';
try
{
    cts = Database.query(searchQuery);
}
catch (Exception e)
{

}
cts = new Contact(phone = '555', email = '', Membership_number__c = customerNumber);
Schema.SObjectField f = Contact.Fields.Membership_number__c;
Database.UpsertResult cr = Database.upsert(cts, f, false);
system.debug('is success: ' + cr.isSuccess()); //Returns false
system.debug('Id is: ' + cr.getId()); //This returns the ID of inserted/updated record

Best Answer

Try Database.UpsertResult cr = Database.upsert(cts[0], f, false); since you're only inserting one record instead of an array.

Or recode to something like the following:

Contact cts;
string searchQuery = 'SELECT id, firstName FROM contact WHERE Membership_number__c = 123456789 limit 1';
cts = Database.query(searchQuery);
System.debug('Cts contains data: ' + cts.isEmpty()); (Returns False)
cts = new Contact(phone = '555', email = ''); //Just hardcoding a new value here!
Schema.SObjectField f = Contact.Fields.Membership_number__c;
Database.UpsertResult cr = Database.upsert(cts, f, false);  
cr.getId(); 

Also, following your query, you should already have the Id which is cts.Id

Related Topic