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
Shree KShree K 

Unable to save case record with attachment

Unable to save case record with attachment, code as follows,help will be appreciated.
<apex:page standardController="Case" Extensions="CaseHandlerExtn" ShowHeader="False">
<apex:form >
<apex:pageBlock Title="Submit a Case" >
<apex:PageBlockSection Title="Section 1" columns="1">
<apex:PageblockSectionItem >
<apex:outputLabel >Contact Name</apex:outputLabel>
<apex:InputField Id="Id1" value="{!Case.ContactId}"/>
<apex:PageblockSectionItem >
<apex:outputLabel >Email</apex:outputLabel>
<apex:inputField Id="Id2" value="{!Case.ContactEmail}" />
<apex:PageblockSectionItem >
<apex:outputLabel >Subject</apex:outputLabel>
<apex:inputField Id="Id2" value="{!Case.subject}" />
<apex:PageblockSectionItem >
<apex:outputLabel >Description</apex:outputLabel>
<apex:inputField Id="Id2" value="{!Case.Description}" />
<apex:pageBlockButtons >

<apex:commandButton Id="Cancel" action="{!Cancel}" Value="Cancel" />

<apex:pageBlock title="Upload Attachment">
            <apex:inputFile style="width:100%" id="fileToUpload" value="{!fileBody}" filename="{!fileName}" />
            <apex:commandButton value="Upload Attachment" action="{!UploadFile}"/>
            <apex:commandButton Id="save" action="{!Save}" value="Save" />
Public Class CaseHandlerExtn {

Public attachment Atchmnt {get;set;}
Public Case Cs{get;set;}
Public Blob Filebody{get;set;}
Public String FileName{get;set;}
Public Id RecId {get;set;}

//Public Contact Con{get;set;}

Public CaseHandlerExtn (Apexpages.StandardController StndCntlr){
      Atchmnt = New attachment();
       RecId = StndCntlr.getRecord().Id; 
      Cs = New Case(status='New',Origin='Web');    
 Public Void SaveCase(){
  insert Cs;
  Insert Atchmnt ;
  public PageReference UploadFile()
        PageReference pr;
        if(fileBody != null && fileName != null)
          Attachment myAttachment  = new Attachment();
          myAttachment.Body = fileBody;
          myAttachment.Name = fileName;
          myAttachment.ParentId = recId;
          insert myAttachment;
           pr = new PageReference('/' + myAttachment.Id);
           return pr;
        return null;

Best Answer chosen by Shree K
sagarika bsagarika b
  • Change your code at line 30 in VisualForce page as
    <apex:commandButton Id="save" action="{!SaveCase}" value="Save" />
  • Moreover, Change SaveCase() code as below
  •      insert Cs;
         Atchmnt .clear()
         Atchmnt.Body = fileBody;
         Atchmnt.Name = fileName ; 
         Atchmnt.ParentId =;           
         insert Atchmnt;

    With this changes, we are successful insert attachments to case object.
We hope it helps you