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;

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 '14 at 16:16

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.