I have a VF page where the user is to upload a file and a custom controller to save this to the notes and attachments section of the object record.
I'm receiving the following error when hitting the save button on my VF page:
Insert failed. First exception on row 0 with id a014W00000xc8aOQAQ; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
Error is in expression '{!saveScholarship}' in component <apex:commandButton> in page testpage: Class.regularController.saveScholarship: line 14, column 1
Records save successfully when not attaching a document.
Here is my code:
Custom controller
public with sharing class regularController {
public Scholarship_Award__c sch {get;set;}
public Recipient__c rec {get;set;}
//Constructor
public regularController(){
sch = new Scholarship_Award__c();
rec = new Recipient__c();
}
public void saveScholarship(){
rec.School__c=sch.School__c;
insert rec;
sch.Recipient__c = rec.Id;
insert sch;
}
}
Controller extension for document upload
public with sharing class testController{
//
public testController(regularController ctrlParam){
}
public Recipient__c myCustomObject;
private Attachment myDocument;
public Attachment myDoc
{
get
{
if(myDocument==null){
myDocument = new Attachment();
}
return myDocument;
}
set;
}
public testController(ApexPages.StandardController controller)
{
myCustomObject = (Recipient__c) controller.getRecord();
}
public PageReference upload()
{
myDoc.parentId = myCustomObject.Id;
insert myDoc;
return null;
}
}
VF Page
<apex:page controller="regularController" extensions="testController" lightningStylesheets="true">
<apex:form>
<apex:pageBlock >
<!--Recipient form-->
<apex:pageBlockSection title="Add recipients" columns="2">
<apex:inputField value="{!rec.Name}"/>
<apex:inputField value="{!rec.Last_Name__c}"/>
<apex:inputField value="{!rec.Preferred_Name__c}"/>
<apex:inputField value="{!rec.Email__c}"/>
<apex:inputField value="{!sch.Award__c}"/>
<apex:inputField value="{!sch.School__c}"/>
<apex:inputField value="{!rec.School__c}" rendered="false"/>
<apex:inputField value="{!sch.Year__c}"/>
<apex:inputField value="{!rec.Specialty__c}"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Biography">
<apex:outputLabel >Upload or enter student biography/CV</apex:outputLabel>
<apex:inputFile id="myFile" value="{!myDoc.Body}" fileName="{!myDoc.Name}">
</apex:inputFile>
<apex:inputTextarea value="{!rec.Biography__c}" rows="3" cols="100"/>
</apex:pageBlockSection>
<!--Record list-->
<!--Submit all records in record list-->
<apex:pageBlockButtons location="bottom">
<apex:commandButton action="{!saveScholarship}" value="Submit"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
<apex:pageMessages>
</apex:pageMessages>
</apex:page>
Thank you all for your help.