Referring to this post on primefaces forum.
Has someone got any idea how can we use multiple datatable on the same page but only display the correct one?
My problem is that i have a view-Scoped bean whose properties contain data from different tables from a database. I have multiple datatables for data of each database table. Now i want to display the datatable on the basis value selected from <p:selectOneMenu>
(encircled in red color).
this screenshot would explain a bit further.
The basic approach would be to let the rendered
attribute of the tables depend on the selected item of the menu.
<p:selectOneMenu value="#{bean.table}">
<f:selectItem itemValue="players" itemLabel="Players" />
<f:selectItem itemValue="jobs" itemLabel="Jobs" />
<f:selectItem itemValue="business" itemLabel="Business" />
...
<p:ajax update="tables" />
</p:selectOneMenu>
<h:panelGroup id="tables">
<p:dataTable value="#{bean.players}" rendered="#{bean.table == 'players'}">
...
</p:dataTable>
<p:dataTable value="#{bean.jobs}" rendered="#{bean.table == 'jobs'}">
...
</p:dataTable>
<p:dataTable value="#{bean.business}" rendered="#{bean.table == 'business'}">
...
</p:dataTable>
...
</h:panelGroup>
This is easy to implement, but you end up with a lot of code in the view (which can of course be split over <ui:include>
files). The more advanced and reuseable approach would be to let the value
of the single table depend on the selected item of the menu and use <p:columns>
to generate columns dynamically.
<p:selectOneMenu value="#{bean.table}">
<f:selectItems value="#{bean.tables}" />
<p:ajax listener="#{bean.changeModel}" update="table" />
</p:selectOneMenu>
<p:dataTable id="table" value="#{bean.model}" var="item">
<p:columns value="#{bean.columns}" var="column">
<h:outputText value="#{item[column]}" />
</p:columns>
</p:dataTable>
with something like:
public void changeModel() {
model = populateModelBasedOn(table);
columns = populateColumnsBasedOn(table);
}
This only allows less fine-grained control whenever you want to add more specialized columns. You'd probably want to work with tag files instead.