1

I created a custom field on Account Create_contact__c which should be checked if any contact is inserted related to that account. I did write the following trigger to achieve this but ended up with writing SOQL queries and DML inside loop. Can someone suggest proper way to put these outside loop.

trigger trg3 on Contact (after insert) {
    if(trigger.isinsert){
        list<contact> con = trigger.new;
        for(contact c : con){
            list<Account> acc = [SELECT id from Account WHERE id =: c.AccountId];
            for(Account a : acc){
                a.Create_Contact__c = true;
                update a;
            }
        }
    }
}

Thanks

2 Answers 2

3
 trigger trg3 on Contact (after insert) {
    if(trigger.isinsert){
        list<Id> accIdList = new list<id>();
        for(contact c : trigger.new){
           accIdList.add(c.AccountId); 
        }

         list<Account> acc = [SELECT id,Create_Contact__c from Account WHERE id in: accIdList];
            for(Account a : acc){
                a.Create_Contact__c = true;
              }
         update acc;
    }
}
0
1

Try using the below code snippet :

trigger trg3 on Contact (after insert) {
    if(trigger.isinsert){
  set<Id> setofIds = new set<Id>();
        list<contact> con = trigger.new;
        for(contact c : con){
   setofIds.add(c.AccountId);
  }

        list<Account> acc = new list<Account>();
        for(Account a : [SELECT id, Create_Contact__c, (select id from contacts) from Account WHERE id IN : setofIds]){
    a.Create_Contact__c = true;
   acc.add(angel);
  }            
  update acc;
    }
}

Plz mark as best answer and let me know if this helps.

You must log in to answer this question.

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