I wrote the folloing re-parenting trigger to reparent Contacts with their parent Accounts, this is based on a unique identier (TFID). If I test each record one by one they all re-parent correctly, however, if I use Dataloader to load a large batch all of them get re-parented to the same parent Account (the parent of the last Contact record inserted).

trigger reParentContactsbyTFIDs on Contact (after insert) {

List<Contact> unParentedContacts = [SELECT id, recordTypeId FROM Contact WHERE recordTypeId = 'xxxxxxxxxxx' AND id = :Trigger.newMap.keySet()];

    set<String> TFIDs = new set<String>();
    for(Contact cont : [SELECT id, TFID__c 
                     FROM Contact 
                     WHERE id 
                     IN :unParentedContacts]){


    set<String> parentAccounts = new set<String>();
    for(Account pacct : [SELECT id 
                     FROM Account 
                     WHERE TFID__c IN :TFIDs]){


    for(Contact cont : unParentedContacts) {
        for(String pacct : parentAccounts){
            cont.accountId = pacct;

    update unParentedContacts;


I suggest you do this in a before insert trigger to avoid any need to do an update:

trigger reParentContactsbyTFIDs on Contact (before insert) {

    Id rtId = 'xxxxxxxxxxx';

    Set<String> tfids = new Set<String>();
    for (Contact c : Trigger.new) {
        if (c.RecordTypeId == rtId && c.TFID__c != null) tfids.add(c.TFID__c);

    Map<String, Id> m = new Map<String, Id>();
    for (Account a : [select TFID__c, Id from Account Where TFID__c in :tfids]) {
        m.put(a.TFID__c, a.Id);

    for (Contact c : Trigger.new) {
        if (c.RecordTypeId == rtId && c.TFID__c != null) c.AccountId = m.get(c.TFID__c);

The map in the middle section of this code ensures the right Account ID is assigned in the bulk case (assuming the TFID values are unique on Account.)

  • The Map collection worked perfectly. The before insert is much more effecient. Since its an insert, the TFID field will always be null. Smart Cookie. – All about the W Mar 31 '16 at 22:06

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.