I am new to JSF and I am struggling with dynamicaly rendering included pages. My code looks like this:
MenuBean
#ViewScoped
public class MenuBean implements Serializable {
private MenuItem[] menuItems = new MenuItem[] {
new MenuItem("page_1", "/page_1.xhtml"),
new MenuItem("page_2", "/page_2.xhtml"),
};
private String selectedItemLabel;
//...
}
MenuItem
public class MenuItem implements Serializable {
private String label;
private String page;
//...
}
index.xhtml
<ui:repeat var="menuItem" value="#{menuBean.menuItems}">
<h:panelGroup rendered="#{menuBean.selectedItemLabel eq menuItem.label}" layout="block">
<h:outputText value="#{menuBean.selectedItemLabel}" />
<ui:include src="#{menuItem.page}" />
</h:panelGroup>
</ui:repeat>
The result is 2 buttons rendered. Whenever I click any button the label inside conditionaly rendered panelGroup appears but included page doesn't. If I change 'menuItem1' var from first ui:repeat it works but it is really unpredictable. For example if I hardcode setSelectedItemLabel parameter to 'page_1' then when I click to button_1 page_1 is displayed but even if I click to button_2 page_2 (!?) is displayed...
You're facing a view build time vs view render time problem. This is essentially the same problem which is already answered in detail in JSTL in JSF2 Facelets... makes sense? In that answer, replace "JSTL" with "ui:include". To the point, the <ui:repeat> runs during view render time, while the <ui:include> has already run during view build time before.
You'll understand that the only solution is to replace the <ui:repeat> by another tag which runs during view build time, such as JSTL <c:forEach>.
Note that I don't guarantee that it will solve the concrete functional requirement which you've in mind. Using JSTL may have undesirable "side effects" (which are however explainable, understandable and workaroundable).
See also:
How to ajax-refresh dynamic include content by navigation menu? (JSF SPA)
Related
This question already has an answer here:
How to call JSF backing bean method only when onclick/oncomplete/on... event occurs and not on page load
(1 answer)
Closed 6 years ago.
Recently I ran into a problem with one of my . I have a separate xhtml containing conditionally rendered icons/links to show different kinds of popups. This xhtml is basically a container for specific kinds of popups that I can include on different pages. The rendered conditions (and a passed ui:parameter) make sure only the relevant icons/links get shown depending on where this xhtml is included. This prevents me of having to write lots of different ui:includes on each page.
For some popups it's necessary to prepare some data, which is done via the onclick attribute of an a4j:commandLink. Then, the oncomplete will show the actual popup like so:
<a4j:commandLink render="clientGroupMemberInfoPopup" rendered="#{assignmentDO.clientGroupMember}"
onclick="#{clientInfoBean.registerGmClientGroupMember(assignmentDO.gmClientGroupMemberDO)}"
oncomplete="RichFaces.ui.PopupPanel.showPopupPanel('ClientInfo')">
<h:graphicImage value="/img/icons/icon_info_sm.png" rendered="#{!printFriendly}"/>
</a4j:commandLink>
The corresponding bean:
#ManagedBean
#ViewScoped
public class ClientInfoBean {
#EJB
private ClientService clientService;
#Getter
#Setter
private ClientContextDO clientContextDO;
#Getter
#Setter
private GmClientGroupMemberDO gmClientGroupMemberDO;
#Getter
#Setter
private Long clientId;
public void registerGmClientGroupMember(final GmClientGroupMemberDO aGroupMember) {
gmClientGroupMemberDO = aGroupMember;
clientContextDO = clientService.findByClientId(gmClientGroupMemberDO.getClientId());
}
}
In this case above the rendered condition of the a4j:commandLink evaluates to true. However... the onclick is evaluated every single time, on every page this xhtml is included, once the rendered condition evaluates to true. Even when the page is still loading and nobody has clicked on anything yet!
Why? And what's the best way to prevent this? There's some relatively heavy db-stuff being done to prepare all the info necessary for the popup. I only want this stuff done the moment someone actually clicks on the link for the popup, not during page rendering phases.
There IS a duplicate of this question, I'm sure but I cannot find it. I'll remove this answer when BalusC flags it as such.
The onclick is for executing javascript, not accessing a server-side method. So the EL in it is evaluated as a value expression, not a method expression. So the output is considered as javascript. Consequently it is just evaluated at render time and re-evaluated when clicked.
The solution is to change the onclick to action
<a4j:commandLink render="clientGroupMemberInfoPopup" rendered="#{assignmentDO.clientGroupMember}"
action="#{clientInfoBean.registerGmClientGroupMember(assignmentDO.gmClientGroupMemberDO)}"
oncomplete="RichFaces.ui.PopupPanel.showPopupPanel('ClientInfo')">
<h:graphicImage value="/img/icons/icon_info_sm.png" rendered="#{!printFriendly}"/>
</a4j:commandLink>
Update: for those flagging this to be closed as a duplicate, the supposed duplicate question is nothing like what I am asking. My problem is I do not know until render time what the question set will be, how many questions there will be or what the question types will be so I cannot use the technique described in the "possible duplicate" answer.
Part of our JSF 2.x application has a requirement to render sets of questions to the user where the questions and the question types are not known until run-time. e.g we have something like (getters/setters omitted for clarity) :
public class QuestionSet {
private List<Section> sections;
}
public class Section {
private String sectionTitle;
private List<Question> questions;
private SectionStatus status; // e.g. UNANSWERED, CURRENTLY_ANSWERING,ANSWERED, COMPLETED
}
public class Question {
private String questionText;
private QuestionType questionType; // E.G TEXT, RADIO, LIST, CHECKBOX
private List<String> options; // for RADIO/LIST/CHECKBOX types
private List<String> answers;
}
We need to render each section in a seperate div, depending on it's status (e.g. UNANSWERED would display a div with just the title, ANSWERED would display a div with the section title and a green tick mark, and CURRENTLY_ANSWERING would render a div with the section title and then each question with the appropriate input control based on the question type.
The questions are also dynamic during the run - e.g. if a user answers yes to a radio button question, this may prompt further sub-questions.
I am currently doing this using a binding, i.e.
<h:panelGroup binding = "#{bean.panelGroup}" />
and within the bean's getPanelGroup creating the component tree by hand usin things like HtmlPanelGroup, HtmlOutputText, UIInput with ValueExpressions etc. which works fine but on reading some of BalusC's answers, particlarly to this question: How does the 'binding' attribute work in JSF? When and how should it be used? I am wondering if there is a "better" approach?
One of the things that concerns me is that the getter is called during RECREATE_VIEW for reasons explained in the linked question (after invoking the method referred to in the binding) so unless I take steps to, in RECREATE_VIEW phase, just return the component I created in the last RENDER_RESPONSE phase, this introduces unnecessary expense of recreating something I've just created.
In this case, it also seems pointless that JSF calls my setter to set the thing I just gave it in the getter for the bound property. (my bean is View scope as I will need to use ajax for some of the functionality our users require)
Thoughts/opinions (Especially from the ever helpful BalusC) greatly appreciated...
I don't see much reason to use component binding in this case. You can decide in your view what to render and how. You can have <ui:fragment>/<c:if> to conditionally render elements basing on question type, <ui:repeat>/<c:forEach> to handle the question set, etc.
So, if I understand the workflow correctly, your question set will be determined in e.g. post constructor method:
#PostConstruct
public void init() {
questionSet = service.get();//get it somehow
}
Then you'll have a set of sections and each of these section will contain questions, or answers, and validity is to be checked via AJAX. If I understand you right, then you can have the following view:
<h:form id="q-set">
<ui:repeat value="#{bean.questionSet.sections}" var="section">
<div>#{section.title}</div>
<div class="#{section.status eq 'UNANSWERED' ? 'section-unanswered' : ... }"/>
<ui:fragment rendered="#{section.status eq 'ANSWERED' ?}"><div class="tick"/></ui:fragment> ...
<ui:fragment rendered="#{section.status eq 'ANSWERED' ?}">
<ui:repeat value="#{section.questions}" var="question">
<div>#{question.title}</div>
<ui:fragment rendered="#{question.type eq 'RADIO'}">
<h:selectOneRadio value="#{question.answers[0]}" validator="...">
<f:selectItems value="#{question.options}" var="opt" itemLabel="#{opt}" ... />
<f:ajax ...>
</h:selectOneRadio>
</ui:fragment>
...
</ui:repeat>
</ui:fragment>
</ui:repeat>
</h:form>
It looks like you are going to have too much logic/conditions in your view.
What about generating the view programmatically on the Java side ?
For tricky parts you may resort to JavaScript and JSON.
I am new to JSF and I am struggling with dynamicaly rendering included pages. My code looks like this:
MenuBean
#ViewScoped
public class MenuBean implements Serializable {
private MenuItem[] menuItems = new MenuItem[] {
new MenuItem("page_1", "/page_1.xhtml"),
new MenuItem("page_2", "/page_2.xhtml"),
};
private String selectedItemLabel;
//...
}
MenuItem
public class MenuItem implements Serializable {
private String label;
private String page;
//...
}
index.xhtml
<ui:repeat var="menuItem" value="#{menuBean.menuItems}">
<h:panelGroup rendered="#{menuBean.selectedItemLabel eq menuItem.label}" layout="block">
<h:outputText value="#{menuBean.selectedItemLabel}" />
<ui:include src="#{menuItem.page}" />
</h:panelGroup>
</ui:repeat>
The result is 2 buttons rendered. Whenever I click any button the label inside conditionaly rendered panelGroup appears but included page doesn't. If I change 'menuItem1' var from first ui:repeat it works but it is really unpredictable. For example if I hardcode setSelectedItemLabel parameter to 'page_1' then when I click to button_1 page_1 is displayed but even if I click to button_2 page_2 (!?) is displayed...
You're facing a view build time vs view render time problem. This is essentially the same problem which is already answered in detail in JSTL in JSF2 Facelets... makes sense? In that answer, replace "JSTL" with "ui:include". To the point, the <ui:repeat> runs during view render time, while the <ui:include> has already run during view build time before.
You'll understand that the only solution is to replace the <ui:repeat> by another tag which runs during view build time, such as JSTL <c:forEach>.
Note that I don't guarantee that it will solve the concrete functional requirement which you've in mind. Using JSTL may have undesirable "side effects" (which are however explainable, understandable and workaroundable).
See also:
How to ajax-refresh dynamic include content by navigation menu? (JSF SPA)
Project uses Spring Webflow and JSF (PrimeFaces). I have a p:commandButton with f:attribute
<p:commandButton disabled="#{editGroupMode=='edit'}" action="edit_article_group" actionListener="#{articleGroupManager.setSelectedRow}" ajax="false" value="Edit">
<f:attribute name="selectedIndex" value="${rowIndex}" />
</p:commandButton>
Backend code (Spring injected bean):
#Service("articleGroupManager")
public class ArticleGroupManagerImpl implements ArticleGroupManager{
public void setSelectedRow(ActionEvent event) {
String selectedIndex = (String)event.getComponent().getAttributes().get("selectedIndex");
if (selectedIndex == null) {
return;
}
}
}
The attribute "selectedIndex" is always null. Anybody knows what happened here? Thank you.
The variable name "rowIndex" suggests that you've declared this inside an iterating component, such as <p:dataTable>.
This is then indeed not going to work. There's physically only one JSF component in the component tree which is reused multiple times during generating HTML output. The <f:attribute> is evaluated at the moment when the component is created (which happens only once, long before iteration!), not when the component generates HTML based on the currently iterated row. It would indeed always be null.
There are several ways to achieve your concrete functional requirement anyway. The most sane approach would be to just pass it as method argument:
<p:commandButton value="Edit"
action="edit_article_group"
actionListener="#{articleGroupManager.setSelectedRow(rowIndex)}"
ajax="false" disabled="#{editGroupMode=='edit'}" />
with
public void setSelectedRow(Integer rowIndex) {
// ...
}
See also:
JSTL in JSF2 Facelets... makes sense?
How can I pass selected row to commandLink inside dataTable?
Unrelated to the concrete problem, I'd in this particular case have used just a GET link with a request parameter to make the request idempotent (bookmarkable, re-executable without impact in server side, searchbot-crawlable, etc). See also Communication in JSF 2.0 - Processing GET request parameters.
Edited question...
Hello,
I would like to load a .xhtml file of my composite component from a backing bean, and add it to the page dynamically. The name of the .xhtml file comes form a variable.
Ex.:
public MyBean (){
String componentFile = "myCompositeComponent.xhtml"
public String addComponentToPage(){
//how do that?...
return null;
}
}
Thank you!
That's not possible. A composite component is template-based and can only be used in views. Your best bet is to repeat exactly the JSF code which you've originally written in the composite component in the model. Better would be to create a full worthy #FacesComponent class which extends UIComponent, complete with a #FacesRenderer. True, it's a tedious and opaque job, but this way you'll end up with a component which is reuseable in both the view and the model by a single code line.
An -ugly- alternative is to place all possible components in the view and use the rendered attribute.
<my:component1 rendered="#{bean.myComponentType == 'component1'}" />
<my:component2 rendered="#{bean.myComponentType == 'component2'}" />
<my:component3 rendered="#{bean.myComponentType == 'component3'}" />
...
Wrap this if necessary in a Facelets tag file so that it can be hidden away and reused in several places.
I don't understand why do you want to add a composite component from a backing bean. I guess you want to make it visible dynamically in case of an event, but for that there is AJAX reRender.
For example you can do the following:
<h:panelGroup id="composite" rendered="#{myBean.renderComponent}">
<my:compositecomponent/>
</h:panelGroup>
The renderComponent property stores a boolean value. You can switch that value and reRender composite with for e.g. Richfaces's <a4j:commandLink>.
Hope that helps, Daniel