I have the next Java model bean (which contains not only a date in milliseconds but also a time zone)
public class Device {
private Calendar lentDate;
// getters and setters
}
and the next xhtml page fragment
<rich:dataTable value="#{tagBean.devices}" var="device">
<rich:column>
<h:outputText value="#{device.lentDate.time}">
<f:convertDateTime pattern="dd.MM.yyyy" timeZone="#{device.lentDate.timeZone}"/>
</h:outputText>
</rich:column>
</rich:dataTable>
But the timeZone attribute does not get the device.lentDate.timeZone value. Looks like it is because when the f:convertDateTime tag is rendered, the device variable is not available yet.
Is it possible to force JSF to render the f:convertDateTime tag after the device variable is available? Or the only way to make the timeZone set properly for each device in this case is to create a custom date/time converter?
Thank you.
The problem is that the attributes of the converter are evaluated when the view is build. This is partially because a converter is not a component itself, but in Facelets implemented by a TagHandler that sets a converter instance in the parent component. See JSTL in JSF2 Facelets... makes sense? for a very thorough background explanation.
You can solve this by using the <o:converter> from OmniFaces that was specifically build for this use case. Contrary to the regular converters, this one does evaluate its attributes when its parent component is being rendered.
See: http://showcase.omnifaces.org/taghandlers/converter
Related
Is there a way to have a JSF Backing bean cause an update of a component on the page? I am not looking to use an ajax component with update attribute to update a component on the page. I need to trigger an update from within a JSF backing bean method. Note the update on the page can happen after this method completes or prior to its completion. I am using PrimeFaces, if there is a solution that can be had from using PrimeFaces.
Using standard JSF API, add the client ID to PartialViewContext#getRenderIds().
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add("foo:bar");
Using PrimeFaces specific API, use PrimeFaces.Ajax#update().
PrimeFaces.current().ajax().update("foo:bar");
Or if you're not on PrimeFaces 6.2+ yet, use RequestContext#update().
RequestContext.getCurrentInstance().update("foo:bar");
If you happen to use JSF utility library OmniFaces, use Ajax#update().
Ajax.update("foo:bar");
Regardless of the way, note that those client IDs should represent absolute client IDs which are not prefixed with the NamingContainer separator character like as you would do from the view side on.
I also tried to update a component from a jsf backing bean/class
You need to do the following after manipulating the UI component:
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(componentToBeRerendered.getClientId())
It is important to use the clientId instead of the (server-side) componentId!!
The RequestContext is deprecated from Primefaces 6.2. From this version use the following:
if (componentID != null && PrimeFaces.current().isAjaxRequest()) {
PrimeFaces.current().ajax().update(componentID);
}
And to execute javascript from the backbean use this way:
PrimeFaces.current().executeScript(jsCommand);
Reference:
https://github.com/primefaces/primefaces/wiki/Migration-Guide
https://forum.primefaces.org/viewtopic.php?t=53129
Everything is possible only if there is enough time to research :)
What I got to do is like having people that I iterate into a ui:repeat and display names and other fields in inputs. But one of fields was singleSelect - A and depending on it value update another input - B.
even ui:repeat do not have id I put and it appeared in the DOM tree
<ui:repeat id="peopleRepeat"
value="#{myBean.people}"
var="person" varStatus="status">
Than the ids in the html were something like:
myForm:peopleRepeat:0:personType
myForm:peopleRepeat:1:personType
Than in the view I got one method like:
<p:ajax event="change"
listener="#{myBean.onPersonTypeChange(person, status.index)}"/>
And its implementation was in the bean like:
String componentId = "myForm:peopleRepeat" + idx + "personType";
PrimeFaces.current().ajax().update(componentId);
So this way I updated the element from the bean with no issues. PF version 6.2
Good luck and happy coding :)
In order to updte the component from backing bean, we can achieve as below
RequestContext.getCurrentInstance().update('updatePanelGroup');
<h:panelGroup id="updatePanelGroup">
.....
....
</h:panelGroup>
Updating the component differs with respect to prima face version.
I need color picker on my page.
First, I placed Primefaces' colorpicker, but when I tried to use it, I received "IllegalArgumentException: text/xml is not a supported mime type". Probably this occurs because I use my own jquery library, which has no colorpicker element, and it overrides Primefaces' one.
So, I tried it in other way. I used "jscolor" library which turns any input field to colorpicker. I got component:
<h:inputText value="#{searchManagedBean.selectedColor}" class="color"/>
It works perfectly, but when I submit form, value in backing bean doesn't update. In backing bean I have getter and setter for this field, so I can't figure out what is the reason of this problem.
Could you help me with one of these problems, or maybe provide another solution?
Thanks!
I found the solution. If I update the value in some other element, value in backing bean updates too. So, now I have something like this:
<h:inputText value="#{searchManagedBean.selectedColor}" class="color">
<p:ajax event="change" update="outcolor"/>
</h:inputText>
<h:outputText style="display: none" id="outcolor" value="#searchManagedBean.selectedColor}"/>
For me, it's very strange behaviour. I don't know why it works, but it works!
Sorry, really really basic question...
I've got a list of 'messageboard threads' that I display on a page. I want to be able to click on one of them and redirect to a page which displays the details for that thread. I'm struggling despite googling it for a while...
(I'm using PrimeFaces by the way)
Here's the relevant code from my 'list' page:
<p:commandLink value="#{thread.title}" action="#{messageboardBean.showThread()}">
<f:param name="threadId" value="#{thread.id}" />
</p:commandLink>
(it's in an h:form element)
This is part of my named bean (other methods work fine)
...
#ManagedProperty(value="#{param.threadId}")
private Long threadId;
...
public String showThread() {
System.out.println("id is " + getThreadId());
return "messageboard/list";
}
...
As you can see my method isn't implemented yet, but it's not even being called. Please can someone tell me why?
I tried with an h:link too by the way, same (or similar) problem.
Thanks!
UPDATE - Solved
Thanks to the help below, here is my solution (I've renamed 'messageboard' to 'discussion').
The link is generated using this code
value: what to display on the page, in my case the title of my discussion
outcome: refers to edit.xhtml, the faces file I want to go to
...and the [request] param is going to be called 'threadId' and has a value of the id attribute in my 'thread' object.
In the edit.xhtml page, I've got this
<f:metadata>
<f:viewParam name="threadId" value="#{viewDiscussionBean.threadId}" />
<f:event type="preRenderView" listener="#{viewDiscussionBean.loadDiscussion}" />
</f:metadata>
Note that 'threadId' is the same as the param name in the first page, and it is bound to my viewDiscussionBean's threadId property.
Then once the params are all set on my bean, I call the loadDiscussion method of my viewDiscussionBean. Since it now has the threadId property, it's able to do this (see below)
My viewDiscussionBean has the following managed property (I think the viewParam tag sets this, rather than the other way around).
#ManagedProperty(value="#{param.threadId}")
private Long threadId;
private Discussion thread;
So once that's set, this method is able to run (because it now has an ID)
public String loadDiscussion() {
thread = mbDao.find(threadId);
return "edit";
}
This just uses a DAO (using Hibernate) to look up the discussion thread with that ID, and set it in the bean. And then...
In my edit.xhtml page, I can access values in the discussion thread using things like
<h:outputText value="#{viewDiscussionBean.thread.message}" />
Voila! Thanks.
There are many possible caused for an UICommand action not being invoked. You can find them all here: commandButton/commandLink/ajax action/listener method not invoked or input value not updated Among others a missing form, a nested form, or a conversion/validation error elsewhere in the form, being in a datatable whose datamodel is not properly preserved, etcetera.
As to your particular functional requirement, better is to use a <h:link>. A command link issues a POST request which does in your particular case not end up with a bookmarkable URL with the thread ID in the URL. A <h:link> creates a fullworthy link which is bookmarkable and searchbot-indexable.
E.g.
<h:link value="#{thread.title}" outcome="messageboard/list">
<f:param name="threadId" value="#{thread.id}" />
</h:link>
This doesn't require a form nor an action method. You only need to move that #ManagedProperty to the bean associated with messageboard/list, or maybe replace it by <f:viewParam> in the messageboard/list view which allows for finer-grained validation/conversion.
See also:
Communication in JSF2 - Processing GET request parameters
When should I use h:outputLink instead of h:commandLink?
ViewParam vs #ManagedProperty(value = "#{param.id}")
Your best bet it probably to go with BalusC's answer and use <h:link>. However, I have some thoughts about the behavior you're seeing.
Primefaces <p:commandLink> (like <p:commandButton>) uses ajax by default. Therefore, there won't be any actual navigation resulting from returning an outcome from your action. This could make it look like your action isn't being invoked. Try adding ajax=false to your <p:commandLink>.
When using <h:link>, navigation is resolved when the link is rendered rather than when it's clicked. Modifying your example:
<h:link value="#{thread.title}" outcome="#{messageboardBean.showThread()}">
<f:param name="threadId" value="#{thread.id}" />
</h:link>
showThread() will be called (I think) when the view containing the link is being rendered. If you're not checking at the right time, this may also make it look like the method is being called.
In both cases, this doesn't explain why you wouldn't see the message to System.out at all, but I know I've tried that thinking it was fail-safe and still not seen the output, which all depends on your container, configuration, how you launched it, etc.
I have a problem with a binding p:commandButton to a property in a backing bean. I've tried to simplify my code to show general idea.
ExampleBean is a backing bean
public class ExampleBean {
public String title;
List<ExampleWrapper> list;
// Getters and setters
}
ExampleWrapper is a POJO
public class Wrapper {
public String name;
public String description;
public CommandButton button;
// Listener which changes button state
// Getters and setters
}
index.xhtml is a main page:
<h:form>
<h:outputText value="Title" />
<p:inpurText value="#{exampleBean.title}"
<ui:include src="list.xhtml">
<ui:param name="bean" value="#{exampleBean}">
</ui:include>
</h:form>
list.xhtml is a fragment I want to be reused in a few places:
<ui:composition ...>
<ui:repeat id="list" var="exampleWrapper" value="#{bean.list}">
<h:outputText value="#{exampleWrapper.name}"/>
<h:outputTextarea value="#{exampleWrapper.description}"/>
<p:commandButton id="button" binding="#{exampleWrapper.button}"
value="Button" />
</ui:composition>
So, I get exception:
javax.el.PropertyNotFoundException: /list.xhtml ... binding="#{exampleWrapper.button}": Target Unreachable, identifier 'exampleWrapper' resolved to null
Without binding attribute everything works and displays fine
Could you explain why and how can I bind button to this POJO property? Any help will be appreciated
I'm using JSF 2.0.2 with Primefaces 3.0.1
The binding (and id) attribute of a JSF UI component is resolved during view build time. The #{exampleWrapper} instance is not available during the view build time. The view build time is that moment when the XHTML file is parsed into a JSF component tree. The #{exampleWrapper} is only available during the view render time. The view render time is the moment when the JSF component tree generates HTML output.
Basically, there's only one <p:commandButton> in the component tree which generates its HTML output multiple times as many as the <ui:repeat> iterates. You need to bind it to the #{bean} instead, or to use JSTL <c:forEach> instead of <ui:repeat>. The JSTL tags runs namely during view build time and the <c:forEach> will thus produce physically multiple JSF UI components. But, more than often, binding components to backing beans is unnecessary in JSF 2.x. Whatever functional requirement you've had in mind for which you thought that this is the solution, it can definitely be solved in a better way.
I'm getting deeper into JSF 2.0 at the moment and lacking a bit of understanding about the "transport" of managed bean properties from one view to the other. I searched a bit but haven't found a really good example, so if anyone could point me to a tutorial or explain the things a little bit I'd really grateful.
So here is my scenario:
I'm developing a small playground calendar application. The first view select.xhtml contains the calendar selector, where the user can pick a specific date:
<html>
...
<h:form>
<!-- Calendar selector from primefaces -->
<p:calendar value="#{calendarSelect.date}" mode="inline" navigator="true" />
<p:commandButton value="Show entries for date" action="day" />
...
My corresponding backing bean looks like this:
#ManagedBean(name="calendarSelect")
#RequestScoped
public class CalendarSelectComponent {
private Date date = null;
... // Getters and setters
Now when I submit the form from select.xhtml I'm forwarded to day.xhtml
<html>
...
<h:form>
The current day ist:
<h:outputText value="#{calendarEdit.date}">
<f:convertDateTime pattern="dd.MM.yyyy" />
</h:outputText>
The backing bean now looks like this:
#ManagedBean(name="calendarEdit")
#ViewScoped
public class CalendarEditComponent implements Serializable {
private Date date = null;
private CalendarEntryBean currentEntry = null;
private List<CalendarEntryBean> allEntries = null;
....
I am now trying to solve the problem: How do I transfer the date parameter from the selector to the editor?
I've tried a number of options, one was this:
<p:commandButton value="Show entries for date" action="day" />
<f:setPropertyActionListener target="#{calendarEdit.date}" value="#{calendarSelect.date}" />
</p:commandButton>
A debugger shows, that indeed, the date property of the calendarEdit is populated with the value from calendarSelect, but since day.xhtml is a new view, a new CalendarEditComponent backing bean is being created and not the one I've populated with the date from the selector in the select view.
I've read that one solution would be to create a SessionScoped backing bean that does retain all it's values. But this is not the way I think it's supposed to work, because I don't really need the information in the session, I simply want it to "travel" from A to B. Another downside with the session based approach is that I can only use one selector and one editor per session - which I think isn't acceptible if you think of multi window browsing and so on.
I really don't think I'm the first one encountering such a scenario and I'm sure that JSF provides an elegant solution for this but I haven't been able to find that solution.
So once again, if anyone knows how to approach this - I'm listening! ;-)
The <f:setPropertyActionListener> is executed during invoke action phase of the form submit. So it expects that the value is still there at that point. But since your select bean is request scoped, it isn't there during form submit anymore. You want instead to pass a request parameter which get inlined in the output during render response. You can do this with <f:param>.
<p:commandButton value="Show entries for date" action="day" />
<f:param name="date" value="#{calendarSelect.dateAsString}" />
</p:commandButton>
It'll be available as request parameter (note that it only understands Strings, due to the nature of HTTP). You could let JSF set request parameters as managed properties, but since your edit bean is view scoped, this isn't possible with #ManagedProperty. You've got to gather it yourself by ExternalContext.
String dateAsString = externalContext.getRequestParameterMap().get("date");
True, that's clumsy. I would just have used the same bean and view for this and toggle visibility of select/edit forms by rendered attribute. The edit view is after all not directly openable/bookmarkable by a simple GET, isn't it? ;)