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
Jagadeesh AdaveniJagadeesh Adaveni 

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

public class logView3Controller {

   
    public Boolean searched { get; set; }
   
    public List<Weeks__c> weekList = Weeks__c.getAll().values();
    public Map<Integer, Weeks__c> weekMap = new Map<Integer, Weeks__c>();
    public Map<String, Integer> weekMapGetIntWithWeek = new Map<String, Integer>();    
    public Map<String, Subjects_and_Levels__c> subjectLevelMap =  Subjects_and_Levels__c.getAll();
    public List<Subjects_and_Levels__c> subjectLevelList = subjectLevelMap.values();
    public Map<String, Subjects_and_Levels__c> levelMap = new Map<String, Subjects_and_Levels__c>();
       
    public Date StartDate {get;set;}
    public Date EndDate {get;set;}
    public String selectedLocation {get;set;}
    public String selectedDay {get;set;}
    public List<Log_Book__c> logBookEntries {get;set;}
    public List<studentsWithWeeks> studentsWithWeeksList {get;set;} 
    public studentsWithWeeks newSWW {get;set;}
    public String domain {get;set;}
    public List<integer> indexNums {get;set;}
    public List<String> weekTableHeader {get;set;}
    public List<String> subjectTableHeader {get;set;}
    
    public  List<Log_Book__c> relatedLogs{get;set;}
    
    //Jagadeesh
    public String selectedTeacher{get;set;}
    public String selectedDays{get;set;}
    
 
    public Id recordToUpdateId {get;set;} 
    public Id recordToUpdateIdStudent {get;set;} 
    
    
    public log_Book__c logObj {get;set;}
    public Student__c studentObj {get;set;}
    public boolean displayPopup {get; set;}
    public boolean displayPopupStudent {get; set;}
    public String exportToExcelURL {get;set;}
    public log_Book__c newLevel{get;set;}
    public log_Book__c newWeek{get;set;}
    List<Log_Book__c> lbjump{get;set;}
    // 2.  a,b,c,d - a,j,k,l,m - changing the complete series
    // Written by Jagadeesh(New code for skip records) 
    public List<Log_Book__c> jump{get;set;}
    public Log_Book__c jump1{get;set;}
    public List<Log_Book__c> lblist{get;set;}
    
     List<Log_Book__c> updateLogs = new List<Log_Book__c>();
     
     
      public logView3Controller () 
      {    
        domain = ApexPages.currentPage().getHeaders().get('Host'); 
        //exportToExcelURL = '/apex/logView3ExportToExcel?startDate='+startDate+'&endDate='+endDate+'&selectedLocation='+selectedLocation;
        exportToExcelURL = '/apex/logView3ExportToExcel?startDate='+startDate+'&endDate='+endDate+'&selectedLocation='+selectedLocation+'&selectedTeacher='+selectedTeacher;
        weekTableHeader = new List<String>();
        relatedLogs = new List<Log_book__c>();
        searched = false;
        
      
     }
      public String getEnglishColor() {
        return Colr;
      }
   
    public PageReference doUpdateLogObj2()
    {  
      
        String lv =  logObj.Week__c.split('-')[0];
       if(logObj.Subject__c == 'Math' && logObj.Level__c == 'Level 5B' && Integer.valueOf(lv) > 17){
           
          logObj.Week__c.addError('For Math Level 5B week should not exceed 17');
            return null;
        }
        system.debug('hii');
      
        relatedLogs = [SELECT Id FROM Log_Book__c WHERE Student__r.Id =: logObj.Student__r.Id AND Subject__c =: logObj.Subject__c AND Class_Scheduled_Date__c >=: logObj.Class_Scheduled_Date__c and isSkipped__c=false];        
        System.debug(' relatedLogs.Size()'+ relatedLogs.Size());
       
        Log_Book__c lb = new Log_Book__c();
        
        Integer levelOrder = Integer.valueof(subjectLevelMap.get(logObj.Subject__c +':'+logObj.Level__c).Order__c);
        Integer weekOrder;
            System.Debug('levelOrder :' + levelOrder);
            System.Debug('weekList :' + weekList);
            for(Weeks__c week : weekList)
            {
                weekMap.put((Integer)week.Order__c, week);
                weekMapGetIntWithWeek.put(week.Name, (Integer)week.Order__c);
            }
            System.Debug('weekMap :' + weekMap);
            System.Debug('weekMapGetIntWithWeek :'+ weekMapGetIntWithWeek);
            for(Subjects_and_Levels__c level: subjectLevelList)
            {
                levelMap.put(level.subject__c+Integer.valueof(level.Order__c), level);
            }
            System.Debug('levelMap :' + levelMap);
          Integer totalLevels = 0;
          if(logObj.Subject__c == 'English')
            totalLevels = 16;
          else if(logObj.Subject__c == 'Abacus')
            totalLevels = 11;
          else if(logObj.Subject__c == 'Math')
            totalLevels = 14;
          else if(logObj.Subject__c == 'G.K')
            totalLevels = 3;
         
        System.Debug('Total Logs :'+ relatedLogs.Size());
        lb = logObj.clone(false, true, false, false);
        updateLogs.add(lb);
        
        for(Integer i=1; i<relatedLogs.Size(); i++)
        {
                lb = new Log_Book__c();
                
                System.Debug('lblblblblblblb :' + lb);
                
                lb = updateLogs[i-1].clone(false, true, false, false);
                weekOrder = Integer.ValueOf(weekMapGetIntWithWeek.get(lb.Week__c));
                System.Debug('weekOrder : ' + weekOrder);                
                lb.Class_Scheduled_Date__c = lb.Class_Scheduled_Date__c.addDays(7);
                
                System.Debug('weekMapGetIntWithWeek.get(lb.Week__c) :'+ weekMapGetIntWithWeek.get(lb.Week__c));
                System.Debug('weekMapGetIntWithWeek.get(lb.Week__c)+i :'+ Integer.ValueOf(weekMapGetIntWithWeek.get(lb.Week__c))+i);
                if( weekOrder < 26 )
                {
                weekOrder = weekOrder+1;
                lb.Week__c = weekMap.get(weekOrder).Name;
                System.Debug('@@@@@@ lb.Week__c = ' + lb.Week__c);
                }
                else
                {
                  if(lb.week__c == '26-Z')
                  {
                    if(levelOrder < totalLevels)
                    {
                        levelOrder = levelOrder +1;
                        System.Debug('lb.Subject__c+levelOrder : '+ lb.Subject__c+levelOrder);
                        lb.level__c = levelMap.get(lb.Subject__c+levelOrder).Level__c;
                        lb.Week__c = '1-A';
                    
                    }
                  
                  }
                    else
                    if(lb.Subject__c == 'Math' && lb.Level__c == 'Level 5B' && lb.Week__c == '17-Q')
                    {
                        if(levelOrder != null && levelOrder < totalLevels){
                        
                            levelOrder = levelOrder +1;
                        
                         lb.level__c = levelMap.get(lb.Subject__c+levelOrder).Level__c;
                         lb.Week__c = '1-A';
                           
                        
                        
                        }
                    }
                    
                    else
                    {
                    i = relatedLogs.Size();
                    
                    }
                }
           
                 System.Debug('lblblblblblblb :' + lb);
                
                        
                updateLogs.add(lb);
                System.Debug('updateLogs : '+ updateLogs);        
        }
        
         System.debug('--->related logs are--->'+relatedLogs);
         delete relatedLogs;
         System.debug('--->related logs are after delete--->'+relatedLogs);
         insert updateLogs;
         
      
           
         //insertLogs();
              
        System.debug('@@@@@updated logs@@@'+updateLogs.size()+'----------->'+updateLogs[0]);
        
        displayPopup = false;
        doSearch();
        
   
       return null;      
    }
    
   /*public void deleteLogs()
    {
      
         if(relatedLogs.size()>0 && relatedLogs!=null){
        
        System.debug('@@@@@relatedlogs@@@'+relatedLogs.size());
        try{
        delete relatedLogs; 
         } catch(exception e)
             {
                 ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,e.getMessage()));

             } 
        }
           
    }
    
    public void insertLogs()
    {
        if(updateLogs.size()>0 && updateLogs!=null){
        
            System.debug('@@@@@relatedlogs@@@'+relatedLogs.size());
            try{
            insert updateLogs; 
            }catch(exception e)
             {
                 ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error,e.getMessage()));

             } 
           }
         
    }*/
    
    public void closePopup()
    {        
        displayPopup = false; 
    }
    public void closePopupStudent()
    {        
        displayPopupStudent = false; 
    }     
    public void showPopup() 
    {    
        logObj = new log_Book__c();
        try
        {
            system.debug('recordToUpdateId : '+recordToUpdateId);
            logObj = [SELECT Id, Name,Start_Time__c,End_Time__c, Color_Code__c, Comment_on_LogBook__c, Subjects_Registered__c, Student__c, Student__r.Id, Student__r.Color_Code__c, Student__r.Name, Student__r.Last_Name__c, Subject__c, Level__c, Week__c, Week_Day__c, Class_Scheduled_Date__c,Subjects_Registered__r.Teacher__c, Student__r.Location__r.Name FROM Log_Book__c WHERE Id =:recordToUpdateId  ];    
            system.debug('old name : '+logObj.Name+' old week : '+logObj.Week__c+' old Level : '+logObj.Level__c+' id '+logObj.id);
            system.debug('teacher name '+logObj.Subjects_Registered__r.Teacher__c);
        }
        catch(exception e)
        {
        System.Debug(e.getMessage());
        }
        displayPopup = true;    
    }
    public void showPopupForStudent() 
    {    
        studentObj = new Student__c();
        try
        {
        studentObj = [SELECT Id, Color_Code__c, Comment_on_LogBook__c, Name, Last_Name__c FROM Student__c WHERE Id =:recordToUpdateIdStudent];    
        }
        catch(exception e)
        {
        System.Debug(e.getMessage());
        }
        displayPopupStudent = true;    
    }
Best Answer chosen by Jagadeesh Adaveni
Agus AndrésAgus Andrés
Hi Jagadeesh,

The error you are getting is simple, you can't make an insert if you have set the id of an object, you can do two things:

- Set the id of your object to null, in that case salesforce will create a new record putting his own id
- Make and update instead of an insert, in that case this will write your record which have the same id

All Answers

Agus AndrésAgus Andrés
Hi Jagadeesh,

The error you are getting is simple, you can't make an insert if you have set the id of an object, you can do two things:

- Set the id of your object to null, in that case salesforce will create a new record putting his own id
- Make and update instead of an insert, in that case this will write your record which have the same id
This was selected as the best answer
Ansh CoderAnsh Coder
Hi,
on line number: 179
if you want to update the previously existing records then,use 
update updateLogs;

else if you walt to create new records of the Log_book__c
the use this before line 172 and 112
lb.id=NULL;

 
Jagadeesh AdaveniJagadeesh Adaveni
Thanks for your replay,

But this statement is not working
177   delete relatedLogs;