I am trying to create a VF page using which I can attach files and save it to notes and attachment object. I am almost close but there is some problem with the code. I am using input file tag to get the attachment and insert the attachment in extension. But I get an error saying – apex:inputFile can not be used in conjunction with an action component, apex:commandButton or apex:commandLink that specifies a rerender or oncomplete attribute.
I am doing this on a sample custom object that i created – test_Object2__c
VF page:
<apex:page standardController="test_Object2__c" extensions="testobject2">
<apex:form >
<apex:commandButton action="{!savetest}" value="Save" id="theButton" rerender="test"/>
Name <apex:inputfield label="Name" value="{!testobj2.Name}"/>
<apex:outputpanel id="test">
<!-- some code which I rerender , I have to rerender this block when I click save, so I cannot do it in any other way
-->
</apex:outputpanel>
</apex:form>
<apex:form >
Attachment <apex:inputfile value="{!myfile.body}" filename="{!myfile.Name}" />
</apex:form>
</apex:page>
Extension:
public class testobject2 {
public test_Object2__c testobj2{get;set;}
public blob attc{get;set;}
private Attachment myfile;
public Attachment getmyfile() {
myfile = new Attachment();
return myfile;
}
public testobject2(ApexPages.StandardController controller) {
this.testobj2 = (test_Object2__c) controller.getrecord();
}
public pagereference savetest(){
insert testobj2;
system.debug('******************' + attc );
Attachment a = new Attachment(parentid=testobj2.id, Name = myfile.name , Body = myfile.body);
insert a;
return null;
}
}
If I remove rerender in the save commandbutton syntax then I am able to create the attachment but If I use rerender I get the error. For my requirement I have some essential code which I rerender when I click save so I can not remove rerender attribute. Is there any other way to do this.
Best Answer
Do something like this:
Visualforce Page:
Controller: