I am having problem while adding the attachment to case using apex from site. User will enter their details,they will select the PO and PO line item. After that we need to select the file for attachment and finally when they give submit the new case will be must be created along the attachment.But I am facing an issue while adding the attachment Issue no 1: If i have give the reRender = block for the button "Add PO", then the attachment disappear if the user again select the PO.Then we need to select the attachment again and if we click "submit" the record will be saved with attachment. Issue No 2: To over come the issue 1, i have added the outputpanel in my code and in the "AddPO" button i have given reRender = block1. If I have given like this attachment appears after click the "AddPO" again. But when I give submit, it is showing this error:

Input file is inside the Pageblock and Form.

Visualforce Error System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [File Name, Body]: [File Name, Body] Kindly any one help me resolve this.

enter image description here

VF Code:

<apex:page controller="DC_Buying_Wrapper1" tabStyle="Case" showHeader="false" sidebar="false" >
<apex:Form > 
**<apex:pageBlock id="block" >
<apex:outputPanel id="block1">
<apex:actionRegion >**  
<apex:pageMessages id="pgMsg" />                                                                     
<apex:pageBlockSection title="DC Authorization" rendered="{!showSection1}">       
<apex:inputField value="{!cases.Distribution_Centre__c}">

<apex:outputLabel value="Email" style="font-weight:Bold">
<apex:inputText value="{!cases.Email_Address__c}" title="Email" style="margin-left:20px"/>
<apex:commandButton action="{!method1}" value="Verify" reRender="block"/>

<apex:pageBlockSection title="Case Information" rendered="{!showSection2}" id="pag1" columns="2">       

<apex:pageBlockSection columns="1">                
<apex:inputField value="{!cases.Full_Name__c}"   label="Submitted By"/>
<apex:pageBlockSectionItem >       
<apex:outputLabel value="Type" />
<apex:actionRegion > 
<apex:outputPanel styleClass="requiredInput" layout="block" id="pwPanel" > 
<apex:outputPanel styleClass="requiredBlock"/>
<apex:selectList size="1" value="{!type}"  label="Request Reason"  required="true" style="width: 155px; " >
<apex:selectOptions value="{!Types}" /> 
<apex:actionSupport event="onchange"  reRender="mytable,ol"/>   
<apex:pageBlockSectionItem >

<apex:outputPanel id="mytable" style="margin-left:-10px;">
<apex:outputLabel value="Comments" id="ol" for="in" style="font-weight:Bold;margin-left:33px " rendered="{!(type='Why is my order booked, but not received' ||type='Why does my order not have a booking date?'||type='Why is my order booked, but not dispatched?'||type='Why is my order in COMPND status, but not showing in COMP?'||type='My order is in COMPND status, when will this be in store?'||type='Why is my order dispatched, but not completed?'||type='Can you please bring PO into DC earlier?'||type='Why does Vendor have proof of booking but it doesn’t appear in SFR?'||type='Why does Vendor have proof of booking but it doesn’t appear in SFR?'||type='Has my allocation been picked and dispatched to Stores?'||type='Stock is current an OOS, Pls prioritise PO'||type='Why is my order received, but not completed?')}">

<apex:inputtextarea value="{!resolution_comments}" style="margin-bottom:-15px; margin-left:10px" id="in" label="Comments"  rendered="{!(type='Why is my order booked, but not received'||type='Why does my order not have a booking date?'||type='Why is my order booked, but not dispatched?'||type='Why is my order in COMPND status, but not showing in COMP?'||type='My order is in COMPND status, when will this be in store?'||type='Why is my order dispatched, but not completed?'||type='Can you please bring PO into DC earlier?'||type='Why does Vendor have proof of booking but it doesn’t appear in SFR?'||type='Why does Vendor have proof of booking but it doesn’t appear in SFR?'||type='Has my allocation been picked and dispatched to Stores?'||type='Stock is current an OOS, Pls prioritise PO'||type='Why is my order received, but not completed?')}" />

<apex:pageBlockSection columns="1">     
<apex:pageBlockSectionItem >         
<apex:outputlabel value="{!$ObjectType.Case.fields.Vendor_Number__c.label}" for="Request"/>          
<apex:actionRegion immediate="true" >           
<apex:inputField value="{!cases.Vendor_Number__c}" required="true"  id="Request" style="margin-left:0px" >                                                                             
<apex:actionSupport event="onchange" action="{!VN_Populate}" rerender="panel"    / >

<apex:pageBlockSectionItem >
<apex:outputlabel value="{!$ObjectType.Case.fields.Vendor_Number1__c.label}" for="accinfo"/>
<apex:panelGrid id="panel">
<apex:outputField value="{!cases.Vendor_Number1__c}"   id="accinfo" label="Vendor Number" />   

<apex:inputField value="{!cases.Severity__c}" required="true"/>


<apex:pageBlockSection title="PO Information" rendered="{!showSection4}" >
<apex:pageBlockSection >
<apex:inputField value="{!keycode.PO__c}" required="true">
<apex:actionSupport event="onchange" reRender="pgMsg,selectedPoId" immediate="false"  rendered="true" action="{!actionMethod}">
<apex:outputLabel value="PO Line Item" style="font-weight:Bold;margin-left:10px;">
<apex:selectList value="{!selectedPoId}" multiselect="true" size="1" id="selectedPoId"  style="width:150px;height:50px;margin-left:20px;margin-bottom:-20px"  >
<apex:selectOptions value="{!poList}" />
**<apex:commandButton value="Add PO" action="{!addPO}" reRender="block1" />**
<apex:inputHidden value="{!setPOLineStr}" id="theHiddenInput"/>
<!-- Here we will use an extra variable to define a row number -->

<apex:outputPanel id="panelWithVar">
<apex:pageBlockSection id="poLineItemdetails" rendered="{!showSection5}" >
<apex:pageBlockTable value="{!wPO}" var="poLine" id="newItems" >

<apex:column value="{!poLine.poName}" title="PO Number" headerValue="PO Number"/>
<apex:column value="{!poLine.poContainer}" title="Container Number" headerValue="Container Number" />        
<apex:column value="{!poLine.poEventnumber}" title="Event Number" headerValue="Event Number" />
<apex:column value="{!poLine.poSourceSupply}" title="Source Supply" headerValue="Source Supply" />
<apex:column value="{!poLine.poOtype}" title="Order Type" headerValue="Order Type" />
<apex:column value="{!poLine.poSeasonCode}" title="Season Code" headerValue="Season Code" />        
<apex:column value="{!poLine.poNumberPallets}" title="Number Pallets" headerValue="Number Pallets" />
<apex:column value="{!poLine.poLineItemName}" title="PO LineItem" headerValue="PO LineItem" />
<apex:column value="{!poLine.pokeycode }" title="Keycode" headerValue="Keycode" /> 
<apex:column headerValue="Action">
<apex:commandButton value="Delete" action="{!delWrapper}" rerender="block1">
<apex:param name="toDelIdent" value="{!poLine.poLineItemId}" assignTo="{!delPOLineId}"/> 

<apex:pageBlockSection title="Attachment" rendered="{!showAttach}">      
<apex:inputFile filename="{!fileName}" contentType="{!contentType}" filesize="1000" size="50" value="{!Attach}"></apex:inputFile>  

<apex:pageBlockButtons location="Bottom"  id="btn">     
<apex:commandButton Value="Submit And New" action="{!save}" />      
<apex:commandButton Value="Submit And End" action="{!saveEnd}"/>
<apex:commandButton Value="Submit And Clone" action="{!saveClone}"  />        



Apex Code:

public class DC_Buying_Wrapper1

public Attachment myAttachment {get;set;}
 public blob Attach {get;set;}
 public String fileName {get; set;}
  public String contentType {get; set;}

public String searchEmail{get;set;}
public String container{get;set;}
  public ID userid {get; set;} 
   public String resolution_comments{get;set;}
   /*Remove List*/
  public static Integer toDelIdent {get; set;} 
 private Integer nextIdent=0;
 /*Remove List*/
   public Integer numberOfRowToRemove { get; set; }/*Remove List*/
  /*Section Hide*/
  public Boolean showSection1{get;set;}
  public Boolean showSection2{get;set;}
  public Boolean showSection3{get;set;}
  public Boolean showSection4{get;set;}
  public Boolean showSection5{get;set;}
  public Boolean showAttach{get;set;}
  /* Multiselect Populate*/
  public Keycode__c keycode{get;set;}
  public List<selectOption> poList{get;set;}
  public List<String> selectedPoId {get;set;}
  public string sPoId;  
  public Case CaseFname{get;set;}
  public string type{get;set;}
  public string fName;     
  Case cases;
  String distri;
  String email;
  public String setPOLineStr {get; set;}
  public String delPOLineId {get;set;}
  public List<wrapperPO> wPO {get;set;}
   public List<Contact> contacts;
   public list<Keycode__c> poLineItems{get;set;}
  public Case getCases() {
      //if(cases == null) Cases = new Case();
      if(cases == null){
       Cases = new Case();
      if (distri!='' & email!=''){
        cases.Distribution_Centre__c = distri;
        cases.Email_Address__c = email;
      return cases;

  public DC_Buying_Wrapper1(){
    /*Section Hide*/
    wPO = new List<wrapperPO>();
    showSection1=true ;
    showSection2= false;
    showSection3 = false;
    showSection4 = false;
    showSection5 = false;
    myAttachment = new Attachment();
    /* Multiselect Populate*/
    keycode = new Keycode__c();

    distri = ApexPages.currentPage().getParameters().get('Distri'); 
    email = ApexPages.currentPage().getParameters().get('email');
    poList = new List<selectOption>();
    poList.add(new selectOption('', '- None -')); 
    CaseFname=new Case();   
    poLineItems =new List<Keycode__c>();  
    String message = '' + ApexPages.CurrentPage().GetParameters().Get('message');
    String pageHeaderReferer = ApexPages.currentPage().getHeaders().get('Referer'); 

    // Use the referrer parameter to only show the message when coming from Page 1
    if(pageHeaderReferer != null && pageHeaderReferer.containsIgnoreCase('DC_Buying_Wrapper') && message != 'null')
        // ApexPages.CurrentPage().AddMessage(new ApexPages.Message(ApexPages.Severity.Info, message));
        ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, message)); 


  /* DC Populate Full Name*/
  public void actiionFullName()
  CaseFname =[select id,Distribution_Centre__r.Name from Case where id=:CaseFname.Distribution_Centre__c];
  /****************************************Delete Row*******************************************************/  
  public PageReference delWrapper()
 /* Integer toDelPos=-1;
  for (Integer idx=0; idx<wPO.size(); idx++)
   if (wPO   [idx].ident==toDelIdent)

  if (-1!=toDelPos)

  system.debug('>>>delWrapper before setPOLineStr:' + setPOLineStr);
    Set<String> setPOLine = new Set<String>();
    if(setPOLineStr.length() > 0) {
        setPOLine = convertStringToSet(setPOLineStr);
    system.debug('>>>delWrapper setPOLine:' + setPOLine);
    system.debug('>>>delWrapper toDelIdent:' + delPOLineId);
    // if(setPOLine.contains(delPOLineId)){

       setPOLineStr = convertSetToString(setPOLine);
        system.debug('>>>delWrapper after setPOLineStr:' + setPOLineStr);
    // }
    return null;
 /****************************************End Delete Row*******************************************************/ 

    // Convert comma separated string to Set<String>
    private Set<String> convertStringToSet(String cStr) {
        Set<String> setStr= new Set<String>();
        if(cStr.length() > 0) {
            if(cStr.contains(',')) {
                String[] part = cStr.split(',');
                for(string str : part) {
            else {
        return setStr;

    private String convertSetToString(Set<String> setStr) {
        String cStr = '';
        if(setStr.size() > 0) {
            for(String str:setStr) {
                cStr += (str + ',');
            cStr = cStr.subString(0,cStr.length()-1);
            system.debug('>>>Converted string value:' + cStr);
        return cStr;
      //Vendor Number  Populate from Account
    public String getVNo_ID(Id vnid)
        String vnoId = [select Name,Vendor_Number__c 
                        from Account
                        where id=:vnid
                        LIMIT 1].Vendor_Number__c;
        return vnoId;
    public void VN_Populate()
        if (case.Vendor_Number__c != null)
            String vendornumberid = getVNo_ID(cases.Vendor_Number__c);
            cases.Vendor_Number1__c = vendornumberid ;

  /* Multiselect Populate*/
  public void actionMethod()
    sPoId = keycode.PO__c;
    poList = new List<selectOption>();
    poList.add(new selectOption('', '- None -'));

    for (Keycode__c key : [SELECT Name,PO__r.Container_Number__c,PO_Line_Item_Keycode__c FROM Keycode__c where PO__c =: sPoId Order By Name ASC   ]) 
      //poList.add(new selectOption(key.Id, key.Name)); 
      poList.add(new selectOption(key.Id, key.PO_Line_Item_Keycode__c)); 

    /*keycode=[Select Id,Name,PO__r.Container_Number__c from Keycode__c where id=:keycode.PO__C limit 1];
    // return null;

    /* public PageReference container()


    /*Section Hide*/  
  public PageReference method1()
   /* contacts = [select Id,Name,email from contact where AccountId =:cases.Distribution_Centre__c 
                and Email=:cases.Email_Address__c Limit 1 ];
     contacts = [select Id,Name,email from contact where AccountId =:cases.Distribution_Centre__c Limit 1 ];          
    if(contacts.size() > 0){  */

    If(Pattern.matches(('^[_A-Za-z0-9._-][email protected]'), cases.Email_Address__c)||Pattern.matches(('^[_A-Za-z0-9._-][email protected]'), cases.Email_Address__c)||Pattern.matches(('^[_A-Za-z0-9._-][email protected]'), cases.Email_Address__c)||Pattern.matches(('^[_A-Za-z0-9._-][email protected]'), cases.Email_Address__c)||Pattern.matches(('^[_A-Za-z0-9._-][email protected]'), cases.Email_Address__c))
      //cases.Full_Name__c = contacts[0].Name;
        showSection2= true;
        showSection3 = true;
        showSection4 = true;
      showSection2= false;
      showSection3 = false;
      showSection4 = false;
      ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'No matching DC user found in the system, please contact the C&S Team')); 

    return null;        

   // The method to remove an item from the list
    public PageReference removeNewObject(){


        return null;

    /************************************************Add PO*************************************************************/
    private Map<id,wrapperPO> MapOfwrapperPO = new Map<id,wrapperPO>();
  set<id> MapOfwrapperPO2 = new set<Id>();
  public PageReference addPO(){
     Set<String> setPOLine = new Set<String>();
   system.debug('>>>before setPOLineStr:' + setPOLineStr);
    // system.debug('>>>before setPOLine add:' + setPOLine);
    if(setPOLineStr.length() > 0) {
        setPOLine = convertStringToSet(setPOLineStr);
    for(string str : selectedPoId) {
        else {
            //add ApexPage messages
           ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR,' The PO and PO Line Item selected has already been added to this query '));
    setPOLineStr = convertSetToString(setPOLine);
    system.debug('>>>after setPOLineStr:' + setPOLineStr);
    system.debug('>>>after setPOLine add:' + setPOLine);
    // Set<Keycode__c> myset = new Set<Keycode__c>();
    //wPO = MapOfwrapperPO.values(); 
    return null;
    /************************************************End Add PO*************************************************************/
    /*******************************Change PO Line item based selected line item ******************************************/
    private void changePOLineItems(Set<String> setPOLine) {
        system.debug('>>>changePOLineItems setPOLine' + setPOLine);
        List<Keycode__c> poLineItems = [Select Id,Name,Keycode__c,PO__c,PO__r.Name,PO__r.Container_Number__c,PO__r.Event_Number__c,PO__r.Source_of_Supply__c,PO__r.Booking_Date_Time__c,PO__r.Order_Type__c,PO__r.Season_Code__c,PO__r.Number_Pallets_Cartons__c from Keycode__c where id IN: setPOLine Order By PO__r.Name,Name ASC   ];
        system.debug('>>>poLineItems:' + poLineItems);
        wPO = new List<wrapperPO>();
        for(Keycode__c poLineItem:poLineItems){
            // if(!MapOfwrapperPO2.contains(poLineItem.id)){
                wrapperPO wsinglePO = new wrapperPO(nextIdent++);
                wsinglePO.poLineItemId = poLineItem.Id;
                wsinglePO.poLineItemName = poLineItem.Name;
                wsinglePO.pokeycode = poLineItem.Keycode__c;
                wsinglePO.poID = poLineItem.PO__c;
                wsinglePO.poName = poLineItem.PO__r.Name;
                wsinglePO.poEventnumber =poLineItem.PO__r.Event_Number__c;
                // MapOfwrapperPO2.add(poLineItem.Id);
            // }
        system.debug('>>>wPO:' + wPO);
 /*******************************Change PO Line item based selected line item ******************************************/   


  public PageReference save(){
     /*get owner id*/
              User us = new User();
               us = [SELECT ID, Name FROM User where name =: 'C&S Team' LIMIT 1];               
               userid = us.ID;
               /*get owner id*/
    Case caseRecord = new Case();
    List<Big_W_Case_PO__c> CasePOs = new List<Big_W_Case_PO__c>();
    Set<id> poIds = new Set<id>();
    List<BIG_W_Case_PO_PO_Line_Items__c> casePOPOLineItems = new List<BIG_W_Case_PO_PO_Line_Items__c>();
    //caseRecord.Full_Name__c = cases.Full_Name__c;
    //caseRecord.Email_Address__c = cases.Email_Address__c;
    caseRecord.Logged_By_Email__c = cases.Email_Address__c;
    //caseRecord.OwnerID = userid;
    caseRecord.Distribution_Centre__c = cases.Distribution_Centre__c;
    caseRecord.Vendor_Number__c = cases.Vendor_Number__c;
     caseRecord.Vendor_Number1__c = cases.Vendor_Number1__c ;
    //caseRecord.DC_Contact_Name__c = cases.Full_Name__c;
    //caseRecord.DC_Contact_Name__r.LastName = cases.Full_Name__c;
    caseRecord.Severity__c = cases.Severity__c;

   // caseRecord.DC_Contact_Name__c = contacts[0].Id;

    caseRecord.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().
                                get('Big W DC Buying Queries Record').getRecordTypeId();

   /************Assignment Rule**************/

   AssignmentRule  AR = new AssignmentRule();
        AR = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];

        //Creating the DMLOptions for "Assign using active assignment rules" checkbox
        Database.DMLOptions dmlOpts = new Database.DMLOptions();
        dmlOpts.assignmentRuleHeader.assignmentRuleId= AR.id;
       // dmlOpts.EmailHeader.triggerAutoResponseEmail = true; 
       dmlOpts .EmailHeader.triggerUserEmail = true;

   /************End Assignment Rule**************/                               

    insert caseRecord;
    insert myAttachment;   

    for(wrapperPO wPOs:wPO){

     Big_W_Case_PO__c casePO = new Big_W_Case_PO__c();
     casePO.Case__c = caseRecord.Id;
     CasePO.PO__c = wPOs.poID;
      casePO.Keycode__c =wPOs.pokeycode; 
     CasePO.RecordTypeId = Schema.SObjectType.Big_W_Case_PO__c.getRecordTypeInfosByName().
                                get('Big W DC Buying Queries Record').getRecordTypeId();
   insert CasePOs;
   for(wrapperPO wPOs:wPO){
    for(Big_W_Case_PO__c casePO:CasePOs){
      BIG_W_Case_PO_PO_Line_Items__c casePOPOLineItem = new BIG_W_Case_PO_PO_Line_Items__c();
      if(casePO.PO__c == wPOs.poID){
        casePOPOLineItem.Big_W_Case_PO__c = casePO.Id;
        casePOPOLineItem.PO_Line_Item__c = wPOs.poLineItemId;
        casePOPOLineItem.Keycode__c  = wPOs.pokeycode;
        casePOPOLineItem.RecordTypeId = Schema.SObjectType.BIG_W_Case_PO_PO_Line_Items__c .getRecordTypeInfosByName().
                                get('BIG W DC Buying Queries Record').getRecordTypeId();

    insert casePOPOLineItems;

    PageReference pg = new PageReference('/apex/DC_Buying_Wrapper');
  // PageReference pg = Page.DC_Buying_Wrapper;
   /* pg.getParameters().put('Distri',cases.Distribution_Centre__c);
    pg.getParameters().put('email', cases.Email_Address__c);*/
         pg.getParameters().put('message', 'Record Created Successfully');

    //apexpages.Message msg = new Apexpages.Message(ApexPages.Severity.Info,'Record Created Successfully: ');

    return pg;

     /************************************************End Save************************************************************/

public List<SelectOption> getTypes()
        List<SelectOption> options = new List<SelectOption>();

        options.add(new SelectOption('None','None'));    
        options.add(new SelectOption('Why is my order booked, but not received','Why is my order booked, but not received'));
        options.add(new SelectOption('Why does my order not have a booking date?','Why does my order not have a booking date?'));
        options.add(new SelectOption('Why is my order booked, but not dispatched?','Why is my order booked, but not dispatched?'));
        options.add(new SelectOption('Why is my order in COMPND status, but not showing in COMP?','Why is my order in COMPND status, but not showing in COMP?'));
        options.add(new SelectOption('My order is in COMPND status, when will this be in store?','My order is in COMPND status, when will this be in store?'));
        options.add(new SelectOption('Why is my order dispatched, but not completed?','Why is my order dispatched, but not completed?'));
        options.add(new SelectOption('Can you please bring PO into DC earlier?','Can you please bring PO into DC earlier?'));

        options.add(new SelectOption('Why does Vendor have proof of booking but it doesn’t appear in SFR?','Why does Vendor have proof of booking but it doesn’t appear in SFR?'));
          options.add(new SelectOption('Has my allocation been picked and dispatched to Stores?','Has my allocation been picked and dispatched to Stores?'));
        options.add(new SelectOption('Stock is current an OOS, Pls prioritise PO','Stock is current an OOS, Pls prioritise PO'));
        options.add(new SelectOption('Why is my order received, but not completed?','Why is my order received, but not completed?'));

        return options;

  public class wrapperPO{
    public string poID {get;set;}
    public string poName {get;set;}
    public string pokeycode{get; set;}
    public string poLineItemId {get;set;}
    public string poLineItemName {get;set;}
    public string poContainer {get;set;}
     public string poEventnumber {get;set;}
     public string poSourceSupply {get;set;}
     public Date poBdateTime {get;set;}
     public string poOtype {get;set;}
     public string poSeasonCode {get;set;}
     public string poNumberPallets {get;set;}
     public Integer ident {get; private set;}
      public wrapperPO(Integer inIdent)

  • Can yo add to the question the parts of the controller that touch fileName and Attach?
    – Keith C
    May 21, 2014 at 7:31
  • @Keith, Thanks for your reply, I have edited my questions. May 21, 2014 at 7:44
  • Thanks, though I still can't see the cause of the problem, but hopefully someone else will.
    – Keith C
    May 21, 2014 at 7:56
  • 1
    Looks like your problem is a duplicate of this How to resolve a inputfile rerender problem?. I assume the root cause is that while rerender can put back the state that is bound to controller properties, it can't put back the browser state related to a selected file.
    – Keith C
    May 21, 2014 at 8:06
  • 1
    As the answer in @KeithC's comment mentions, this just is not supported. There are is a hack work around dealing with apex:actionRegion, but it isn't worth the trouble. One solution that has worked for me, is to add a second page that the user is directed to where he/she can upload the document, at which point then the records are created/modified. May 26, 2014 at 16:28

1 Answer 1


use below line of code to attach document

apex:inputFile filename="{!Attach.name}" contentType="{!contentType}" filesize="1000" size="50" value="{!Attach.body}"/>

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .