Render component in primefaces by value [duplicate] - primefaces

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

Related

Primefaces KeyFilter: Not working after calling "ajax update" on h:inputText

Prime faces p:keyFilter stops working when an ajax update happens on h:inputText. Please have a look at the following example.
Expected Behavior:
p:keyFilter should allow only alphabets and numbers in inputText at any point of time.
Steps to reproduce:
1) Go directly to "Project Key" field and try entering special characters.. it will not allow.. the filter works this time.
2) Now go to "Project Name" field and then click on "Project Key". This time try entering special characters. It allows to enter. The filter does not work now.
Sample xhtml:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
</h:head>
<h:form>
<h:outputText value="Project Name:"></h:outputText>
<h:inputText id="projectName" value="#{testBean.projectName}" >
<p:ajax event="blur" listener="#{testBean.updateKey()}" update="projectKey" process="#form"></p:ajax>
</h:inputText>
<br/>
<h:outputText value="Project Key:"></h:outputText>
<h:inputText id="projectKey" value="#{testBean.projectKey}" label="Project Key" size="29" maxlength="10">
</h:inputText>
<p:keyFilter for="projectKey" mask="alphanum" />
</h:form>
</html>
Sample Managed Bean:
import javax.faces.bean.ManagedBean;
import javax.persistence.Entity;
#ManagedBean(name="testBean")
#Entity
public class Test {
private String projectName;
private String projectKey;
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectKey() {
return projectKey;
}
public void setProjectKey(String projectKey) {
this.projectKey = projectKey;
}
public void updateKey()
{
if(projectName.equals("Shivani"))
{
projectKey = "SK";
}
}
}
This error was reported to PrimeFaces: https://github.com/primefaces/primefaces/issues/3596
The bug was in the Jquery KeyFilter Plugin itself here: https://github.com/akzhan/jquery-keyfilter/issues/7
The patch has been applied and will be in PrimeFaces 6.3 and higher.
The PrimeFaces keyfilter is applied when the keyFilter is 'rendered'. The way it is applied can be seen in the source of the keyfilter.js.
In the PrimeFaces showcase (and documentation) you'll see two examples:
<p:inputText id="text1" value="....">
<p:keyFilter regEx="/[ABC]/i"/>
</p:inputText>
<h:outputText value="KeyFilter with mask on a h:inputText"/>
<h:inputText id="text2" value="..."/>
<p:keyFilter for="text2" mask="num" />
One where the p:keyFilter is nested and one where the for attribute is used. The latter will not be automatically reapplied after an update of the input, but the former will.
If you do need the non-nested way, make sure you update both the input and the keyfilter by either explicitly updating both, or nesting them both in e.g. a h:panelgroup id="inputAndFilter" and updating that.
<h:panelgroup id="inputAndFilter">
<h:inputText id="text2" value="..."/>
<p:keyFilter for="text2" mask="num" />
</ui:panelgroup>

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}" />

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.

Haw can I do for making button show me fileupload

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;

display dialogue immediately after selecting value in selectonemenu

I have a requirement with p:selectonemenu when I am using inside dataTable.
<p:selectOneMenu value="#{buyerInProcessBean.subject}"
id="buyerResponseId" >
<f:selectItems
value="#{buyerInProcessBean.subjectMap[trans.decisionrule.ruleId]}"
var="subject" itemLabel="#{subject}" itemValue="#{subject}"></f:selectItems>
<f:selectItem itemLabel="Other" itemValue="Other"></f:selectItem>
</p:selectOneMenu>
If I choose 'other' a dialogue must compulsory get popup. otherwise it is not mandatory.
How can I achieve this type of requirement?
You should bind a function to an onchange event of your <p:selectOneMenu>, find out if the value of the desired option matches the value that should open the dialog, and trigger dialog.open() in that case.
Note, that Primefaces' component wraps the <select> tag within some divs and outputs the selected <option> in an intermediary component, therefore attachment of event to the hidden <select> element won't work. On the other hand, for example, JSF <h:selectOneMenu> tag renders a <select> element, so binding behaviour to the onchange will trigger the desired behaviour.
The view:
<h:form id="form">
<p:selectOneMenu value="#{buyerInProcessBean.subject}" id="buyerResponseId" onchange="changeEvent(this)">
<f:selectItems value="#{buyerInProcessBean.subjectMap[trans.decisionrule.ruleId]}"
var="subject" itemLabel="#{subject}" itemValue="#{subject}" />
<f:selectItem itemLabel="Other" itemValue="Other" />
</p:selectOneMenu>
</h:form>
<p:dialog widgetVar="dialog">
<h:outputText value="Additional Data" />
</p:dialog>
The JavaScript:
function changeEvent(element) {
var val = $(element).find('option:selected').text();
if(val === 'Other') {
dialog.show();
}
}