The <h:inputText> value is not been set in a request scoped bean. If the value is preserved from DB, it works fine.
view:
<h:inputText id="receipient" size="90" styleClass="text" readonly="#{!bean.enable}" value="#{bean.recipient}" />
bean:
public class Bean {
private String recipient;
Bean(){
recipient = //load from db
}
//set
//get
}
What is the problem and how can I solve this?
Ensure that readonly="#{!bean.enable}" evaluates the same as it was in initial view. If it evaluates true during apply request values phase of the form submit, then the component's value won't be processed (because it is marked as read only).
An easy test is to put the bean in session scope. If that fixes it, then you know the culprit. If you're using JSF 2.0, just put bean in view scope by using #ViewScoped instead of #RequestScoped. If you're still on JSF 1.x, use Tomahawk's <t:saveState> component to let the bean act like the JSF 2.0 view scoped one.
<t:saveState value="#{bean}" />
Related
I have a ViewScoped Managed Bean. In my .xhtml page I want to set bean's attribute's value and use it in methods in the same bean.
I managed to set the value from jsf page, but when i want to use it in some method the value of an attribute is not the value i have set before.
Description (xhtml):
In this form there is a command link which sets the value of an attribute. And it is working fine. Also, as command link is clicked, second form is being showed.
<h:form>
<h:commandLink value="Set" >
<f:setPropertyActionListener target="#{bean.attribute}" value="true" />
<f:ajax execute="#this" />
</h:commandLink>
</h:form>
This form executes method that uses attribute's value set before, but the value is not true, its false.
<h:form>
<h:commandButton id="submit" value="Execute" action="#{bean.execute}" />
</h:form>
Bean:
public void execute(){
if(isAttribute())
---do something---
}
The question is: Why execute() is not reading attribute's value right?
When I use one form, it's working fine. But I need them to be in separated forms.
The scope of your bean is incorrect. ViewScoped means that the minute the view is changed, the bean is discarded and re-created for the next view. So, in your case, the original data you had for the first view is lost.
I'm going to refer you to BalusC's blog:
http://balusc.blogspot.co.uk/2010/06/benefits-and-pitfalls-of-viewscoped.html
which states:
A #ViewScoped bean will live as long as you're submitting the form to the same view again and again. In other words, as long as when the action method(s) returns null or even void, the bean will be there in the next request. Once you navigate to a different view, then the bean will be trashed
I can't determine of you stay on the same page with both requests. If you do, viewScope should work even in two different forms. If you are navigating from 1 view to another, another viewScope will be created and you will loose the current one.
You could set the value in the sessionScope with java or by annotating the backingNean. But then everything in your backingBean becomes sessionScoped and that might not be needed.
You could also use a spring-like flow scope.
Example to do it with java:
public void callThisAfterFirstClick() {
Faces.setSessionAttribute(attribute, true)
}
public void callThisAfterSecondClick() {
Faces.getSessionAttribute(attribute);
}
Mojara 2.1.21
I've updated my question based on comments. I have two situation where a component is bound to server session bean. (Additional links with information: Binding attribute causes duplicate component ID found in the view and https://stackoverflow.com/a/12512672/2692917)
Version 1:
single.xhtml:
<h:outputText value=... binding="#{mysessionbean.out}" />
java:
#SessionScoped #Named public class Mysessionbean {
UIOutput out;
//getter and setter ....
}
Version 2:
template.xhtml:
<h:outputText value=... binding="#{mysessionbean.out}"
view1.xhtml:
<ui:composition template="template.xhtml" />
view2.xhtml:
<ui:composition template="template.xhtml" />
java:
#SessionScoped #Named public class Mysessionbean {
UIOutput out;
//getter and setter ....
}
Version 1 is ok. (At least I've not encounter any errors so far). But in version 2 the duplicate id error is occured if I navigate from one page to another. Why does it happen ?
Is it safe to use (request-scoped) component (in version 1) with session scoped binding ?
Are there another use cases to consider ?
Edit:
Functional requirement 1:
I want to use Primefaces datatable in a view. I need some info from this datatable. (Such as selected row or row index). So binding the datatable helps me to retrieve this info.
Functional requirement 2:
Components binding in composite components. They will be bound to session scoped bean. (And used mainly on one page, but what if I used it on another page ?
Requirements 3
The situation as in "Version 2". Template with primefaces menu and session scoped binding. For this I've used the EL-Binding.
In JSF 2.x, unless you want to manipulate components programmatically (which is at its own also rather fishy), there is no sensible real world use case to bind components to a backing bean. For sure not if they are further not been used in the backing bean itself, or if it are solely their attributes which are been flattened out.
As to the functional requirement of getting the current row of the data table, there are much better ways listed here, How can I pass selected row to commandLink inside dataTable?, for example if your environment supports EL 2.2:
<h:dataTable value="#{bean.items}" var="item">
<h:column>
<h:commandLink value="Foo" action="#{bean.foo(item)}" />
The two last requirements are totally unclear. At least, if you're doing something like:
<x:someComponent binding="#{bean.someComponent}" />
with in bean
someComponent.setSomeAttribute(someAttribute);
someComponent.setOtherAttribute(otherAttribute);
then you should instead be doing
<x:someComponent someAttribute="#{bean.someAttribute}" otherAttribute="#{bean.otherAttribute}" />
Or, if you intend to be able to use the component somewhere else in the view like so
<h:inputText ... required="#{not empty param[bean.save.clientId]}" />
...
<h:commandButton binding="#{bean.save}" ... />
and the instance is further nowhere been used in the bean, then just get rid of the unnecessary property altogether:
<h:inputText ... required="#{not empty param[save.clientId]}" />
...
<h:commandButton binding="#{save}" ... />
If there is really, really no way for some unclear reason, then split all request scoped properties of the session scoped bean out into a separate request scoped bean which you in turn bind to form actions. The session scoped one can just be injected as a #ManagedProperty of the request scoped one.
See also:
Binding attribute causes duplicate component ID found in the view
How does the 'binding' attribute work in JSF? When and how should it be used?
We ran into a similar problem and I just want to share our solution:
Problem:
In a view there was a (extended largely customized) datatable.
<x:dataTable binding="#{bean.someSomeDataTable}" />
After navigating to another page and back we wanted the datatable to have the exact same state. Previously we solved that by binding the datatable to to backing bean. This worked fine with JSPs. With Facelets we could not do that (Duplicate ID errors). So we used the binding, but only saved/restored the state of the datatable component.
public HtmlDataTable getSomeDataTable()
{
HtmlDataTable htmlDataTable = new HtmlDataTable();
if (tableState != null)
htmlDataTable.restoreState(FacesContext.getCurrentInstance(), tableState);
return htmlDataTable;
}
public void setSomeDataTable(HtmlDataTable table)
{
tableState = table.saveState(FacesContext.getCurrentInstance());
}
Using JSF2 (MyFaces 2.1) and CDI (Weld) I use a selectOneMenu filled with an enum to conditionally render a second selectOneMenu (doublemenu in the code). There are several other fields in the form which are validated using bean validation.
The problem:
If there are validation errors after clicking on the commandButton and error messages are shown, the doublemenu will not reappear. It appears that bean.type =='double' is not true. But why? The selectOneMenu itself shows the option double as the selected item.
#javax.inject.Named
#javax.enterprise.context.RequestScoped
public class Bean {
private enum MyEnum {
Single, Double
}
private MyEnum type;
public MyEnum getType() {
return type;
}
public void setType(MyEnum type) {
this.type = type;
}
public MyEnum [] getTypes() {
return MyEnum.values();
}
<h:form>
<h:selectOneMenu value="#{bean.type}">
<f:selectItems value="#{bean.types}" />
<f:ajax render="doublemenu" />
</h:selectOneMenu>
<h:panelGroup id="doublemenu">
<h:panelGroup rendered="#{bean.type == 'double'}">
<h:selectOneMenu ...>
</h:selectOneMenu>
</h:panelGroup>
</h:panelGroup>
<h:inputText id="VALIDATED"/>
<h:commandButtonaction="#{bean.save}"
</h:form>
BTW: bean.save is not executed
It's because your bean is request scoped. Request scoped beans are garbaged by end of every request and newly created on begin of every request. This also applies to individual ajax requests on the same view.
The rendered attribute is also evaluated during collecting submitted values (the apply request values phase). However, at the point the submitted values are to be collected, the #{bean.type} is obviously not been set yet (it has still to be set based on the collected submitted value during update model values phase). As your bean is request scoped, it would return the default value, not the submitted value from a previous request.
There are basically 2 ways to fix this.
Put the bean in a bit broader scope. JSF offers the #ViewScoped for exactly this purpose. This is in the current JSF 2.1 version only not compatible with CDI. If switching to JSF #ManagedBean is not an option, then you'd need MyFaces CODI to bridge the JSF #ViewScoped transparently to CDI, or to wait for JSF 2.2 to get a CDI compatible #ViewScoped out the box.
Check a request parameter instead of a bean property.
<h:selectOneMenu binding="#{type}" ...>
...
</h:selectOneMenu>
<h:panelGroup rendered="#{param[type.clientId] == 'Double'}">
Please note that this all is completely unrelated to enums. You'd have had exactly the same problem when using e.g. a String. Also please note that I fixed a typo in your code example, an enum value of Double is definitely not the same as double.
See also:
How to choose the right bean scope?
commandButton/commandLink/ajax action/listener method not invoked or input value not updated
I have a facelet template with:
<f:metadata>
<o:viewParam name="id" value="#{homeBean.id}" />
</f:metadata>
<h:form>
<h:inputHidden value="#{homeBean.id}" />
<h:inputText value="#{homeBean.user.firstName}" />
<h:commandButton value="Submit" action="#{homeBean.onSave()}" />
</h:form>
and a request scoped bean with:
#Named
#RequestScoped
public class HomeBean {
private Integer id;
private User user;
public void setId(Integer id) {
System.out.println("setId called");
user = // code for loading User entity bean with supplied id
}
// other accessors for id and user
}
Initial page load works well, entity is loaded and displayed in a form, inputHidden is set to entity id. Problem is that submit throws:
javax.el.PropertyNotFoundException - Target unreachable, base expression '. user' resolved to null
probably because getUser is called before setId. How can I solve this? I really would like to have a request scoped bean, I know that this can be easily solved with at least viewaccess scoped bean.
EDIT: Now i noticed that exception is thrown in Process Validations phase, I initially thought that exception is thrown in Update Model Values phase. I changed "private User" to "private User user = new User()" and now it's OK, but it feels little weird.
Regards,
Pavel
The OmniFaces <o:viewParam> sets the request parameter only in the initial request and not in postbacks. This is intented to be used with #ViewScoped beans so that the request parameter isn't unnecessarily been validated, converted and updated on every single postback (because it's already still present in a view scoped bean). The API documentation and the showcase example also explicitly mentions that it should be used with view scoped beans.
You've there however a request scoped bean which get trashed and recreated on every single request, also on postbacks to the same view. So the user property disappears and falls back to default null on every subsequent postback request.
There are basically 2 ways to fix it:
Replace <o:viewParam> by <f:viewParam>. It will call the setter on every request, also on postbacks.
Replace #Named #RequestScoped by #ManagedBean #ViewScoped, this way the bean will live as long as you're interacting with the same view. Or if you insist in using CDI, use #Named #ConversationScoped instead, but you have to manage the begin and end of the conversation yourself.
My view is:
<h:commandLink value="BookFlight" action="#{bookSeatController.doLoginOrCC}">
<f:setPropertyActionListener target="#{bookSeatController.flightNumber}"
value="#{flightInfoController.flight.number}" />
</h:commandLink>
My setter is:
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
When I use the debugger I get a flightNumber of null in the setter. However, if I change the view to the following:
<h:commandLink value="BookFlight" action="#{bookSeatController.doLoginOrCC}">
<f:setPropertyActionListener target="#{bookSeatController.flightNumber}"
value="122334" />
</h:commandLink>
The flightNumber property is set to 122334. How is this caused and how can I solve it to set the intended value instead of null?
If the #{flightInfoController.flight.number} is request scoped, then it has to preserve exactly the same flight in during the request of processing the form submit as it was during the request of displaying the form. This has to happen in the bean's (post)constructor.
If that is not an option, because it depends on some request based variables, then your best bet is to put the bean in the view scope instead (I however still assume that your bean is properly designed that it doesn't do any business/preloading job in getters).
If putting the bean in the view scope is in turn not an option, then you'd need to pass it as a fullworthy request parameter instead. You can do that by <f:param>.
<h:commandLink value="BookFlight" action="#{bookSeatController.doLoginOrCC}">
<f:param name="flightNumber" value="#{flightInfoController.flight.number}" />
</h:commandLink>
You can let JSF set it by #ManagedProperty in the BookSeatController or by <f:viewParam> in the current view.
See also:
How can I pass selected row to commandLink inside dataTable?
ViewParam vs #ManagedProperty(value = "#{param.id}")
If it's working when assigning "122334" but when assigning flightInfoController.flight.number it's "null" and since you are not receiving any exception, then it means probably your flightInfoController is not properly initialized (regarding it's field flight and hence number in the flight).
Just make sure the bean is properly initialized (or update your OP with the bean code).