Is is possible to concatenate the values of a field during the merging of records ?

Is is possible to concatenate the values of a field during the merging of records ?
For example : BuyerConnection field on Record A1 = ‘ca/phnx/nv’
Record A2 = ‘mo/oh/ny’

when these 2 records are merged I have to get the resultant field value on the winning record as ‘ca/phnx/nv/mo/oh/ny’

any ideas are greatly appreciated

Answer

You can perform custom logic while merging using an after-delete trigger. Because the records are locked during the merge, you should use an asynchronous call (@future) to update the records afterwards. You can query the deleted records with the ALL ROWS keyword of SOQL.

Here’s a demonstration:

Trigger:

trigger mergeAccount on Account (after delete) {
    AccountMerge.customMerge(Trigger.oldMap.keySet());
}

Class:

public class AccountMerge {
    @future
    public static void customMerge(Set<Id> accounts) {
        Map<Id, Account> oldAccounts = new Map<Id, Account>([SELECT Id, Name, Description, MasterRecordId FROM Account WHERE Id IN :accounts ALL ROWS]);
        Map<Id, Account> newAccounts = new Map<Id, Account>();
        for(Account record:oldAccounts.values()) {
            newAccounts.put(record.MasterRecordId, null);
        }
        newAccounts.remove(null);
        if(newAccounts.isEmpty()) {
            return;
        }
        newAccounts.putAll([SELECT Id, Description FROM Account WHERE Id IN :newAccounts.keySet() FOR UPDATE]);
        for(Id oldId: accounts) {
            Account oldAccount = oldAccounts.get(oldId), newAccount = newAccounts.get(oldAccount.MasterRecordId);
            if(String.isBlank(oldAccount.Description)) {
                continue;
            }
            if(String.isBlank(newAccount.Description)) {
                newAccount.Description = '';
            }
            newAccount.Description += '\n\nMerged from '+oldAccount.Name+':\n\n'+oldAccount.Description;
        }
        update newAccounts.values();
    }
}

Attribution
Source : Link , Question Author : user8332 , Answer Author : sfdcfox

Leave a Comment