Monday, January 2, 2017

Visualforce - Beyond Basics Series 39 - Modern Upload Button

How to upload an attachment to record ?

Using apex:inputFile tag, we can upload a file & store that as the attachment to the record. The master record id should be assigned to parentId for the Attachment.


What is the traditional way ?

Traditionally, developers use the same styling of inputFile as it is. That means there will be an upload button for user to select the file & there has to be a commandButton/commandLink to call the action function.


How to transform that to modern look ?

But, in a modern Upload button solution, a Upload label will be styled as a Button. Then, the inputFile tag will be inside the label & hidden from user. So, user will see only Label(Button), not the acutal inputFile.

Where is the Code ?

<apex:page standardController="Opportunity" extensions="testcls39_02012017">
<style>
.UploadBtn {
display : block;
width: 100px;
height: 30px;
padding-top: 15px;
border-radius : 5px;
border: 1px solid black;
text-align: center;
background-color: #099ad6;
cursor : pointer;
}
.UploadBtn:hover {
background-color: #d5ecf2;
}
.UploadBtn input {
display : none;
}
</style>
<apex:form id="UploadForm">
<!-- Classic Style -->
<apex:outputPanel layout="none">
<apex:sectionHeader title="Classic Style"/>
<!-- Upload button -->
<apex:inputFile value="{!att.body}" fileName="{!att.Name}"/> <br/>
<apex:commandButton value="Upload" action="{!addAttach}"/>
</apex:outputPanel>
<!-- Modern Style (Input field inside label )-->
<apex:outputPanel layout="none">
<apex:sectionHeader title="Modern Style"/>
<apex:outputLabel value="Upload" styleClass="UploadBtn">
<apex:actionFunction name="addAttach_js" action="{!addAttach}"/>
<apex:inputFile value="{!att.body}" fileName="{!att.Name}" onchange="addAttach_js();"/>
</apex:outputLabel>
</apex:outputPanel>
<!-- Upload status -->
<apex:outputText value="Attachment created successfully" rendered="{!att.Id != Null}"/>
</apex:form>
</apex:page>
view raw gistfile1.txt hosted with ❤ by GitHub
public class testcls39_02012017 {
public Attachment att {get; set;}
public testcls39_02012017(ApexPages.StandardController sc) {
att = new Attachment( ParentId = sc.getId());
}
public void addAttach() {
insert att;
}
}
view raw gistfile1.txt hosted with ❤ by GitHub
Here's the code that illustrates the traditional method & more modern method to upload the file.

Any Screenshots ?



Walk through in a video ?


No comments:

Post a Comment

Thanks for reading my blog !