AnuRaj
AnuRaj

Reputation: 27

Not creating all records

In apex-code i have wrote 2 triggers. I have 2 objects A and B. I need to create records of B object when A object is created. For eg: When 1 record of Object A is created then then create 4 records of object B. I have wrote 2 trigger 1 is for default some fields in B object when A object is created (this is before insert, before update) trigger and 2 trigger is to create record of object B when record of A is created(this is after insert, after update) trigger.

But when i create i record of Object A then 4 record id created. But when used Apex Data Loader to create records of object A at that time 2 records are created for A but for B object only 4 records are create. This is created for the second record of the A object.

i changed the code to

for(Object e : Trigger.new){

for(){ create 4 records for B object }}

I am getting this error when i did it

Insert failed. First exception on row 0 with id abcdef12345; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

Can any body help me to solve the problem. Thanks Anu

Upvotes: 0

Views: 1055

Answers (2)

twamley
twamley

Reputation: 801

Id isn't populated yet during a before insert trigger so you may be referencing it too early, maybe trying to point the B records back at the A records. Another problem would be trying to assign a value to B.Id. Both code problems are illustrated below:

trigger trigA on A__c (before insert) {
    List<B__c> listB = new List<B__c>();
    for (A__c a : trigger.new) {
        B__c b = new B__c();
        B__c.reference_to_A__c = a.Id; // <-- Wrong! a.Id isn't populated yet in before insert
        B__c.Id = '...'; // <-- Wrong! Salesforce generates the Id field for you
        listB.add(b);
    }
    insert listB;
}

It would be helpful to see more of your code.

Upvotes: 0

Rajesh
Rajesh

Reputation: 339

The error message is telling you that you cannot assign a value to the ID field. The ID field is protected and the value for it is auto-generated by Salesforce.com.

Remove ID field from your insert statement.

Upvotes: 0

Related Questions