+ Start a Discussion
Linda 98Linda 98 

INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

Please help me with solving this error.
My trigger fires each time is record is inserted.It works fine with small data.Every night i get lot of inserts I am getting this error:: System.DmlException: Insert failed. first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

below is my code
 
trigger Linktorecord on project__c (before insert,before update,after insert) {

    Map<String,product2> pMap=new Map<String,product2>();
    List<product2> p2List=new List<Product2>();
    List<Opportunity> oppList=New List<Opportunity>();
    List<Opportunity> oppList2=New List<Opportunity>();    
    oppList=[select id,name,accountid,serialnumber__c from opportunity where SerialNumber__c !=null];

    for(product2 pro  : [select id,productcode from product2]){
        pMap.put(pro.productcode,pro);
    }
   
  if(trigger.isinsert&&trigger.isbefore)
    for(Project__c I:trigger.new){

        if(i.Number__c != null && Pmap.Containskey(i.Number__c))
        {
            i.product__c=pMap.get(i.Number__c ).Id;
            break;
        } 
            
        else{
               
        Product2 newp =new Product2();
        if(i.number__c  !=null){        
        newp.Name=i.Number__c;
        }
        if(i.Number__c !=null){
        newp.ProductCode=i.Number__c;
        }
        p2List.add(newp);
        }
       
        insert p2List;
        if(p2List.size() >0){
        i.product__c=p2List[0].id; 
        }
       }
       
       if(trigger.isinsert && trigger.isafter){
       List<project__c> newproj =new List<project__c>();
       set<id> opids=new set<id>();
       newproj=trigger.new;
       Opplist2=[select id,SerialNumber__c,project__c from opportunity where Serialnumber__c =:newproj[0].Serialnumber__c];
       for(project__c I2:newproj){
         opids.add(i2.id);
       }
      if(!opids.isempty()){
      List<opportunity> oList =[select id,project__c from opportunity where Serialnumber__c =:newproj[0].Serialnumber__c];
       for(Opportunity ol:olist){
             
             ol.project__c =trigger.new[0].id;
       }      
      update olist;
      }       
    }
}

 
SijuSiju
 The issue is because ,you are trying to insert all the items you've already inserted So check the record in an If Condition  before Insert  , If  ID present already then do an Update  otherwise do Insert.
Sure@DreamSure@Dream
Hi Linda,

Replace insert with upsert. 

Mark this as the solution, if it solves your problem. 

Thanks
Linda 98Linda 98
Ok..My bad!!
Makes sense.Thanks.
I am also trying to bulkify my trigger.Could you please help me in that point.
I am trying to avoid [0] because this doesnt work when i do bulk insert.But not sure how i can avoid it.Could you please guide me.
Sunil AwareSunil Aware

For now this is temporary solution

Replace this else block
        else{
            Product2 newp =new Product2();
            if(i.number__c  !=null){       
            newp.Name=i.Number__c;
            }
            if(i.Number__c !=null){
            newp.ProductCode=i.Number__c;
            }
            p2List.add(newp);
            }
            insert p2List;
            if(p2List.size() >0){
            i.product__c=p2List[0].id;
            }
           }

with below code

else{
      if(i.number__c  !=null){
                Product2 newp =new Product2();
                newp.Name=i.Number__c;
                newp.ProductCode=i.Number__c;
                insert newp;
                i.product__c=newp.id;
      }
}


You need to do many changes to bulkify your Trigger, You have done some DML operations in loop as well some hard coded indexes.
Linda 98Linda 98
Ok..i changed my code.I decided not to insert newp.

I am trying to make this part as bulkified .Could you please help me in this.
if(trigger.isinsert && trigger.isafter){
       List<project__c> newproj =new List<project__c>();
       set<id> opids=new set<id>();
       newproj=trigger.new;
       Opplist2=[select id,SerialNumber__c,project__c from opportunity where Serialnumber__c    =:newproj[0].Serialnumber__c];
       for(project__c I2:newproj){
         opids.add(i2.id);
       }
          if(!opids.isempty()){
          List<opportunity> oList =[select id,project__c from opportunity where Serialnumber__c =:newproj[0].Serialnumber__c];
       for(Opportunity ol:olist){
             ol.project__c =trigger.new[0].id;
       }     
      update olist;
      }    
    }

 
Amit Chaudhary 8Amit Chaudhary 8
Please try below bulky code
if(trigger.isinsert && trigger.isafter)
	{
		Set<String> setSerNum = new Set<String>();
		For(project__c p : trigger.new)
		{
			if(p.Serialnumber__c != null)
			{
				setSerNum.add(p.Serialnumber__c);
			}
		}
		
		if( setSerNum.size() > 0 )
		{
			List<opportunity> lstOpp = [ select id,SerialNumber__c,project__c from opportunity where Serialnumber__c in :setSerNum ];
			Map<String,opportunity> mapSerlNumWiseOpp = new  Map<String,opportunity>();
			For(opportunity opp : lstOpp )
			{
				mapSerlNumWiseOpp.put(opp.SerialNumber__c , opp);
			}

			List<opportunity> lstOppToUpdate = new List<opportunity>();	
			For(project__c p : trigger.new)
			{
				if(p.Serialnumber__c != null && mapSerlNumWiseOpp.containsKey(p.Serialnumber__c) )
				{
					Opportunity opp = mapSerlNumWiseOpp.get(p.Serialnumber__c);
					opp.project__c = p.id ;
					lstOppToUpdate.add(opp);
				}
			}
			if(lstOppToUpdate.size() > 0 )
			{
				update lstOppToUpdate;
			}
		}
    }
1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers


4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail


Let us know if this will help you

 
Linda 98Linda 98
Ah!!!!
Thanks a lot Amit for the pointers.Really helps.
I would like to include or in soql.

I mean i would not only compare one serial number condition.
'if serial number or code number matches,then get the id of opportunity'

In that case how can i check rest of code?