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
nikita dhamalnikita dhamal 

System.DmlException: Insert failed. First exception on row 0 with id a0O17000001aWCWEA2; first error: INVALID_FIELD_FOR_INSERT_UPDATE

I am trying to insert new record in object and if the project name and task name already exist then it should update the record. getting error
"System.DmlException: Insert failed. First exception on row 0 with id a0O17000001aWCvEAM; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
Error is in expression '{!save}' in component <apex:commandButton> in page timesheet1: Class.TimeSheetDataController.save: line 32, column 1"
mu code is:
<apex:pageBlock id="xxxpb1" title="TimeSheet Entry">
        <apex:pageBlockSection columns="2"> 
            <apex:inputField value="{!tsObj.Start_Date__c}"/>
            <apex:inputField value="{!tsObj.End_Date__c}"/>
            <apex:inputField value="{!tsObj.Projects__c}"/>
            <apex:inputField value="{!tsObj.Tasks__c}"/>   
            <apex:inputField value="{!tsObj.Log_Hours__c}"/>
            <apex:inputField value="{!tsObj.Important_Notes__c}"/>
        </apex:pageBlockSection>
       
        <apex:pageBlockButtons >
            <apex:commandButton value="Save" action="{!save}" reRender="block"/>
            <apex:commandButton value="Cancel" action="{!cancel}" reRender="block"/>

        </apex:pageBlockButtons>
    </apex:pageBlock>
 public PageReference save()
 {  PageReference page = new PageReference('/apex/Timesheet1');
  List<Timesheet__c> timesheetentries1 = new List<Timesheet__c>();
   
    timesheetentries1 = [select name,id,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from Timesheet__c];
     
     for(Timesheet__c ts:timesheetentries1)
    {
       if(ts.Projects__c==tsObj.Projects__c && ts.Tasks__c==tsObj.Tasks__c )
        {
         d=tsObj.Log_Hours__c;
         tsObj1=[select id,name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from Timesheet__c where Projects__c =: tsObj.Projects__c and Tasks__c=:tsObj.Tasks__c];
         tsObj1.Log_Hours__c= tsObj1.Log_Hours__c+tsObj.Log_Hours__c;
         update tsObj1;
         page.setRedirect(true);
       }
      
      else{
        insert tsObj;
        page.setRedirect(true);}
        }
       return page;
 
 }
Best Answer chosen by nikita dhamal
Amit Chaudhary 8Amit Chaudhary 8
Try below code. To check duplicate record and update
public class TimeSheetDataController{
public TimeSheet__c tsObj{get;set;}
public boolean checkbx{get;set;}
public string val{get;set;}
public Decimal d;
public TimeSheetDataController()
{
   tsObj = new TimeSheet__c();
   checkbx = false;
}

public PageReference save()
{
	PageReference page = new PageReference('/apex/TimeSheetEntry');
    List<TimeSheet__c> timesheetentries = new List<TimeSheet__c>();
    timesheetentries = [select  id,name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from TimeSheet__c where Projects__c=:tsObj.Projects__c and Tasks__c=:tsObj.Tasks__c];

	if(timesheetentries.size() > 0 )
	{
		for(TimeSheet__c ts:timesheetentries)
		{
			 d=tsObj.Log_Hours__c;
			 ts.Log_Hours__c= tsObj.Log_Hours__c+d;
		}	
		Update timesheetentries;
		 page.setRedirect(true);
	}
	else
	{
			 insert tsObj;
			 page.setRedirect(true);
	}

    return page;
 }
 
 public PageReference cancel(){
 
    PageReference page = new PageReference('/apex/TimeSheet1');
    page.setRedirect(true);
    return page;
 }
  
public List<TimeSheet__c>getTimesheetEntries()
{
    system.debug('****************************Value*****************************'+val); 
    List<TimeSheet__c> timesheetentries = new List<TimeSheet__c>();
    
    if(val =='CurrentWeek')
    {
    timesheetentries = [select name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from TimeSheet__c where LastModifiedDate > LAST_N_DAYS:7];
    return timesheetentries ;
    }
    if(val =='LastWeek')
    {
    timesheetentries = [select name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from TimeSheet__c where LastModifiedDate = LAST_WEEK];
    return timesheetentries ;
    }
    else
    {    
     timesheetentries = [select name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from TimeSheet__c where createdById =:UserInfo.getUserId()];
     return timesheetentries ;
    }
    
    return timesheetentries;
 }
 
 public pageReference viewData(){
 getTimesheetEntries();
 return null;
 }
 
}
let us know if this will help u
 

All Answers

BALAJI CHBALAJI CH
Hi Nikita,

This Exception occued because "tsObj" is already a record in object Timesheet__c and it cannot be reinserted again.
To insert a record with same value of tsObj, you can try this in your else block.
 
else{
    Timesheet__c temp = new Timesheet__c ();
    temp = tsObj;
    insert temp;
    page.setRedirect(true);}
}
return page;
}

Let me know if that helps you.

Best Regards,
BALAJI
nikita dhamalnikita dhamal
hi.. i tried to implement as per your solution but m still getting the same error in inserting new record as well as updating the record
 
BALAJI CHBALAJI CH
Can you please share full Apex code, where did tou initialised "tsObj" in the controller and where else you used.
nikita dhamalnikita dhamal
Controller:
public class TimeSheetDataController{
public TimeSheet__c tsObj{get;set;}
public boolean checkbx{get;set;}
public string val{get;set;}
public Decimal d;
public TimeSheetDataController()
{
   tsObj = new TimeSheet__c();
   checkbx = false;
}

public PageReference save()
{
PageReference page = new PageReference('/apex/TimeSheetEntry');
    List<TimeSheet__c> timesheetentries = new List<TimeSheet__c>();
    timesheetentries = [select  id,name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from TimeSheet__c];
     
     for(TimeSheet__c ts:timesheetentries)
     {
     if(ts.Projects__c==tsObj.Projects__c && ts.Tasks__c==tsObj.Tasks__c )
     {
         d=tsObj.Log_Hours__c;
         tsObj=[select name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from TimeSheet__c where Projects__c=:tsObj.Projects__c and Tasks__c=:tsObj.Tasks__c];
         tsObj.Log_Hours__c= tsObj.Log_Hours__c+d;
         update tsObj;
         page.setRedirect(true);
   
     }
     else
      {
         Timesheet__c temp = new Timesheet__c ();
         temp = tsObj;
         insert temp;
         page.setRedirect(true);
        
    }
      }
    return page;
 }
 
 public PageReference cancel(){
 
    PageReference page = new PageReference('/apex/TimeSheet1');
    page.setRedirect(true);
    return page;
 }
  
public List<TimeSheet__c>getTimesheetEntries()
{
    system.debug('****************************Value*****************************'+val); 
    List<TimeSheet__c> timesheetentries = new List<TimeSheet__c>();
    
    if(val =='CurrentWeek')
    {
    timesheetentries = [select name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from TimeSheet__c where LastModifiedDate > LAST_N_DAYS:7];
    return timesheetentries ;
    }
    if(val =='LastWeek')
    {
    timesheetentries = [select name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from TimeSheet__c where LastModifiedDate = LAST_WEEK];
    return timesheetentries ;
    }
    else
    {    
     timesheetentries = [select name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from TimeSheet__c where createdById =:UserInfo.getUserId()];
     return timesheetentries ;
    }
    
    return timesheetentries;
 }
 
 public pageReference viewData(){
 getTimesheetEntries();
 return null;
 }
 
}
page:
<apex:page sidebar="false" controller="TimeSheetDataController" >
<apex:form style="padding-left:6%;padding-right:6%" >
    <apex:pageBlock id="xxxpb1" title="TimeSheet Entry">
        <apex:pageBlockSection columns="2"> 
            <apex:inputField value="{!tsObj.Start_Date__c}"/>
            <apex:inputField value="{!tsObj.End_Date__c}"/>
            <apex:inputField value="{!tsObj.Projects__c}"/>
            <apex:inputField value="{!tsObj.Tasks__c}"/>   
            <apex:inputField value="{!tsObj.Log_Hours__c}"/>
            <apex:inputField value="{!tsObj.Important_Notes__c}"/>
        </apex:pageBlockSection>
       
        <apex:pageBlockButtons >
            <apex:commandButton value="Save" action="{!save}" reRender="block"/>
            <apex:commandButton value="Cancel" action="{!cancel}" reRender="block"/>

        </apex:pageBlockButtons>
    </apex:pageBlock>
 <apex:pageBlock >
    
    <apex:selectList id="selected_list" value="{!val}" required="false" size="1">
       <apex:selectOption itemvalue="AllTime" itemLabel="AllTime"/>
          <apex:selectOption itemvalue="CurrentWeek" itemLabel="CurrentWeek"/>
          <apex:selectOption itemvalue="LastWeek" itemLabel="LastWeek"/>
          <apex:actionSupport event="onchange" reRender="block" action="{!viewData}"/>
          </apex:selectList>
   <br></br><p></p><div></div>      
 <apex:pageBlockTable value="{!Timesheetentries}" var="t">
 <apex:column headerValue="Timesheet ID">
 <apex:outputLink value="/{!t.id}">{!t.name}</apex:outputLink></apex:column>
 <apex:column value="{!t.Start_Date__c}"/>
 <apex:column value="{!t.End_Date__c}"/>
 <apex:column value="{!t.Projects__c}"/>  
 <apex:column value="{!t.Tasks__c}"/>
 <apex:column value="{!t.Log_Hours__c}"/>
 </apex:pageBlockTable>
 </apex:pageBlock>
</apex:form>
</apex:page>
Amit Chaudhary 8Amit Chaudhary 8
Try below code. To check duplicate record and update
public class TimeSheetDataController{
public TimeSheet__c tsObj{get;set;}
public boolean checkbx{get;set;}
public string val{get;set;}
public Decimal d;
public TimeSheetDataController()
{
   tsObj = new TimeSheet__c();
   checkbx = false;
}

public PageReference save()
{
	PageReference page = new PageReference('/apex/TimeSheetEntry');
    List<TimeSheet__c> timesheetentries = new List<TimeSheet__c>();
    timesheetentries = [select  id,name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from TimeSheet__c where Projects__c=:tsObj.Projects__c and Tasks__c=:tsObj.Tasks__c];

	if(timesheetentries.size() > 0 )
	{
		for(TimeSheet__c ts:timesheetentries)
		{
			 d=tsObj.Log_Hours__c;
			 ts.Log_Hours__c= tsObj.Log_Hours__c+d;
		}	
		Update timesheetentries;
		 page.setRedirect(true);
	}
	else
	{
			 insert tsObj;
			 page.setRedirect(true);
	}

    return page;
 }
 
 public PageReference cancel(){
 
    PageReference page = new PageReference('/apex/TimeSheet1');
    page.setRedirect(true);
    return page;
 }
  
public List<TimeSheet__c>getTimesheetEntries()
{
    system.debug('****************************Value*****************************'+val); 
    List<TimeSheet__c> timesheetentries = new List<TimeSheet__c>();
    
    if(val =='CurrentWeek')
    {
    timesheetentries = [select name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from TimeSheet__c where LastModifiedDate > LAST_N_DAYS:7];
    return timesheetentries ;
    }
    if(val =='LastWeek')
    {
    timesheetentries = [select name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from TimeSheet__c where LastModifiedDate = LAST_WEEK];
    return timesheetentries ;
    }
    else
    {    
     timesheetentries = [select name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from TimeSheet__c where createdById =:UserInfo.getUserId()];
     return timesheetentries ;
    }
    
    return timesheetentries;
 }
 
 public pageReference viewData(){
 getTimesheetEntries();
 return null;
 }
 
}
let us know if this will help u
 
This was selected as the best answer
Manish BhatiManish Bhati
As a precaution you should not be using insert or update in FOR loop, so that your governing limits doesn't break.
In your case 

------------------------------------------------------------------------------------------
for(Timesheet__c ts:timesheetentries1)
    {
       if(ts.Projects__c==tsObj.Projects__c && ts.Tasks__c==tsObj.Tasks__c )
        {
         d=tsObj.Log_Hours__c;
         tsObj1=[select id,name,Important_Notes__c,Start_Date__c,End_Date__c,Projects__c,Owner.Name,Tasks__c,Log_Hours__c from Timesheet__c where Projects__c =: tsObj.Projects__c and Tasks__c=:tsObj.Tasks__c];
         tsObj1.Log_Hours__c= tsObj1.Log_Hours__c+tsObj.Log_Hours__c;
         update tsObj1;
         page.setRedirect(true);
       }
      
      else{
        insert tsObj;
        page.setRedirect(true);}
        }

------------------------------------------------------------------------------------------

let us take a case when you gave some new values in input field from your Page.
Also timesheetentries1 is a list which has multiple records let say 5 records(hence FOR loop will run 5 times), so, when it checks the if condition for first time from the table it will come to be false as the records are not in table Timesheet__c. So,it will goto else condition and insert the record.
But again when the loop runs for the second time and the conditions come to false it will try to reinsert the input record and will fail.
 
nikita dhamalnikita dhamal
@amit : m able to insert new record now ..thanks!!
@manish: i think thats the problem m facing..working on it.. thanks!!