+ Start a Discussion
SF_MonkeySF_Monkey 

Attach file to VF page and show it as a related list

I am trying to add an attachment to a VF page on a custom object. I want those attached files to appear as related files on the record. The page creates a new record, give list of cases to attach with it (Works Well) and option of three attachments (problem). When Save button is hit, new record and cases are added; however, the attachments do not show up in the related files.
I am aware that as of 2016, Salesforce convert all of the attachments as files. I have read some articles about ContentVersion and ContentDocument.
I am unable to understand how to put it into practice or how to use it in this context. My futile attempt is written in the code below. Any help will be appreciated.
Thanks!
VisualForce Page:
<apex:page standardController="Account" extensions="newCom" >
     <script>
     function closeWindow(){      
            window.opener.location.href="/{!$CurrentPage.parameters.id}"
      }

    var $j = jQuery.noConflict();
    function getValues() {
        var v1 = $j('.value1').val();
        if(typeof v1 != 'undefined') sendValues(v1);
    }
    </script>
    <!--Page Header -->
    <apex:sectionHeader title="New Bill Complete Form"/>


    <apex:form html-novalidate="novalidate">
        <apex:actionFunction name="sendValues" reRender="render">
            <apex:param name="value1" value="" assignTo="{!value1}" />
        </apex:actionFunction> 

    <!--Page block to enter the new information -->   
    <apex:pageBlock title="New Billing Complete Form" mode="edit">

        <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!comInsert}"/>
                <apex:commandButton value="Cancel" action="{!noBill}" immediate="true" />
            </apex:pageBlockButtons>

        <apex:pageBlockSection title="Information"  >

            <apex:outputField label="Account" value="{!comBill.Account__c}" /> 
             <apex:outputField label="Record Type" value="{!comBill.RecordTypeID}"/> 
            <apex:inputField label="Reason for Removal" value="{!comBill.Reason_for_Removal__c}" onchange="getValues()" required="true"/><br/>
            <apex:inputField label="Total Adjustment Amount" value="{!comBill.Total_Adjustment_Amount__c}" required="true"/> 
            <apex:inputField label="Notes" value="{!comBill.Notes__c}" style="width: 360px; height: 100px" />         
        </apex:pageBlockSection>

        <apex:pageBlockSection title="Actions To Complete After Final Approval">
            <apex:inputCheckBox label="Backups Moved To Bill Complete" value="{!comBill.Backups_Moved_To_Bill_Complete__c}"/> 
            <apex:inputField label="Billing Status" value="{!comBill.Billing_Status__c}"/> 
            <apex:inputCheckbox label="Credit Memo Created" value="{!comBill.Credit_Memo_Created__c}"/> <br/>
            <apex:inputCheckbox label="Update Futures" value="{!comBill.Update_Futures__c}"/> 
            </apex:pageBlockSection>

                              <!-- FOR THE CASE FINDING SECTION -->

        <apex:pageBlockSection title="Case Findings">
             <apex:pageBlockTable value="{!show}" var="e" title="show" style="width: 1450px">

            <apex:column >
                <apex:inputCheckbox value="{!e.check}" />
                    <apex:actionSupport event="onclick" action="{!inIt}" rerender="none"/>
                </apex:column>

                <apex:column value="{!e.con.Name}"/>
                <apex:column value="{!e.con.DISCOVERY_AMOUNT__c}"/>
                <apex:column value="{!e.con.BILLING_BEGINS_DATE__c}"/>
                <apex:column value="{!e.con.REPORT_DESCRIPTION__c}"/>
                <apex:column value="{!e.con.CONTINGENCY__c}"/>
            </apex:pageBlockTable>
        </apex:pageBlockSection>
        </apex:pageBlock>
        </apex:form>
                            <!-- FOR THE ATTACHMENT SECTION -->
       <apex:form >
           <apex:pageBlock >
        <apex:pageBlockSection title="Attachment">
            <apex:inputFile value="{!attachment1.body}" fileName="{!attachment1.name}"/> <br/>
            <apex:inputFile value="{!attachment2.body}" fileName="{!attachment2.name}"/> <br/>
            <apex:inputFile value="{!attachment3.body}" fileName="{!attachment3.name}"/>
         </apex:pageBlockSection>

        </apex:pageBlock>   
            </apex:form>
</apex:page>

My controller extension:
public with sharing class newCom {
    //Declare variables
    public account acc{get;set;}
    public Billing_Change_Form__c comBill {get;set;}
    id acID = System.currentPagereference().getParameters().get('id');
    public list<conCase> caseList{get;set;}
    public boolean bool{get;set;}
    public set<id> caseIds{get;set;}
    ApexPages.StandardController controller;
    public string result{get;set;}
    public Attachment attachment1 { get; set; }
    public Attachment attachment2 { get; set; }
    public Attachment attachment3 { get; set; }

    //Contructor
    public newCom (ApexPages.StandardController con){
        comBill = new Billing_change_form__c();
        id acID = System.currentPagereference().getParameters().get('id');
        comBill.RecordTypeId = '0124A000001lBu9QAE';
        comBill.Account__c = acId;
         controller = con;
        caseList = new list<conCase>();
        bool = false;
        caseIds = new Set<id>();
        attachment1 = new Attachment();
        attachment2 = new Attachment();
        attachment3 = new Attachment();
    }

    //Event on clicking the checkbox
    public void inIt(){
        List<Contingency__c> selectedCase = new list<Contingency__c>();
        for(conCase conObj : caseList){
            if(conObj.check != False)
            { system.debug('conObj.con'+ conObj.con);   
             selectedCase.add(conObj.con); 
             caseIds.add(conObj.con.id); bool = true;
            }
               If(conObj.check != true) 
               {caseIds.remove(conObj.con.id); }   
    }
    }

    //Displaying the case findings records

    public List<conCase> getShow(){
        caseList = new list <conCase> ();

        for(Contingency__c coObj : [Select id, name,billing_type__c, report_description__c, discovery_amount__c,
                        billing_begins_date__c, contingency__c, VENDOR_INVOICE__r.Account_del__r.Id from Contingency__c
            where (VENDOR_INVOICE__r.Account_del__r.Id = :acID) AND (contingency__c like 'IN BILLING') 
                                   ORDER BY NAME])  
        {caseList.add(new conCase(coObj, Bool));}

        return caseList;
    }


    //Event on saving
    public PageReference comInsert(){
        // newBill.RecordTypeId = '0124A000001lBu9QAE';
        // Inserting the new record
        comBill.name = 'Nada';
        comBill.account__c = acID;
        insert comBill;   
        result = comBill.Id;

        //Inserting Case Findings
        list<Contingency__c> updateSelectedCase = new list<Contingency__c>();  
        for(Contingency__c co:[select id, name, bill_form__c from Contingency__c where id = :caseIds ])   
        {co.bill_form__c =result ;
         updateSelectedCase.add(co);}
        update updateSelectedCase;

        //Adding the attachment to the record
        List<Attachment> toInsert = new List<Attachment>();
            if(attachment1.Name != null)
            {
                attachment1.ParentId = result;
                toInsert.add(attachment1);
            }

            if(attachment2.Name != null)
            {
                attachment2.ParentId = result;
                toInsert.add(attachment2);
            }

            if(attachment3.Name != null)
            {
                attachment3.ParentId = result;
                toInsert.add(attachment3);
            }
            if(toInsert.size() > 0)


                insert toInsert;



        //Redirecting Page to new record created
        PageReference rePage = new PageReference('/'+result);
        rePage.setRedirect(true);
        rePage.getParameters().put('id',controller.getId());
        return repage;

    }

    //Event on hitting the cancel button
    public PageReference noBill(){
        comBill.Reason_for_Removal__c = 'Our Error';
        comBill.Total_Adjustment_Amount__c = 1;
        comBill.Name = 'Nada';
        PageReference pageRef = new PageReference('/'+acId);
        pageRef.setRedirect(true);
        return pageRef;
    }
    //Wrapper class for the selected records
       public class conCase{
        public contingency__c con{get;set;}
        public boolean check{get;set;}
        public conCase(contingency__c c, boolean boo){
            con = c;
            check = boo;           
        }
    }
}

​​​​​​​