[SalesForce] Error with Parent as Required Field when Uploading Attachment from Form

I am making a custom form with the standard Case controller that needs to be able to accept attachments. I have written a controller extension that does a couple of things, including handle the attachment. The problem I am running into is when i go to insert the attachment. The error states: "Insert Failed REQUIRED_FIELD_MISSING, Required fields are missing: [Parent]: [Parent]".

I have, however, set the parentId for this attachment when I write: ParentId = supportCase.Id. Below is teh code for the controller extension:

public class PartnerSupportCaseController {

public Case supportCase {get;set;}

public Attachment attachedFile;



public PartnerSupportCaseController(ApexPages.StandardController controller)
{

    this.supportCase = (Case)controller.getRecord();
    supportCase.Protocol_Sub_Issue__c = 'Partner Support - Please Pick';
    supportCase.Protocol_Issue__c = 'Partner Support - Please Pick';
    supportCase.RecordTypeId = '012M000000092ju';


}

public Attachment getAttachedFile(){
    attachedFile = New Attachment();
    return attachedFile;

}



public pagereference Save()
{


    Attachment a = new Attachment(ParentId = supportCase.Id, name = attachedFile.Name, body = attachedFile.Body);

    insert supportCase;
    insert a;      

    PageReference pg = Page.PartnerSupportThankYou;
    pg.setredirect(true);
    return pg;


  }


 } 

I am also adding the excerpt from my form where the file is taken in:

<apex:page sidebar="false" showHeader="false" standardController="Case" extensions="PartnerSupportCaseController">

<apex:pageBlockSection>

           <apex:inputfile value="{!attachedFile.body}" filename="{!attachedFile.Name}" />                       
           </apex:pageBlockSection>

I just need to pinpoint why this insert is failing due to a missing required field, even though I have filled that required field.

Thanks,
-CP

Best Answer

putting this as answer because if I put that as comment you might confuse with syntax.

you have defined a visualforce page and until and unless you are not passing id of case in url controller will not get it, Try to get one case id in your org and pass this in url in following way.

/apex/YOURVFPAGENAME?id=CASERECORDID

replace both parameters.

  1. YOURVFPAGENAME with your visualforce page name
  2. CASERECORDID with any case id.

if you want to create a case everytime you upload attachment update your save method in following way

public pagereference Save()
{

   upsert supportCase;
   Attachment a = new Attachment(ParentId = supportCase.Id, name = attachedFile.Name, body = attachedFile.Body);
   insert a; 

} 
Related Topic