So the Apex docs say you have to set the value of the master record if you want to retain the discarded account field values before the merge operation.

Is there a better way to do validation for a merge DML Operation then having to write tons if statements for each field to validate if a field is null on a master record before setting it to the retained value of the discarded account?


public void mergeAccountFields(Account masterRecord, Account discardedAccount){

        if(masterRecord.FirstName __c == null){
                masterRecord.FirstName__c = discardedAccount.FirstName__c;

        if(masterRecord.LastName__c == null){
               masterRecord.LastName__c = discardedAccount.LastName__c;

          if(masterRecord.NumberOfLocations__c == null){
                 masterRecord.NumberOfLocations__c = discardedAccount.NumberOfLocations__c;

1 Answer 1


If you are just looking for a bit of code refactoring of this, creating a list of the fields you want to copy and then looping over the list and making use of methods like SObject.get and SObject.put is a bit cleaner:

private static final SObjectField[] FIELDS = new SObjectField[] {

public void mergeAccountFields(Account masterRecord, Account discardedAccount) {
    for (SObjectField f : FIELDS) {
        if (masterRecord.get(f) == null) {
            masterRecord.put(f, discardedAccount.get(f));
  • This would be a great place to use a FieldSet also to make this process even more dynamic.
    – drakored
    Dec 24, 2014 at 16:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .