+ Start a Discussion
willardwillard 

Merge SObjects with the same Id, but different fields populated

Is there an easy way to merge two SObjects?  Right now I have one method that spits out some opportunities with certain values filled in, i.e., CloseDate, Stage, etc..  I have another method that spits out some opportunities with other values filled in, ie. Amount, UpgradeAmount, etc.

 

Is there an easy way to combine these two SObjects into one with the new SObject having all the fields populated?

 

Something like a copyFieldsTo method:

Id oppId = '<someid>';
Opportunity opp1 = new Opportunity(Id = oppId, closedate = today, ...);
Opportunity opp2 = new Opportunity(Id = oppId, amount = 100, ...);
opp1.copyFieldsTo(opp2);

// opp2 will now have amount AND closedate populated

 

sfdcfoxsfdcfox

Out of the box, no, but you can do this:

 

SObject dest, source; // Choose one as the "master"
for(SObjectField field:dest.getSObjectType().getDescribe().fields.getMap().values())
  dest.put(field, dest.get(field)==null?source.get(field):dest.get(field));

 Edit: updated code.

willardwillard

Thanks for the start sfdcfox.

 

First, after some tweaking, I was able to get the merged sobject, but it was setting all the fields that weren't supposed to be set to null, which is definitely not good.  Here's the final solution in case anyone needs it:

for(SObjectField field:opp1.getSObjectType().getDescribe().fields.getMap().values()) {
    try {
        Object opp1Field = opp1.get(field);
        Object opp2Field = opp2.get(field);
        // Need this if statement b/c even though the exception occurs above, the "put" method was still being executed!
        if (opp2Field != null) {
  			opp1.put(field, opp1Field==null ? opp2Field : opp1Field);
        }
    }catch (SObjectException ex) {
        // don't do anything
    }
}