You need to sign in to do that
Don't have an account?
![Shakespeare Shakespeare](https://dfc-org-production.my.site.com/img/userprofile/default_profile_45_v2.png)
How to add attachment in custom controller
Hi, I am trying to make an attachment page on one of my custom pages. I am unable to find any totorial for this particular purpose. Can somebody please refer me to some tutorial that associates an attachment to the custom objects and controls.
I came accross teh follwoing example of uploading attachments. I am unable to run this code because I dont find any option to create the extension for the standardController-Document
<apex:page standardController="Document" extensions="documentExt"> <-- Upload a file and put it in your personal documents folder--> <apex:messages /> <apex:form id="theForm"> <apex:pageBlock> <apex:pageBlockSection> <apex:inputFile value="{!document.body}" filename="{!document.name}"/> <apex:commandButton value="save" action="{!save}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page> /*** Controller ***/ public class documentExt { Appendix D: Standard Component Reference inputFile public documentExt(ApexPages.StandardController controller) { Document d = (Document) controller.getRecord(); d.folderid = UserInfo.getUserId(); //this puts it in My Personal Documents } }
Can someone please help me in:
1- How can I associate an attachments to my records when I am working with a custom controller (some code or step by step tutorial).
2- How can I add an extension when I am using a standard controlle
Hi Shakespeare,
I'm not sure I totally understand your question, but it seems like you are trying to create a page from which you can upload attachments. If that's the case, here's some code that should work:
Here's the controller code:
public class FileUploadController
{
private String fileName;
private Integer fileSize;
private Blob fileBody;
public FileUploadController(ApexPages.StandardController controller)
{
}
public FileUploadController()
{
}
public String getFileName()
{
return this.fileName;
}
public void setFileName(String fileName)
{
this.fileName = fileName;
}
public Blob getFileBody()
{
return this.fileBody;
}
public void setFileBody(Blob fileBody)
{
this.fileBody = fileBody;
setFileSize(this.fileBody.size());
}
public Integer getFileSize()
{
return this.fileSize;
}
public void setFileSize(Integer fileSize)
{
this.fileSize = fileSize;
}
private Database.SaveResult insertCustomObject()
{
CustomObj__c custObj = new CustomObj__c();
// fill out cust obj fields
return Database.insert(custObj);
}
private Database.SaveResult insertAttachment(Id parentId)
{
Database.SaveResult result;
Attachment attachment = new Attachment();
attachment.Body = this.fileBody;
attachment.Name = this.fileName;
attachment.ParentId = parentId;
result = Database.insert(attachment);
fileBody = Blob.valueOf(' ');
return result;
}
public PageReference processUpload()
{
try
{
Database.SaveResult result = insertCustomObj();
if (result == null || !result.isSuccess())
{
return null;
}
result = insertAttachment(result.getId());
if (result == null || !result.isSuccess())
{
return null;
}
}
catch (Exception e)
{
ApexPages.AddMessages(e);
}
return returnUrl();
}
}
If I understand you question #1 correctly, one thing you can do is create a String field on your custom object, and store the Id of the newly created Attachment there. It's not quite as useful as having a lookup field to the Attachment in your custom object, but that's not possible.
I hope this helps.
Andrew
Hi Andrew,
Thank you very much for your help, using this code I have successfully uploaded the file. Since I am new to visualforce, - I suprise that how do I verify that files have been uploaded, where to find the file?
- My categoric requirement is "to provide the user with a link on Contact page; clicking the link will open a popup visualforce page, where user will be able to browse a file and attach it with the Contact. Also he should be able to delete any previously added attachment and then attach the new one."
By the way, there were a couple of errors in the class code, that I have ractified and pasting them here.
I really appriciate your help.
Thanks,
Shakespeare
Body Download Apex public class FileUploadController { public FileUploadController(PixelReqFormAttachCont controller) { } private String fileName; private Integer fileSize; private Blob fileBody; public FileUploadController(ApexPages.StandardController controller) { } public FileUploadController1() { } public String getFileName() { return this.fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public Blob getFileBody() { return this.fileBody; } public void setFileBody(Blob fileBody) { this.fileBody = fileBody; setFileSize(this.fileBody.size()); } public Integer getFileSize() { return this.fileSize; } public void setFileSize(Integer fileSize) { this.fileSize = fileSize; } private Database.SaveResult insertCustomObject() { CustomObj__c custObj = new CustomObj__c(); // fill out cust obj fields return Database.insert(custObj); } private Database.SaveResult insertAttachment(Id parentId) { Database.SaveResult result; Attachment attachment = new Attachment(); attachment.Body = this.fileBody; attachment.Name = this.fileName; attachment.ParentId = parentId; result = Database.insert(attachment); fileBody = Blob.valueOf(' '); return result; } public PageReference processUpload() { try { Database.SaveResult result = insertCustomObject(); if (result == null || !result.isSuccess()) { return null; } result = insertAttachment(result.getId()); if (result == null || !result.isSuccess()) { return null; } } catch (Exception e) { ApexPages.AddMessages(e); } return null; } }
Just to add,
- How can I display the attachments (against that contact) , when VF popup is opened?.
- How to delete that attachment?
- And how to recieve/get the attachmentID in order to save/diplay the attachment against that contract?
Thanks,
Shakespeare
Hi Shakespeare,
There is a correct way to do what you want to do. You can attach files to attachments directly on the Contact detail page via the 'Notes & Attachments' related list. See the documentation to find out how to put the 'Notes & Attachments' related list on your Contact page layout. I don't feel qualified to advise you further since I am also new to Apex coding.
Andrew
Thank you very much for your help Andrew. In fact I did not know that a built in Notes and Attachment pane is there. It has resolved my problem.
Regards,
Shakespeare
Hi,
I'm working in file upload and I came across with this post.
Your variables are marked private, don't they have to be public so it can be accessed in the visualforce page?
After I choose the file to upload, can I use the values in the variables fileName and fileBody in the Controller class without making any insert statement? I keep getting the value null in both of them...
Can you please give me some insight on this?
Thank you very much!
Hi Joana,
The variables are marked private, but they are accessible from the visual force page via the getters and setters. You can access them without the 'get/set' like this {!fileName}.You can use the value of the fileName variable in the controller, but I believe that Apex does not make available the data in a blob object, so you can't access the fileBody, only upload it.
Andrew
Thank's for the quick reply.
I'm trying to build a complex solution. I need to save the attachments associated with a case in an external system (through webservice) and then erase them from salesforce. This is already working with a visualforce page accessed through a custom button in Cases. But then, in that same page, users can upload a file from the disk to save them to that external system - so I don´t want to save the uploaded file in Salesforce, I only want to get the name and blob to send them to a webservice.
The problem is that I keep getting the value null in my "fileName" and "fileBody" variables... Any thoughts on this?
Here's a sample of my code: (by the way, I can only call the method "criarDoc()" with an actionFunction, it's not working with commandButton...)
public class CC_TipificarDocumentosController {
public void criarDoc(){
System.debug('\n\n\n################### fileName:' + fileName);
}
}
<apex:page controller="CC_TipificarDocumentosController" >
<apex:form >
<apex:actionFunction name="criarDoc" action="{!criarDoc}" />
<apex:inputFile title="Procurar" value="{!fileBody}" filename="{!fileName}" id="inpFile"/>
<apex:commandButton value="Ok" action="{!criarDoc}" />
<input type="submit" value="Ok" onclick="criarDoc(); " />
</apex:form>
</apex:page>
Hi Joana,
I am not an expert, and maybe one of the gurus on this discussion board can confirm this, but I believe that there is no way to access the bits contained in a Salesforce blob object. It seems that this is what you are trying to do - read the data bits in a SFDC attachment and upload to external storage.
You might be able to load the attachment blob, and assign it to another attachment, essentially copying the attachment to another attachment, but to upload it externally you would need some mechanism to read the data into a buffer, and I don't know that there is away to do that.
Andrew
Ok, I'll try a different approach then.
Thank's for your help!
Hi AndrewX,
Your post is really awesome. It is really a great savior for me I had a similar requirement where I was getting and setting file from web service external system. This has help me lot. I wish I could give 10 kudos :P
Thanks again for the great post.
Regards,
After looking so many posts for what i am looking , this is litte bit related to what i am looking for...........
I have Created a VF Page where the External User fill there contact details using Sites and there is also a Document attached to this Page where the External user has to attach the document .
When the User fill the Information and attach the document and click on Submit it is throwing the Error as below............
You must first log in or register before accessing this page.
If you have forgotten your password, click Forgot Password to reset it.
can't able to figure it out.
Could you please help me out....................
Any idea.......
Regards
Micky