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
veerna551.3942206611176638E12veerna551.3942206611176638E12 

INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Class.AccAndCons.save:

System.DmlException: Insert failed. First exception on row 0 with id 0019000000xjDWMAA2; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Class.AccAndCons.save: line 37, column 1 Class.AccAndCons_Test.AccAndCons_testMethod: line 22, column 1

apex code:
public with sharing class AccAndCons {
public account acc{get;set;}

    public AccAndCons(ApexPages.StandardController controller) {
    this.acc=(Account)controller.getRecord();
     index = new List<integer>();
          listCon  = new List<contact>();
          for(integer i=0;i<=1;i++){
           index.add(i);
          listCon.add(new Contact());

    }
    }


    public List<integer> index { get; set; }

    public List<contact> listCon { get; set; }
  
   public PageReference cancel1(){
 
   PageReference pg =new PageReference(' https://ap1.salesforce.com/001/o');

           pg.setredirect(true);

           return pg;

   }
 
 


    public PageReference save() {
    list<contact> cc=new list<contact>();
 
    acc.name=name;
    Database.SaveResult srList = Database.insert(acc);
    if(srList.isSuccess()){
   
     for(contact c:listCon ){
   
       c.AccountId=acc.id;
       cc.add(c);
     }
     
        insert cc;
       }
      
   
   
  
  
 
  
        return null;
    }


  

    public String name { get; set; }
}


test class:

@isTest
public class AccAndCons_Test{

    static testMethod void AccAndCons_testMethod(){
  
   
     Account a = new Account(name='chows');
  
     insert a;
     System.assertEquals(a.name,'chows');
     list<contact> con=new list<contact>();
     contact c1=new contact(lastName='test1',AccountID=a.id);
     contact c2=new contact(lastName='test2',AccountID=a.id);
     con.add(c1);
     con.add(c2);
    insert con;
     ApexPages.StandardController sc = new ApexPages.StandardController(a);
      
   
     AccAndCons aa=new AccAndCons(sc);
   
     aa.save();
  
     aa.cancel1();
    }


}
Anoop yadavAnoop yadav
LastName is mandatory in Contact
Add last Name before insert the contact.
Ramu_SFDCRamu_SFDC
Hi The problem is due to the existence of ID for the account object which you are trying to save(Insert) again through aa.save(); function.

Usually when the id is available you can only update that corresponding object but not insert, you would rather try aa.update(); function rather than aa.save().

Let me know if this worked.
Shri RajShri Raj
If the Id already exists, Try doing an Upser. which is Insert + Update