+ Start a Discussion
neckrneckr 

Logic to handle Multiple Record Insert Scenerio in Trigger?

Hi,


My objective is to add 3 Trade_Reference_Reports__c Object records for every unique Category__c field in Con_Service_Task_Request__c Object. In other words add 3 Trade References for every Service Task Requested within a Category that  does not already have 3 trade references.


My trigger runs fine when I add 1 Con_Service_Task_Request__c record at a time for a category that does not yet have any trade references, however when I add more than 1 Con_Service_Task_Request__c from the same category that does not yet have Trade References, its creates 3 trade references for each record under that category instead of the intended 1.


I am a bit stuck on how do handle this scenerio and was hoping someone can suggest some ideas?


I copied my Trigger code and method that allows my to process multiple records at once.



trigger ConVerificationRecordSetup on Con_Service_Task_Request__c (after insert, after update) 
{

if (FireTrigger.getRun()) {


Con_Service_Task_Request__c[] STS = Trigger.new.deepClone();


Map<ID, List<Trade_Reference_Report__c>> mapExistingTRVs = new Map<ID, List<Trade_Reference_Report__c>>();
Set<String> uniqueCategories = new Set<String>();
Map<ID, Con_Service_Task_Request__c> mapST = new Map<ID, Con_Service_Task_Request__c>();



List <Trade_Reference_Report__c> listTRV1 = new List<Trade_Reference_Report__c>();
List <Contact> listTRVCompanyContact1 = new List<Contact>();

List <Trade_Reference_Report__c> listTRV2 = new List<Trade_Reference_Report__c>();
List <Contact> listTRVCompanyContact2 = new List<Contact>();

List <Trade_Reference_Report__c> listTRV3 = new List<Trade_Reference_Report__c>();
List <Contact> listTRVCompanyContact3 = new List<Contact>();


for(Con_Service_Task_Request__c ST : STS){
        
         accID.add(ST.Account__c);
         mapST_Account.put(ST.id , ST.Account__c);
         
         Contact Principalcontact=[SELECT ID FROM Contact WHERE AccountId = : ST.Account__c AND Contact_Type__c = 'Acct Principal Contact' limit 1];
         mapPrincipalAcctCont.put(ST.id, Principalcontact.ID); 
         
         List<Trade_Reference_Report__c> ExistingTRVs = [SELECT ID, TRV_Work_Category__c FROM Trade_Reference_Report__c 
         WHERE Account__c = : ST.Account__c AND TRV_Work_Category__c = : ST.Category__c];
             
	 if(ExistingTRVs == NULL)  {
                ExistingTRVs = New List<Trade_Reference_Report__c>();
                }
             
         mapExistingTRVs.put(ST.id, ExistingTRVs); 
         
         mapST.put(ST.id, ST);
         
         for(Trade_Reference_Report__c WC : ExistingTRVs){
         uniqueCategories.add(WC.TRV_Work_Category__c);
        }
    }
    


for (Con_Service_Task_Request__c ST : Trigger.new) {



//CHECK TO SEE IF TRADE REFERENCE FOR PARTICULAR CATEGORY EXISTS, IF SO ASSIGN ID'S TO ST, //IF NOT CREATE 3 NEW TRV RECORDS - WHEN ADDING MULTIPLE Con_Service_Task_Request__c //RECORDS AT THE SAME TIME, IT CREATES 3 TRV RECORDS FOR ALL Con_Service_Task_Request__c RECORDS
// INSTEAD OF JUST THE FIRST ONE. UNSURE OF EASIEST WAY TO HANDLE THIS SCENERIO.

if ((uniqueCategories.Contains(ST.Category__c))&&(mapExistingTRVs.get(ST.id).size() > 0) && !(ST.Service__r.Trade_Reference_Reports__c ))
{

mapST.get(ST.id).Trade_Reference_Report_1__c = mapExistingTRVs.get(ST.id).get(0).ID;

mapST.get(ST.id).Trade_Reference_Report_2__c = mapExistingTRVs.get(ST.id).get(1).ID;

mapST.get(ST.id).Trade_Reference_Report_3__c = mapExistingTRVs.get(ST.id).get(2).ID;

}

if ((!uniqueCategories.Contains(ST.Category__c)) && !(ST.Service__r.Trade_Reference_Reports__c ))
{ 
{ 
 Contact TRVCompanyContact1 = new Contact(AccountId = ST.Account__c , Contact_Type__c = 'TRV Company', LastName = 'Enter Last Name 1');
 listTRVCompanyContact1.add(TRVCompanyContact1);
 
 Contact TRVCompanyContact2 = new Contact(AccountId = ST.Account__c , Contact_Type__c = 'TRV Company', LastName = 'Enter Last Name 2');
 listTRVCompanyContact2.add(TRVCompanyContact2);

Contact TRVCompanyContact3 = new Contact(AccountId = ST.Account__c , Contact_Type__c = 'TRV Company', LastName = 'Enter Last Name 3');
 listTRVCompanyContact3.add(TRVCompanyContact3);
       
}

}

insert listTRVCompanyContact1;
insert listTRVCompanyContact2;
insert listTRVCompanyContact3;


for (Integer i=0; i<Trigger.new.size(); i++) { 


if(listTRVCompanyContact1.size()> 0){ 
Trade_Reference_Report__c TRV1 = new Trade_Reference_Report__c(Account__c = STS[i].Account__c , TRV_Company_Contact__c = listTRVCompanyContact1[i].ID, TRV_Principal_Contact__c = mapPrincipalAcctCont.get(STS[i].id), TRV_Work_Category__c = STS[i].Category__c, TRV_Number__c = 1 );    
listTRV1.add(TRV1);
}

if(listTRVCompanyContact2.size()> 0){ 
Trade_Reference_Report__c TRV2 = new Trade_Reference_Report__c(Account__c = STS[i].Account__c , TRV_Company_Contact__c = listTRVCompanyContact2[i].ID, TRV_Principal_Contact__c = mapPrincipalAcctCont.get(STS[i].id), TRV_Work_Category__c = STS[i].Category__c, TRV_Number__c = 2 );    
listTRV2.add(TRV2);
}

if(listTRVCompanyContact3.size()> 0){ 
Trade_Reference_Report__c TRV3 = new Trade_Reference_Report__c(Account__c = STS[i].Account__c , TRV_Company_Contact__c = listTRVCompanyContact3[i].ID, TRV_Principal_Contact__c = mapPrincipalAcctCont.get(STS[i].id), TRV_Work_Category__c = STS[i].Category__c, TRV_Number__c = 3 );    
listTRV3.add(TRV3);
}

} 



insert listTRV1;
insert listTRV2;
insert listTRV3;


for (Integer i=0; i<STS.size(); i++) { 

Con_Service_Task_Request__c ST = STS[i];

if(listTRV1.size()> 0){ 

ST.Trade_Reference_Report_1__c = listTRV1[i].id;

}

if(listTRV2.size()> 0){ 

ST.Trade_Reference_Report_2__c = listTRV2[i].id;

}


if(listTRV3.size()> 0){ 

ST.Trade_Reference_Report_3__c = listTRV3[i].id;

}


update mapST.values();

}



}




public PageReference processSelected() {

    List<Service_Categories__c> selectedServiceTasks = new List<Service_Categories__c>();
    
    for(aServiceTask aST : getServiceTasks() ) {
        if(aST.selected == true) {
        selectedServiceTasks.add(aST.ST);
        }
     }
     System.debug('These are the selected Service Tasks...');
     List<Con_Service_Task_Request__c >Strs = new List<Con_Service_Task_Request__c >();
     for(Service_Categories__c ST : selectedServiceTasks) {
           
     servicecode = ST.Service_Name__c + ' - ' + countrycode + ' - ' + provincestatecode + ' - ' + city;
     
     Product2 service = [SELECT id FROM Product2 WHERE ProductCode = : servicecode limit 1]; 
     
     Con_Service_Task_Request__c newSTR = new Con_Service_Task_Request__c(Account__c = acctID, Service__c = service.id, Service_Code__c = servicecode, Service_Name__c = ST.Service_Name__c, Service_Area__c = servicearea, Country__c = country, 
     Province_State__c = provincestate, City__c = city,  Postal_Zip_Code__c = postalzip, Category__c = category,  Service_Task_Request_Status__c = 'Not Verified'); //Service__c = serviceid, 
     
     Strs.add(newSTR);
      system.debug(ST);
      
     }
     try {
     upsert Strs;
     } 
     catch (DmlException e) {
        
        
     }
     return null;
     }





Best Answer chosen by Admin (Salesforce Developers) 
Shashikant SharmaShashikant Sharma

 

Try this
Add a Integer i = 0; before first loop
your code will be like this
Integer j = 0;

for(Con_Service_Task_Request__c ST : STS){

 

Remove this second loop
for (Integer i=0; i<Trigger.new.size(); i++) { 

 

Use this interger j in index instead i where you instantiate TRV records like this 

 

 

if(listTRVCompanyContact1.size()> 0){ 
Trade_Reference_Report__c TRV1 = new Trade_Reference_Report__c(Account__c = STS[j].Account__c , TRV_Company_Contact__c = listTRVCompanyContact1[j].ID, TRV_Principal_Contact__c = mapPrincipalAcctCont.get(STS[j].id), TRV_Work_Category__c = STS[j].Category__c, TRV_Number__c = 1 );    
listTRV1.add(TRV1);
}

if(listTRVCompanyContact2.size()> 0){ 
Trade_Reference_Report__c TRV2 = new Trade_Reference_Report__c(Account__c = STS[j].Account__c , TRV_Company_Contact__c = listTRVCompanyContact2[j].ID, TRV_Principal_Contact__c = mapPrincipalAcctCont.get(STS[j].id), TRV_Work_Category__c = STS[j].Category__c, TRV_Number__c = 2 );    
listTRV2.add(TRV2);
}

if(listTRVCompanyContact3.size()> 0){ 
Trade_Reference_Report__c TRV3 = new Trade_Reference_Report__c(Account__c = STS[j].Account__c , TRV_Company_Contact__c = listTRVCompanyContact3[j].ID, TRV_Principal_Contact__c = mapPrincipalAcctCont.get(STS[j].id), TRV_Work_Category__c = STS[j].Category__c, TRV_Number__c = 3 );    
listTRV3.add(TRV3);
}

 

 

after you insert TRV records using increase index

 

insert listTRV1;
insert listTRV2;
insert listTRV3;
j = j + 1;

 These changes will surely fix your issue

 

 

 

 

 

 

 

 

All Answers

Shashikant SharmaShashikant Sharma

I would suggest you to change some code in your trigger,

 

1) Use single dml for inserting all contacts , however you can have 3 lists to calculate the logic that  you want.

 

2)Your question is why 3 same TRV records created : Please check you are not coming in the trigger again as you are updating same records 

 

 

mapST.values();

 

 

neckrneckr

1) What syntax do I use to call all three contacts in one DML statement? I am assuming you are referring to these below?

 

insert listTRVCompanyContact1;
insert listTRVCompanyContact2;
insert listTRVCompanyContact3;

 

2) I took update mapST.values(); outside of the loop, and same results.  Any thing else you see that may be casuing this?

Shashikant SharmaShashikant Sharma

For the list do one thing

Create a one more list

List<Contact> listOfAllTRVCompanyContact = new List<Contact>();

listOfAllTRVCompanyContact.addAll(listTRVCompanyContact1);

listOfAllTRVCompanyContact.addAll(listTRVCompanyContact2);

listOfAllTRVCompanyContact.addAll(listTRVCompanyContact3);

 

if(listOfAllTRVCompanyContact.size) > 0)

insert listOfAllTRVCompanyContact;

 

For the map my idea is that as you are updating record which is invoking the trigger please check you do not come in the trigger again.

neckrneckr

I do not think I am retriggering because it only happens in the case of multiple inserts at same time and not single insert.

 

I also have this if statement encompassing my entire trigger code if (FireTrigger.getRun()) {  that calls the following class

 

public Class FireTrigger{
    private static boolean runTrigger = true;
    public static boolean getRun(){
         if(runTrigger ){
       runTrigger =false;
       return true;
       }
      else{
          return runTrigger;
       }
    }
}

 

 

Shashikant SharmaShashikant Sharma

Please test your trigger and answer these

are you getting as many TRV records as many items you work on? Like if you run trigger for 3 then theree records and if you run triggers on 4 records then 4 TRV

 

Or 

In all cases three records when ever more than one?

 

One more thing check id's of TRV records in all items are they same or different?

neckrneckr

Scenerio 1:  No records exist

 

Step 1) When I insert 1 new record for a particular category I get 3 TRV records all with unique ID's as desired.

 

If I insert 1 or more in that same category after step 1) I get no additional TRV records as desired.

 

Scenerio 2: No records exist

 

Step 1) When I insert 2 or more records for a particular category I get 3 TRVs times the number of records inserted in that category.  For example 2 new reocrds will give me 6 TRV records with all unqiue id's.

 

If I insert 1 or more in that same category after step 1) I get no additional TRV records as desired.

 

Problem only exist in step 1 of Scenerio 2, which is multiple added records for category that has not been added as of yet.

 

 

Shashikant SharmaShashikant Sharma

 

Try this
Add a Integer i = 0; before first loop
your code will be like this
Integer j = 0;

for(Con_Service_Task_Request__c ST : STS){

 

Remove this second loop
for (Integer i=0; i<Trigger.new.size(); i++) { 

 

Use this interger j in index instead i where you instantiate TRV records like this 

 

 

if(listTRVCompanyContact1.size()> 0){ 
Trade_Reference_Report__c TRV1 = new Trade_Reference_Report__c(Account__c = STS[j].Account__c , TRV_Company_Contact__c = listTRVCompanyContact1[j].ID, TRV_Principal_Contact__c = mapPrincipalAcctCont.get(STS[j].id), TRV_Work_Category__c = STS[j].Category__c, TRV_Number__c = 1 );    
listTRV1.add(TRV1);
}

if(listTRVCompanyContact2.size()> 0){ 
Trade_Reference_Report__c TRV2 = new Trade_Reference_Report__c(Account__c = STS[j].Account__c , TRV_Company_Contact__c = listTRVCompanyContact2[j].ID, TRV_Principal_Contact__c = mapPrincipalAcctCont.get(STS[j].id), TRV_Work_Category__c = STS[j].Category__c, TRV_Number__c = 2 );    
listTRV2.add(TRV2);
}

if(listTRVCompanyContact3.size()> 0){ 
Trade_Reference_Report__c TRV3 = new Trade_Reference_Report__c(Account__c = STS[j].Account__c , TRV_Company_Contact__c = listTRVCompanyContact3[j].ID, TRV_Principal_Contact__c = mapPrincipalAcctCont.get(STS[j].id), TRV_Work_Category__c = STS[j].Category__c, TRV_Number__c = 3 );    
listTRV3.add(TRV3);
}

 

 

after you insert TRV records using increase index

 

insert listTRV1;
insert listTRV2;
insert listTRV3;
j = j + 1;

 These changes will surely fix your issue

 

 

 

 

 

 

 

 

This was selected as the best answer
neckrneckr

Thank you very much

Shashikant SharmaShashikant Sharma

Your welcome neckr, It is my pleasure to solve your issues as they are most tricky  and always gives me a chance to learn something. Below is my blog , I have written a lot there for writting trigges and how to save limits in trigger while handling with bulk data. My next post is on Dynamic binding, Please check that out tommorow if you have time.

 

http://forceschool.blogspot.com/