I have a PrimeFaces (5) DataTable and like to store the page size selection in the view, so that the user sees the same number of rows when he returns to the view.
But all I see from documentation is that there is a page event which can be captured, but which won't give me the currently selected page size. The closest I got was getting the event's source (the DataTable) and get the rows attribute, but it only contains the number of rows before applying the new value.
Here on SO, I found a solution here, but it seems to me not the best way to implement it having to use some inline JQuery stuff.
It seems to me a not-so-exotic feature to persist the page size selection within the session, so there must be a good solution for it, I assume?
As you already noticed, the page event is being fired before the selected number of rows has been applied to the table. At the moment, there is no event being fired after changing the number of rows.
However, there is a possible workaround:
bind your datatable to the backing bean
Use AJAX page-event without any listener. Instead, call a <p:remoteCommand> after ajax request is complete.
Add your actionListener method to the <p:remoteCommand>.
Within this method, check the datatable's number of rows. It's the new value.
Keep in mind, page event is not only fired when changing the number of rows, but also on page change.
Example:
XHTML/JSF
<h:form>
<p:remoteCommand name="pageChanged" actionListener="#{tableBean.onPageChanged}"/>
<p:dataTable binding="#{tableBean.table}" paginator="true" rowsPerPageTemplate="5,10,20" rows="5">
<p:ajax event="page" process="#none" oncomplete="pageChanged()" />
<!-- columns here -->
</p:dataTable>
</h:form>
TableBean.java
private DataTable table;
public void onPageChanged(){
int numRows = table.getRows();
// ...
}
//getter/setter for table
Related
How do I execute code when the user clicks a cell in a data table? Similarly to listener and actionListener on a p:commandButton.
For example
<p:commandButton oncomplete="PF('editProductDialog').show()"
actionListener="#{bean.doStuffToGetASelectOneMenuReadyforTheEditProductDialog()}" />
public void doStuffToGetDialogReady() {
//query databases to get select item list
}
The database is only queried when/if the user clicks the commandButton
But for p:dataTable inline cell editing how to I call code that would query database to get select items only when they click the data table cell to make an edit?
<p:cellEditor>
<f:facet name="output"/>
<f:facet name="input">
<p:selectOneMenu>
<f:selectItems value="#{bean.someListSpecificToThisUser}" />
</p:selectOneMenu>
</f:facet>
</p:cellEditor>
I've been populating the someListSpecificToThisUser selectItems list in the #PostConstruct init() method
#PostConstruct
public void init() {
//code specific to the page and datatable
someListSpecificToThisUser = service.queryValuesForUser(user);
}
but if the user never clicks the cell to edit the selectOneMenu value then I hit the database and stored the list in memory for no reason. Or should I not worry about the overhead?
In case of cell editing of a p:dataTable there are a few events you can use:
Event
Fired
cellEdit
When a cell is edited.
cellEditCancel
When a cell edit is cancelled e.g. with escape key
cellEditInit
When a cell edit begins.
All taking a org.primefaces.event.CellEditEvent as the listener parameter.
You could use the cellEditInit method to populate the list when it is still null. Downside is that this requires an Ajax call on each edit init.
An other option you have is to store the list in a SessionScoped user bean, which will cost you some memory.
The option to pick depends on the size of the list, how much time it takes to fetch the list and how many edits you expect. If you don't expect much edits, use an Ajax listener to populate the list. If the list is long and takes some time to load, I would switch to a p:autoComplete field.
See also:
https://primefaces.github.io/primefaces/10_0_0/#/components/datatable?id=ajax-behavior-events
How to choose the right bean scope?
https://www.primefaces.org/showcase/ui/input/autoComplete.xhtml
I'm trying to implement live searching with primefaces inputtext, all works well until the situation where user deletes last symbol in search field and all results must be shown back. For example when i open page all results are shown, i type letter a, results being filtered, delete a and again see all results. Problem is, when i delete last letter the ajax event is not being fired (maybe because of empty string?). Code for inputtext:
<p:inputText id="searchString" title="searchString" value="#{findDoctorBean.searchString}" >
<p:ajax event="keyup" listener="#{findDoctorBean.searchForDoctorsByName}" process="#this" update=":resultGroup"></p:ajax>
</p:inputText>
How should i fire an event in such situation?
i tested your Code with the following Ajax listenerMethod:
public final void search(AjaxBehaviorEvent event){
System.out.println("search: "+this.searchString);
}
and its being fired also with empty Strings.
So your Problem is in your searchForDoctorsByName Method in your bean, you have to reset (reInit) your DB-Items List if entered String is emtpy. So your Problem is in your SQL statement not in ajax.
I have a primefaces multiple select table populated from a backing bean. I am using the table.getSelectedRowsCount() javascript widget var to validate atleast one selection and it is working fine.
I now want to throw up a javascript confirmation dialog based on the state of the selected rows. for ex I have a button at the bottom of the table for printing the details of selected rows. I need to check a certain field of the bean and then allow printing.
IN pseudo code
if (#{bean.isComplete})
allowPrinting();
else
// alert user that this row is not yet in complete state
Update and panelGroup on button ajax event as shown in follow.
<h:panelGroup id="validateRerpot">
<h:panelGroup rendered="#{bean.isComplete}">
<script type="text/javascript">alert('show Dialog inplace');</script>
</h:panelGroup>
</h:panelGroup>
Try to update validateReport panel
I'm curious about how to get the row number of an element inside the <p:dataTable>.
<p:dataTable id="userDataTable" value="#{bean.rows}" rowIndexVar="rowIndex">
<p:column headerText="RowCounter">
<p:commandLink id="row#{rowIndex+1}" actionListener="#{bean.getRows}">
<h:outputText value="Show Row #{rowIndex+1}" />
</p:commandLink>
</p:column>
</p:dataTable>
Bean:
public void getRows(ActionEvent ae) {
System.out.println(ae.getComponent().getId().toString());
}
Always prints row1, no matter which <p:commandLink> is clicked. What am I missing?
As to your concrete problem, the id attribtue of a JSF component is evaluated during view build time. However, the #{rowIndex} is only set during view render time. Thus, at the moment the id attribute is evaluated, the #{rowIndex} is nowhere been set and defaults to 0. This problem has essentially exactly the same grounds as already answered and explained here: JSTL in JSF2 Facelets... makes sense? Note thus that there's only one <p:commandLink> component, not multiple. It's just that it's been reused multiple times during generating HTML (everytime with the same component ID!).
To fix it, just use id="row" instead. The dynamic ID makes no sense in this particular case. JSF would already automaticlaly prepend the row index (check generated HTML output to see it). I'm not sure why exactly you incorrectly thought that you need to manually specify the row index here, so it's hard to propose the right solution as there are chances that you actually don't need it at all. See also How can I pass selected row to commandLink inside dataTable?
For the case you really need the row index, here's how you could obtain it:
Integer rowIndex = (Integer) ae.getComponent().getNamingContainer().getAttributes().get("rowIndex");
The UIComponent#getNamingContainer() returns the closest naming container parent which is in your particular case the data table itself, in flavor or UIData which in turn has thus the rowIndex property. You can alternatively also do so, which is a bit more self documenting:
UICommand commandLink = (UICommand) ae.getComponent();
UIData dataTable = (UIData) commandLink.getNamingContainer();
Integer rowIndex = dataTable.getRowIndex();
On a JSF page for viewing data, I've an OpenFaces datatable with sorting and column reordering enabled saved to appropriate backing bean properties (via: sortColumnId, sortAscending, columnsOrder attributes on the o:dataTable element). On a corresponding inline edit page (where through custom code individual lines of the table can be saved one at a time by the user), the columnsOrder of the datatable is linked to the same property so the columns appear in the same order as on the view page, but the o:columnReordering element is not present in the datatable to prevent column reordering on the edit page. This is required because the AJAX call initiated by moving column fails, due to an error in the partial response XML, to update the table. (There are other requirements too which mean the table should be prevented from being updated via AJAX on the edit page.)
I want to be able to have the datatable on the edit page sorted in the same order as on the view page but with sorting disabled too. However, this doesn't seem possible in OpenFaces. I've linked the datable on the edit page to the same backing bean properties, but for the sorted column to display as sorted, the o:column tag needs to have a sortingExpression attribute. When that attribute is added to the column, that column becomes sortable by the user being able to click on the column header. When not added, the column is not sortable by the user but the table is also not sorted by that column even though it's specified in the backing bean property as being the column to sort by.
Using JavaScript run by JQuery once the DOM has been created, I've tried overwriting the function called by the click event on the 'th' element of the OpenFaces column header but after calling the function, the AJAX call to sort and refresh the table is still called. The code used is:
in Edit.xhtml:
<script type="text/javascript">
$(document).ready(function() {
$('#doorNumberColumnHeader').parents('th').onclick = null;
$('#doorNumberColumnHeader').parents('th').click(function(event) {
alert("Preventing AJAX call");
if (event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
}
return false;
});
});
</script>
within OpenFaces datatable of Edit.xthml:
<o:column id="doorNumberColumn" sortingExpression="#{submission.doorNum}" fixed="true" width="50px">
<f:facet name="header">
<h:outputText value="#{bundle.SubmissionDoorNumber}" id="doorNumberColumnHeader"/>
</f:facet>
<h:outputText value="#{submission.doorNum}"/>
</o:column>
Is there a better way of attempting to prevent the AJAX call to stop the user being able to change the sort order of the table?
Thanks.
For those who may be interested, I found the answer to my question was to overwrite the OpenFaces JavaScript _reload() function after the DOM has been created. I understand this may prevent any OpenFaces component on the same page from making AJAX calls (although on the page in question I only have the one datatable so that's not a problem.)
<script type="text/javascript">
$(document).ready(function() {
// Prevent OpenFaces datatable component from sending AJAX requests!
window.OpenFaces.Ajax._reload = function(one, two, three) {
// Do nothing!
};
});
</script>
This solution does not prevent other AJAX calls from being made within the page so an a4j:commandButton can still be used.