Skip to main content

Add Attachment and Create a Record on the Same Visualforce Page

This article explains how you can upload an attachment while creating a new record to any SObject using Visualforce.

Salesforce.com desktop screenshot
Salesforce1 mobile screenshots
 ------------------------------------------------------------------------------------------------------------

Visualforce Page

<apex:page controller="SafetyObservationExtensionController" >
<apex:messages />
    <apex:form id="theForm">
        <apex:pageBlock title="New Safety Observation Form">
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton action="{!cancel}" value="Cancel"/>
                <apex:commandButton action="{!save}" value="Submit"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection columns="1">
                <apex:inputField label="Account" value="{!safetyObs.Account__c}"/>
                <apex:inputField label="Date & Time" value="{!safetyObs.Date_Time__c}"/>
                <apex:inputField label="Operations" value="{!safetyObs.Operations__c}"/>
                <!-- <apex:inputField label="Location" value="{!Safety_Observation__c.Location__c}"/> -->
                <apex:inputField label="Observation Type" value="{!safetyObs.Type__c}"/>
                <apex:inputField label="Risk" value="{!safetyObs.Risk__c}"/>
                <apex:inputFile value="{!attachment.body}" filename="{!attachment.name}"/>
            </apex:pageBlockSection>
            <apex:repeat value="{!safetyObs.attachments}" var="attachment">
                <apex:image height="200px" value="{!URLFOR($Action.Attachment.Download, attachment.Id)}"/><p/>
            </apex:repeat>
        </apex:pageBlock>
    </apex:form>
</apex:page>

------------------------------------------------------------------------------------------------------------

Apex Class

public class SafetyObservationExtensionController {

    private final Safety_Observation__c safetyObs;

    public Attachment attachment {
        get {
            if (attachment == null) attachment = new Attachment();
            return attachment;
        }

        set;
    }

    public SafetyObservationExtensionController (ApexPages.StandardController stdController)
    {
        safetyObs = (Safety_Observation__c)stdController.getRecord();
    }

    public PageReference save() {
        insert safetyObs;
        attachment.parentId = safetyObs.Id;
        insert attachment;
     
        PageReference page = ApexPages.currentPage();
        page.setRedirect(true);
        return page;
     }
}

------------------------------------------------------------------------------------------------------------

If you want to attach the uploads to a new, not yet extant record, make the attachment variable belong to the controller, not just scoped within the upload function. Then the attachment remains as part of the controller until the controller finally runs save().

Within your controller's save() function you do this:

insert myNewRecord;
attachment.parentId = myNewRecord.Id
insert attachment;

So within save(), you're creating the new record of the object type related to the controller. Once you insert it, you have an idea. Now apply that ID to the attachment.

Voila!

Note that the above class will return to the input page and will not return to the record detail page upon save. If you want the latter, change the page reference from:

PageReference page = ApexPages.currentPage();
-- to --
PageReference page = new PageReference('/'+safetyObs.id);

Comments

Popular posts from this blog

How to create a custom button to open Visualforce page

Let's say that you are working in a large Org and different groups throughout the company use the same object, but each a little differently. Instead of overriding the standard "Edit" or "New" buttons, create a custom button. For example, there is a custom object on the standard Opportunity object and you want to launch a different page layout for your sales team for a custom quoting object. Create your "Quote" Visualforce page. Create the custom button on the custom object. Label: New API Name: New_Quote Type: List Button Content Source: OnClick JavaScript Behavior: Execute JavaScript Button or Link URL: window.open("/apex/InputVisualforcePageNameHere?RecordType=InputRecordTypeIdHere&retURL={!Opportunity.Id}&cancelURL={!Opportunity.Id}&saveURL={!Opportunity.Id}","_parent"); Edit the Opportunity page layout for the sales team and modify the buttons on the related list to add your custom button. In ...

How to Format Number or Currency Values in Conga (Word)

Formatting Number Values The number formatting parameter begins with \#, followed by any combination of the following parameters.  Please see the examples following this table. When Conga Composer populates a numeric value, the digit grouping symbol (the “thousands separator”) is defined according to your Locale settings (as defined in Salesforce’s Setup | Personal Information) or according to the Culture or CurrencyCulture Conga Composer parameter. Despite the cultural settings that govern the output from Conga Composer, within an appearance parameter, you must use a comma (",") for the digit grouping symbol (for thousands) and a period (".") as the decimal symbol. ​   PARAMETER DESCRIPTION 0 (zero) Specifies the requisite numeric places to display in the result. If the result does not include a digit in that place, Word displays a 0 (zero). Example: { = 4 + 5 \# 00.00 } displays "09.00". # Specifies the requisite numeric places to display in the r...

How to create the Conga Composer Button

Create  a Custom Conga Composer Button Conga Composer includes sample buttons on the following standard objects so you can easily copy and paste the base URL into your button.  Lead   Contact Account Opportunity Case Contract                       ​From Setup, click  Customize , select one of the above standard objects and click  Buttons, Links, and Actions ​Click on the  Conga Composer  button and copy the four lines in the Button or Link URL field 3. Click back to the main Buttons, Links, and Actions menu and click  New Button or Link      ​4. For the label, enter something that will describe the kind of document you will create     with Conga Composer, i.e. "AccountPlan" or "Invoice" ​5. For the Display type, choose either a  Detail Page Link  or a  Detail Page Button ​6. In the Button or Link URL text box, paste th...