function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Salesforce Admin 110Salesforce Admin 110 

error with code only works on one transaction at a time

i have a problem , when testing this code by inserting more than 2 records via dataloader i get below error: i had only ever been testing by manually adding 1 contact at a time.......i understand i may have to move the DML outside of the loop but i am new to apex and not sure how to fix this

easycontacttrigger: execution of AfterInsert

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

Class.easycontacttriggerhelper.buyerconConveyancy2: line 139, column 1
Trigger.easycontacttrigger: line 28, column 1

here's a snippet of the class
public with sharing class easycontacttriggerhelper {
public static void buyerconConveyancy2(list<Contact> cons) {
system.debug('###list<Contact> cons ' +  cons);



list<Easy_Opportunity__c> opplist = new list <Easy_Opportunity__c>();

recordtype[] tt = [Select  r.Id, r.SobjectType, r.Name From RecordType r where sobjecttype ='Easy_Opportunity__c' and Name = 'Residential Sales'];

for(Contact con : cons){

system.debug('### con ' +  con);

if( con.Stage__c == 'Lead' && con.contacttype__c != null && con.contacttype__C.contains('Buyer')){

Easy_Opportunity__c newopp = new Easy_Opportunity__c ();



            
            newopp.ownerid = con.Allocated_Negotiator__c;
            newopp.name = 'Applicant Conveyancy Opportunity'; 
            newopp.account_name__c = con.accountid;
            newopp.CurrencyIsoCode = con.currencyisocode;
            newopp.stage__c = 'New';
            newopp.recordtypeid = tt[0].Id;
            newopp.Contact_Name__c = con.id;
            newopp.Close_Date__c = Date.today().addDays(2);
            
            
            

            opplist.add(newopp);

   insert opplist; 
system.debug('### opplist ' +  opplist);
List<Product__c> Pd = (List<Product__c>) System.Json.deserialize('[{"attributes":{"type":"Product__c"},"Name":"Conveyancing","Sale_Price__c":"111.00"}]', List<Product__c>.class);
    for (Product__c eachProd : Pd)
 eachProd.Easy_Opportunity__c = opplist[0].id;
    
insert Pd;
 system.debug('### pd ' +  pd);
 


}
}
}
}

 
pconpcon
To start off with, this code is not bulk ready.  This error is happening because you add it the list, insert the list, then add a new one to the list.  So then when you try to insert that list again you already have one that has been inserted.  The code below should do what you want.
 
public with sharing class easycontacttriggerhelper {
    public static void buyerconConveyancy2(list<Contact> cons) {
        List<Easy_Opportunity__c> opplist = new list <Easy_Opportunity__c>();

        List<recordtype> tt = [
            select SobjectType,
                Name
            from RecordType
            where sobjecttype = 'Easy_Opportunity__c' and
            Name = 'Residential Sales'
        ];

        for (Contact con : cons) {
            if (
                con.Stage__c == 'Lead' &&
                con.contacttype__c != null &&
                con.contacttype__C.contains('Buyer')
            ){
                oppList.add(new Easy_Opportunity__c (
                    ownerid = con.Allocated_Negotiator__c,
                    name = 'Applicant Conveyancy Opportunity',
                    account_name__c = con.accountid,
                    CurrencyIsoCode = con.currencyisocode,
                    stage__c = 'New',
                    recordtypeid = tt[0].Id,
                    Contact_Name__c = con.id,
                    Close_Date__c = Date.today().addDays(2)
                ));
                opplist.add(newopp);
            }
        }

        insert opplist;

        List<Product__c> prodList = (List<Product__c>) System.Json.deserialize('[{"attributes":{"type":"Product__c"},"Name":"Conveyancing","Sale_Price__c":"111.00"}]', List<Pro
duct__c>.class);
        for (Product__c prod : prodList) {
            // Not sure what you're trying to accomplish here
            eachProd.Easy_Opportunity__c = opplist[0].id;
        }

        insert prodList;
    }
}
NOTE: This code has not been tested and may contain typographical or logical errors
Salesforce Admin 110Salesforce Admin 110
thanks for your answer, this seems ok but at my first attempt to save it in sandbox the code under "insert opplist;" gave an error
pconpcon
what error does it give you?  What line in the code above?
Salesforce Admin 110Salesforce Admin 110
product__c is detail of easy_opportunity__c master further help to achieve this will help alot.........
Salesforce Admin 110Salesforce Admin 110
unexpected token: list

List<Product__c> prodList = (List<Product__c>) System.Json.deserialize('[{"attributes":{"type":"Product__c"},"Name":"Conveyancing","Sale_Price__c":"111.00"}]', List<Pro
duct__c>.class);
pconpcon
the error is because the copy paste failed.  line 35 and 36 should be comined
Salesforce Admin 110Salesforce Admin 110

yes i see that but it pasted ok into one line.........is this error because its a master-detail relationship?