Let's say I have a simple method that, like this:
public String test()
{
return "hello";
}
Now let's say I have the following PrimeFace component:
<p:fieldset styleClass="containers" rendered="#{controller.test()}">
<h2>Testing</h2>
<p:outputLabel for="test" value="Test" />
<p:inputText id="test" />
</p:fieldset>
The method above returns "hello". I would like to dynamically show and hide that fieldSet by comparing the returned value of that method to a field of one of my beans. For instance, on the rendered parameter, I would like to do something like: controller.test() != "some variable" which would return true or false. Am I allow to do that? If not, what is the way of doing it?
Basically the goal is to dynamically show and hide some container by comparing the returned value of a method with a bean property.
Look Like you misunderstood rendered
The rendered Attribute
A component tag uses a Boolean EL expression, along with the rendered
attribute, to determine whether or not the component will be rendered.
If you will check above definition you will know what exactly is the use of this attribute.
More you can see below
The rendered attribute which uses Boolean EL expression indicates
whether a component is currently visible or not. The property is
useful when you want to hide components for specific users or based on
condition. The default value of rendered attribute is true.
<h:outputText value=”mapping” rendered=”Boolean EL expression” />
For example, the commandLink component in the following section of a page is not rendered if the cart contains no items:
<h:commandLink id="check"
...
rendered="#{cart.numberOfItems > 0}">
<h:outputText
value="#{bundle.CartCheck}"/>
</h:commandLink>
With your concrete problem you can do like this
Make a String variable call value
Now create get/set methods for above variable
Now in your test method you can add
public void test(){
value="hello";
}
Bur remember you have call test() method of page load
Now in your Xhtml or Jsf or Jsp page
rendered="#{controller.value != 'hello'}"
Or better way create a Boolean variable and do all the magic of hide and show the component
Related
How can I pass current selected row to JavaScript function in <p:ajax oncomplete>?
<p:dataTable value="#{bolt.sites}" var="bolt" selection="#{bolt.selectedSite}" ...>
<p:ajax event="rowSelect" oncomplete="alert(#{bolt.selectedSite.name});" />
I have tried all: #{bolt.selectedSite.name}, #{bolt.name}.
EL expressions in oncomplete attribute are not evaluated after invoking the action. They are already evaluated while rendering the JavaScript code containing that ajax calling logic.
Your best bet is adding a listener method which adds the name as a callback parameter via RequestContext#addCallbackParam() which will then be available as a property of the implicit args object inside oncomplete context.
<p:ajax ... listener="#{bean.select}" oncomplete="alert(args.name)" />
public void select() {
String name = selectedSite.getName();
RequestContext.getCurrentInstance().addCallbackParam("name", name);
}
Unrelated to the concrete problem, you have a syntax error in your initial JavaScript attempt. The property name "name" suggests that it's a string. In JavaScript, all string values should be quoted. So your fictive solution would be oncomplete="alert('#{bolt.selectedSite.name}');"
I try to do something that is very similar to this richfaces example. I have a form that describes custom ID validation in case that you have not selected one of the predefined ones, else the form will be disabled. So disabled expression for the form members would go to the next method:
public boolean isPredefinedValidator() {
return !currentProjectRegField.getIdValidation().getIdType().equals(IdValidatorType.NONE);
}
that is invoked like this:
disabled="#{accountHome.isPredefinedValidator()}"
and here is the selector for the predefined validator:
<h:selectOneMenu value="#{accountHome.currentProjectRegField.idValidation.idType}"
rendered="#{!(empty accountHome.currentProjectRegField or empty accountHome.currentProjectRegField.idValidation)}">
<a4j:support event="onchange" reRender="customIdValidator"/>
<s:convertEnum />
<s:enumItem enumValue="NONE" label="#{messages['IdValidatorType_enum.NONE']}"/>
<s:enumItem enumValue="USA_ID" label="#{messages['IdValidatorType_enum.USA_ID']}"/>
<s:enumItem enumValue="MEXICO_ID" label="#{messages['IdValidatorType_enum.MEXICO_ID']}"/>
</h:selectOneMenu>
The issue is, when the method isPredefinedValidator() is invoked on a4j rerender (on disabled EL), I receive NPE.
Caused by: java.lang.NullPointerException
at com.whatever.something.action.AccountHome.isPredefinedValidator(AccountHome.java)
And when I try to debug - turns out that the value that has been set from the selectOneMenu is null.
Does it mean that reRender and setting value to the variable happens async, and there is a race condition? And what is the correct solution for this case?
Some black-magic configuration in the rich:modalPanel that contains the h:selectOneMenu resolved this issue. It goes like this <rich:modalPanel ... domElementAttachment="form">
I know how to write out individual cookies from facelets:
JSF:
<h:outputText value="#{facesContext.externalContext.requestCookieMap['TESTCOOKIE'].value}" />
Outputs:
MyCookieValue
I have been able to write out map, but the output is not the values but a reference to the value.
JSF:
<h:outputText value="#{facesContext.externalContext.requestCookieMap}" />
Output:
{DEFAULTUSERNAME=javax.servlet.http.Cookie#36a236a2,
TESTCOOKIE=javax.servlet.http.Cookie#36b436b4,
JSESSIONID=javax.servlet.http.Cookie#36d836d8}
You don't need such a long value expression to access your cookies in JSF 2.0, there is an implicit object named cookie which references the cookie map and it's equivalent to facesContext.externalContext.requestCookieMap.
So, following code:
<h:outputText value="#{cookie['TESTCOOKIE'].value}" />
should output the same as:
<h:outputText value="#{facesContext.externalContext.requestCookieMap['TESTCOOKIE'].value}" />
Now, if you want to iterate through all of them, my recommendation is to use backing bean:
#RequestScoped
#ManagedBean(name = "triky")
public class TrikyBean {
public List getCookies() {
FacesContext context = FacesContext.getCurrentInstance();
Map cookieMap = context.getExternalContext().getRequestCookieMap();
return new ArrayList(cookieMap.values());
}
}
And then use it like this
<ui:repeat value="#{triky.cookies}" var="ck">
#{ck.name}: #{ck.value}<br/>
</ui:repeat>
Clarification: This comes from the fact that the <ui:repeat /> tag will only accept java.util.List in its value attribute, otherwise it will create its own ListModel with just one element inside. Besides, the collection given by the default implementation of the values() method in a java.util.Map is not a java.util.List but a java.util.Set, so, the <ui:repeat/> tag was using that set as the only element of its own list model and when iterating through that list model the number of elements was just one and none of them were actually cookies.
Maps have a values() method that returns a collection of all elements. I think you need a stronger EL engine than the default to do method invocation outside of getters to do that though, like JBoss EL or JUEL (both of which i strongly recommend for any java ee 6 project).
The alternative is doing method invocation in java and supplying a getter like this:
myBean.java
public Collection getCookies(){
return FacesContext.getCurrentInstance().getExternalContext().getRequestCookieMap().values();
}
And iterating over the collection in your markup
<ui:repeat value="#{myBean.cookies}" var="cookie">
<p>#{cookie.name}: #{cookie.value</p>
</ui:repeat>
Haven't tried this out but something similar will work. You might have to replace the Collection with a List, not sure if ui:repeat supports Collections.
EDIT: as per the comment below, you could try this:
<ui:repeat value="#{facesContext.externalContext.requestCookieMap.values()}" var="cookie">
<p>#{cookie.name}: #{cookie.value</p>
</ui:repeat>
The conditional operator works in many attributes like "rendered" "value" and others.
But it does not work in action? Or am I doing it wrong?
<h:commandLink action="#{true ? bean.methodTrue() : bean.methodFalse()}"/>
Error: javax.el.ELException: Not a Valid Method Expression
(I realized it using primefaces ajax action attribute)
This is not supported. The action attribute is supposed to be a MethodExpression, but the conditional operator makes it a ValueExpression syntax. I don't think this will ever be supported for MethodExpressions in EL.
You have basically 2 options:
Create a single action method which delegates the job.
<h:commandButton ... action="#{bean.method}" />
with
public String method() {
return condition ? methodTrue() : methodFalse();
}
If necessary, pass it in as method argument by #{bean.method(condition)}.
Or, conditionally render 2 buttons.
<h:commandButton ... action="#{bean.methodTrue}" rendered="#{bean.condition}" />
<h:commandButton ... action="#{bean.methodFalse}" rendered="#{not bean.conditon}" />
When i tried to send some values with h:commandButton... i recieved null value in the bean...
my xhtml code is:
<p:commandButton action="#{favouriteAction.setFavourite}" value="Add as Favorite" rendered="#{favouriteBean.favouriteButton}">
<f:setPropertyActionListener target="#{favouriteAction.ngoID}" value="#{InsertDataDaoService.ngo_id}"></f:setPropertyActionListener>
</p:commandButton>
In the backing bean i just tried to print the value which i passed with my command button,but it becomes null...
In favouriteAction.java(My backing Bean)
public Integer ngoID;
public Integer getNgoID() {
return ngoID;
}
public void setNgoID(Integer ngoID) {
this.ngoID = ngoID;
}
public String setFavourite(){
System.out.println("Ngo id: "+ngoID);
System.out.println("Ngo id: "+getNgoID);
return "";
}
In console i dint get any exceptions, my o/p is
Ngo id: 0
Ngo id: 0
that is null, and it doesnt get passed..
The <f:setPropertyActionListener> is evaluated during the request of the form submit, not during the request of displaying the form. So if its value #{InsertDataDaoService.ngo_id} is not preserved for that request, then it will fail.
You have basically 2 options:
Ensure that #{InsertDataDaoService.ngo_id} is preserved for the request of the form submit. How exactly do to that depends on the functional requirements which are not clear from the question. But generally, putting the #{InsertDataDaoService} bean in the view scope by #ViewScoped and making sure that you aren't doing any business job in the getter method should be sufficient.
Replace <f:setPropertyActionListener> by <f:param> with #ManagedProperty.
<p:commandButton action="#{favouriteAction.setFavourite}" value="Add as Favorite" rendered="#{favouriteBean.favouriteButton}">
<f:param name="ngoID" value="#{InsertDataDaoService.ngo_id}" />
</p:commandButton>
with
#ManagedProperty("#{param.ngoID}")
private Integer ngoID;
This way the value will be retrieved (and inlined as part of a JavaScript helper function of the commandButton) during the request of displaying the form, not evaluated during the request of submitting the form.
See also:
How can I pass selected row to commandLink inside dataTable?
Have you checked that the value of InsertDataDaoService.ngo_id is not NULL?
Try to replace it with a constant value. Does it work?