Haw can I do for making button show me fileupload - primefaces

haw can I do for diplay fileupload when I press a commande button.
<p:commandButton icon="ui-icon-refresh" onclick="data.show()"></p:commandButton>
this is my Fileupload
<h:form enctype="multipart/form-data" id="t" >
<p:fileUpload auto="true" disabled="true" id="data"
fileUploadListener="#{composantbean.handleFileUpload}"
sizeLimit="2097152"
label="Choose"
allowTypes="/(\.|\/)(pdf)$/"
description="Images"/>
</h:form>
on this solution the file uplad is displayed ..haw can I do

I don't quite understand your need. You want to display the p:fileUpload only after you click the p:commandButton?
If so, you need to create a boolean variable in your bean(controller) and when clicking on the button, set it true. It would look like this:
.xhtml
<p:commandButton icon="ui-icon-refresh" action="#{testController.renderFileUpload()}" update="#this"/>
<p:fileUpload auto="true" id="data" rendered="#{testController.isRenderFU()}"
fileUploadListener="#{composantbean.handleFileUpload}"
sizeLimit="2097152"
label="Choose"
allowTypes="/(\.|\/)(pdf)$/"
description="Images"/>
testController
...
private boolean renderFU = false;
public void renderFileUpload(){
renderFU = true;
}
public boolean isRenderFU() {
return renderFU;
}
public void setRenderFU(boolean renderFU) {
this.renderFU = renderFU;

Related

Render component in primefaces by value [duplicate]

How can I show/hide component with JSF?
I am currently trying so do the same with the help of javascript but not successfull.
I cannot use any third party libraries.
Thanks| Abhi
You can actually accomplish this without JavaScript, using only JSF's rendered attribute, by enclosing the elements to be shown/hidden in a component that can itself be re-rendered, such as a panelGroup, at least in JSF2. For example, the following JSF code shows or hides one or both of two dropdown lists depending on the value of a third. An AJAX event is used to update the display:
<h:selectOneMenu value="#{workflowProcEditBean.performedBy}">
<f:selectItem itemValue="O" itemLabel="Originator" />
<f:selectItem itemValue="R" itemLabel="Role" />
<f:selectItem itemValue="E" itemLabel="Employee" />
<f:ajax event="change" execute="#this" render="perfbyselection" />
</h:selectOneMenu>
<h:panelGroup id="perfbyselection">
<h:selectOneMenu id="performedbyroleid" value="#{workflowProcEditBean.performedByRoleID}"
rendered="#{workflowProcEditBean.performedBy eq 'R'}">
<f:selectItem itemLabel="- Choose One -" itemValue="" />
<f:selectItems value="#{workflowProcEditBean.roles}" />
</h:selectOneMenu>
<h:selectOneMenu id="performedbyempid" value="#{workflowProcEditBean.performedByEmpID}"
rendered="#{workflowProcEditBean.performedBy eq 'E'}">
<f:selectItem itemLabel="- Choose One -" itemValue="" />
<f:selectItems value="#{workflowProcEditBean.employees}" />
</h:selectOneMenu>
</h:panelGroup>
Generally, you need to get a handle to the control via its clientId. This example uses a JSF2 Facelets view with a request-scope binding to get a handle to the other control:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head><title>Show/Hide</title></h:head>
<h:body>
<h:form>
<h:button value="toggle"
onclick="toggle('#{requestScope.foo.clientId}'); return false;" />
<h:inputText binding="#{requestScope.foo}" id="x" style="display: block" />
</h:form>
<script type="text/javascript">
function toggle(id) {
var element = document.getElementById(id);
if(element.style.display == 'block') {
element.style.display = 'none';
} else {
element.style.display = 'block'
}
}
</script>
</h:body>
</html>
Exactly how you do this will depend on the version of JSF you're working on. See this blog post for older JSF versions: JSF: working with component identifiers.
Use the "rendered" attribute available on most if not all tags in the h-namespace.
<h:outputText value="Hi George" rendered="#{Person.name == 'George'}" />
You should use <h:panelGroup ...> tag with attribute rendered. If you set true to rendered, the content of <h:panelGroup ...> won't be shown. Your XHTML file should have something like this:
<h:panelGroup rendered="#{userBean.showPassword}">
<h:outputText id="password" value="#{userBean.password}"/>
</h:panelGroup>
UserBean.java:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class UserBean implements Serializable{
private boolean showPassword = false;
private String password = "";
public boolean isShowPassword(){
return showPassword;
}
public void setPassword(password){
this.password = password;
}
public String getPassword(){
return this.password;
}
}
One obvious solution would be to use javascript (which is not JSF). To implement this by JSF you should use AJAX. In this example, I use a radio button group to show and hide two set of components. In the back bean, I define a boolean switch.
private boolean switchComponents;
public boolean isSwitchComponents() {
return switchComponents;
}
public void setSwitchComponents(boolean switchComponents) {
this.switchComponents = switchComponents;
}
When the switch is true, one set of components will be shown and when it is false the other set will be shown.
<h:selectOneRadio value="#{backbean.switchValue}">
<f:selectItem itemLabel="showComponentSetOne" itemValue='true'/>
<f:selectItem itemLabel="showComponentSetTwo" itemValue='false'/>
<f:ajax event="change" execute="#this" render="componentsRoot"/>
</h:selectOneRadio>
<H:panelGroup id="componentsRoot">
<h:panelGroup rendered="#{backbean.switchValue}">
<!--switchValue to be shown on switch value == true-->
</h:panelGroup>
<h:panelGroup rendered="#{!backbean.switchValue}">
<!--switchValue to be shown on switch value == false-->
</h:panelGroup>
</H:panelGroup>
Note: on the ajax event we render components root. because components which are not rendered in the first place can't be re-rendered on the ajax event.
Also, note that if the "componentsRoot" and radio buttons are under different component hierarchy. you should reference it from the root (form root).
check this below code.
this is for dropdown menu. In this if we select others then the text box will show otherwise text box will hide.
function show_txt(arg,arg1)
{
if(document.getElementById(arg).value=='other')
{
document.getElementById(arg1).style.display="block";
document.getElementById(arg).style.display="none";
}
else
{
document.getElementById(arg).style.display="block";
document.getElementById(arg1).style.display="none";
}
}
The HTML code here :
<select id="arg" onChange="show_txt('arg','arg1');">
<option>yes</option>
<option>No</option>
<option>Other</option>
</select>
<input type="text" id="arg1" style="display:none;">
or you can check this link
click here

primefaces dialog framework: close dialog "onclick"

I show a Primefaces Dialog using the dialog framework, in this way:
RequestContext.getCurrentInstance().openDialog("myDialog", options, params);
In the page myDialog.xhtml I have a message and two buttons: YES or NO.
I would like to close the Pf dialog with the event "onclick", is there a way the to do this?
I cannot statically define the dialog using p:dialog and than close it using PF('widgetVarName').hide();
Generally, you may want something like this:
<p:commandButton action="#{someBean.closeDialog('yes')}" process="#form" update="#form"
icon="#{icons.yes}" value="#{bundle.yes}" />
<p:commandButton action="#{someBean.closeDialog('no')}" process="#form" update="#form"
icon="#{icons.no}" value="#{bundle.no}" />
public void closeDialog(String choice)
{
RequestContext requestContext = RequestContext.getCurrentInstance();
Object someData = executeChoice(choice);
requestContext.closeDialog(someData);
}
Otherwise, if you really need to close the dialog on onclick (sounds a little strange...) you may use:
<p:remoteCommand name="closeDialog" action="#{someBean.closeDialog}" process="#this" />
<p:commandButton type="button" onclick="closeDialog()" icon="#{icons.close}"
value="#{bundle.close}" />
public void closeDialog()
{
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.closeDialog(null);
}
Finally, if you need a pure javascript solution, you may want:
<p:commandButton type="button"
onclick="PrimeFaces.closeDialog({pfdlgcid:'#{param.pfdlgcid}'})"
icon="#{icons.close}" value="#{bundle.close}" />

Validation Message from the fleUploadListener not showing inside a `<p:dialog>`

I have a <p:dialog> in which I am uploading a file.
<p:dialog id="uploadFileDialog"
header="Upload File" widgetVar="uploadFileDialog"
modal="true" minHeight="40">
<p:messages id="fileUploadMsgs" showDetail="true" autoUpdate="true"
closable="true" redisplay="false"/>
<p:fileUpload id="uploadFile" mode="advanced"
multiple="false" allowTypes="/(\.|\/)(docx|doc|pdf)$/"
fileUploadListener="#{testMB.uploadFileListener}"
auto="false" onstart="PF('ajaxStatusDialog').show()"
oncomplete="PF('ajaxStatusDialog').hide()">
</p:fileUpload>
</p:dialog>
In the file Upload Listener I'm looking if a file already exists in the Database, if it does I need to throw and error back in the dialog box. I tried setting globalOnly="true" and passing the client id as null in RequestContext.getCurrentInstance().addMessage, but it didn't work. I even tried passing the id of <p:messages> in addMessage, that didn't work too. Any help is highly appreciated.
Edit: My code for fileUploadListener
public void uploadFileListener(FileUploadEvent event){
boolean success = false;
List<Files> fileList = getDbFilesList();
if(fileList == null){
success = handleDocumentUpload(event);
}else{
success = false;
FacesContext.getCurrentInstance().addMessage(
"fileUploadMsgs",
new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Error : ",
"File Already Exists."));
}
}
I am using primefaces 5.2 and jsf 2.2. Thanks!
I have figured out a way to make it work. Please see the updated code below.
<p:dialog id="uploadFileDialog"
header="Upload File" widgetVar="uploadFileDialog"
modal="true" minHeight="40">
<h:form id="testForm>
<p:messages id="fileUploadMsgs" showDetail="true" autoUpdate="true"
closable="true" redisplay="true"/>
<p:fileUpload id="uploadFile" mode="advanced"
multiple="false" allowTypes="/(\.|\/)(docx|doc|pdf)$/"
fileUploadListener="#{testMB.uploadFileListener}"
auto="false" onstart="PF('ajaxStatusDialog').show()"
oncomplete="PF('ajaxStatusDialog').hide()" update="fileUploadMsgs">
</p:fileUpload>
</h:form>
</p:dialog>
The code for File upload listener is as below :
public void uploadFileListener(FileUploadEvent event){
boolean success = false;
List<Files> fileList = getDbFilesList();
if(fileList == null){
success = handleDocumentUpload(event);
}else{
success = false;
FacesContext.getCurrentInstance().addMessage(
"testForm:uploadFile",
new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Error : ",
"File Already Exists."));
}
}

Why can't I update a p:graphicImage twice after upload a file with p:uploadFile

I have been trying to upload an image with a p:uploadFile and it work fine at first time, but after the first uploaded file it not update the p:graphicImage, but if I reload the page the value of the graphicImage is fine and the image is showed. So, I think that is a problem with the primefaces uploadFile component, but I not sure.
My xhtml is this:
<h:form id="formNuevo" size="150%" enctype="multipart/form-data">
<h:outputLabel value="Diseño Neumatico: *" />
<p:fileUpload fileUploadListener="#{serviciosVentanaDiseno.manejarUploadedFile}" mode="advanced" auto="true" sizeLimit="9000000000" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" update="mensajes graficImage"/>
<p:graphicImage id="graficImage" styleClass="disenoNeumatico" value="#{serviciosVentanaDiseno.streamedContentImagen}" ajax="true"/>
</h:form>
and my bean is a #SessionScoped bean, it's here:
public void manejarUploadedFile(FileUploadEvent event) {
UploadedFile uploadedFile = (UploadedFile)event.getFile();
try {
diseno.setImagen(uploadedFile.getContents());
streamedContentImagen = new DefaultStreamedContent(new ByteArrayInputStream(diseno.getImagen()));
} catch (IOException e) {
//log error
}
}
public StreamedContent getStreamedContentImagen() {
return streamedContentImagen;
}
public void setStreamedContentImagen(StreamedContent streamedContentImagen) {
this.streamedContentImagen = streamedContentImagen;
}
Try setting the cache attribute of the graphicImage component to false:
<p:graphicImage cache="false"
change scope #SessionScoped then <p:graphicImage cache="false">

Update the page with command bouton primefaces

I want to get the value of the input Textarea and show it in the same page by clicking on the command button "compiler "
however i don't get any result ! and the contnet is only shown when I update with the browser updater
Sh How do I upate the page and the managed beans to show the content of a primefaces textarea in the same page
this is the code:
<p:layoutUnit position="west" size="520" header="Code à executer" resizable="true" >
<h:form id="moncode">
<p:inputTextarea id="mycode" value="#{fichier.code}" rows="17" cols="50" />
<p:commandButton value="compiler" id="btn3" action="guest.xhtml" styleClass="myButtonClass" />
</h:form>
</p:layoutUnit>
<p:layoutUnit position="east" size="550" header="Resultat d'execution" resizable="true" >
<h:outputText value="#{fichier.code}" />
</p:layoutUnit>
<p:layoutUnit position="south" >
my application is about compiling a given code: I write a code and then I executed with the button "compiler" so a file will be created however the file is always created with "null" and I think because the var "code" is not yet set in the managed bean that why I want to update the page so the managed bean ill be set here is compile:
`
private String code;
private String error;
public String getCode() {
return code;
}
public String getError() {
return error;
}
public void setCode(String code) {
this.code = code;
}
public void compile() throws IOException {
File file = new File("C:\\Users\\Rad1\\test.c");
PrintWriter ecrivain;
ecrivain = new PrintWriter(new BufferedWriter (new FileWriter(file)));
ecrivain.println(code);
ecrivain.close();
`
There are two ways to achieve what you want: either by using a synchronous submit of a form with a subsequesnt postback, or by sending an AJAX request to partially update necessary parts of the page.
Synchronous submit
<p:inputTextarea id="mycode" value="#{fichier.code}" rows="17" cols="50" />
<p:commandButton value="compiler" id="btn3" action="#{fichier.action}" styleClass="myButtonClass" ajax="false" />
<h:outputText id="upd" value="#{fichier.code}" />
with action method
public String action() {
//do business job
return null;
}
This way a fields will be refreshed by making a postback. Don't forget that the bean Fichier must be view scoped. Note the ajax="false" attribute of <p:commandButton>.
AJAX call
<p:inputTextarea id="mycode" value="#{fichier.code}" rows="17" cols="50" />
<p:commandButton value="compiler" id="btn3" action="#{fichier.action}" styleClass="myButtonClass" update="upd" />
<h:outputText id="upd" value="#{fichier.code}" />
with the same action method
public String action() {
//do business job
return null;
}
This way only the contents of <h:outputText> will be updated after AJAX call is finished. Don't forget that the bean Fichier should also be view scoped. Note that id attribute of <h:outputText> must be specified.
Actually, you don't call the action itself. Your action forwards to a certain page. There is no race condition or syncronization problems in a JSF action betwwen setting the properties and the action itself. I recommend you to read JSF life cycles tutorial by BalusC Aplly request values phase run before the action.
Try to call action on command Button.
<p:commandButton value="compiler" id="btn3" action="#{fichier.compile}" update="outputCode" styleClass="myButtonClass" />
Add an id attribute to your output panel and specify it in the action button.
<p:layoutUnit id="outputCode" position="east" size="550" header="Resultat d'execution" resizable="true" >
<h:outputText value="#{fichier.code}" />
</p:layoutUnit>
P.S. It is also good to read this BalusC answer for better understanding of actions, Ajax/non Ajax request etc.