+ Start a Discussion
splitsplit 

My second trigger

 this is first trigger

trigger chAccGenerate on Organization__c (after insert) {
      if (Trigger.isInsert){
      List<Chart_of_accounts__c> accounts = new Chart_of_accounts__c[0];
      List<SMain__c> smain = new SMain__c[0];
        for (Organization__c o : Trigger.new) {        
            if(o.Industry__c == 'Telecom')
             {accounts.add(new Chart_of_accounts__c (name = 'Sales of product income',Type__c = 'Income',Organization__c = o.ID));
            accounts.add(new Chart_of_accounts__c (name = 'Service/fee income',Type__c = 'Income',Organization__c = o.ID));
            insert accounts;
            }
            
}
}
}

 

 

 

trigger test on Chart_of_accounts__c (after insert) { if (Trigger.isInsert){ List<SMain__c> smain = new SMain__c[0]; for (Chart_of_accounts__c c : Trigger.new) { if(c.Type__c == 'Income') {smain.add(new SMain__c (Chart_of_accounts__c = c.ID)); insert smain; } } } }

 

 

 after create Organization__c record force say:

 

 Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger CloudBudget.chAccGenerate caused an unexpected exception, contact your administrator: CloudBudget.chAccGenerate: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CloudBudget.test: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0 with id a0AA0000000EdM1MAK; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Trigger.CloudBudget.test: line 7, column 13: []: Trigger.CloudBudget.chAccGenerate: line 9, column 13

 

 

???

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Rajesh ShahRajesh Shah

Currently you have the insert command inside the for loop. This will make the insert call for every record. After the first record gets inserted, salesforce generates the Id for it and the record is still in the list. Second time, when you make the insert call, it tries to insert the first record too and hence the error 'Cannot specify Id in the insert call'.

 

Soln: Move the insert call outside the for loop.

All Answers

Rajesh ShahRajesh Shah

Currently you have the insert command inside the for loop. This will make the insert call for every record. After the first record gets inserted, salesforce generates the Id for it and the record is still in the list. Second time, when you make the insert call, it tries to insert the first record too and hence the error 'Cannot specify Id in the insert call'.

 

Soln: Move the insert call outside the for loop.

This was selected as the best answer
splitsplit
Great thanks!