Primefaces multiple select checkbox bean values in Javascript function - jsf

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

Related

Primefaces Data Table actionListener for inline cell editing

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

Can I have both both radio selection and row selection in a p:dataTable

I have a p:dataTable which needs to have both radio selection and row selection.
In primefaces.org/showcase we have checkbox and row selection but with multiple selection and only row selection and only radiobutton selection.
Below is my code
<p:dataTable value="#{streetListBean.streetList}" var="street"
selection="#{streetListBean.selectedStreet}"
rowKey="#{street.streetId}">
<p:column selectionMode="single" style="text-align:center" width="5%"/>
<p:column headerText="#{msgs['label.streetName']}">
<p:outputLabel value="#{street.streetName}"/>
</p:column>
<p:column headerText="#{msgs['label.postalCode']}">
<p:outputLabel value="#{street.postalCode}"/>
</p:column>
<p:column headerText="#{msgs['label.location']}">
<p:outputLabel value="#{street.locName}"/>
</p:column>
</p:dataTable>
in above datatable we have only radio selection, I need row selection too. please help
One thing to ALWAYS remember, is that client-side everything is html/javascript/css (with the help of jQuery in this case).
PrimeFaces 7.0 (and up) has a onRowClick attribute but I'm not sure if this is suitable for this case. A solution that always works (older and newer versions) is composed of several really simple steps (just remember the first statement in this answer)
Start with jQuery for getting Click event on a Table row. For this we need to check where the actual clicks need to be on. Using the id of the datatable for the first part is not a bad choice. But what is the id? Well, for this there also is a Q/A in Stackoverflow. How can I know the id of a JSF component so I can use in Javascript
For the PrimeFaces showcase this actually is #form\\:radioDT" But within that whole html structure, we only need to click on certain rows (e.g. not in headers or the likes). This therefor becomes something like
$("#form\\:radioDT").on("click", "tbody.ui-datatable-data tr", function() {
console.log(this);
});
If you try this in the PrimeFaces showcase, you'll see clicks on the row being logged (including clicks that originate on the radiobutton)
The next step would be to Simulate a click on 'a' element using javascript/jquery
But click where? Well, that can be easily found with the browser developer tools as well. Related to the tr that was clicked (this) it is:
$(this).find(".ui-selection-column .ui-radiobutton-icon").click(); //javascript version (selectors can be different, many work). Alternative is using jquery .trigger('click')
Combining this results in
$("#form\\:radioDT").on("click", "tbody.ui-datatable-data tr", function() {
console.log(this);
$(this).find(".ui-selection-column .ui-radiobutton-icon").click();
});
Which unfortunately results in a 'too much recursion' error. This is caused by the fact that a click on the radio button bubbles up to the row which triggers a click on the radiobutton which... you get the point.
So the first thought is to prevent clicks bubbling up. Unfortunately, it is not bubling up from our function but from the click on the radiobutto so we need to adapt our source. Again existing Q/A in stackoverflow help: jQuery trigger click gives "too much recursion"
What you do is check if the click on the row originated as a click on anything but the radiobutton. Only then simulate the click. For this we need the event and from the event the target and with the same selector as for the click we do a check:
$("#form\\:radioDT").on("click", "tbody.ui-datatable-data tr", function(event) {
if ( !$(event.target).is('.ui-selection-column .ui-radiobutton-icon')) {
console.log("Simulate click on radiobutton: ", event.target);
$(this).find(".ui-selection-column .ui-radiobutton-icon").click();
} else {
console.log("Skip: ", event.target);
}
}
);
Keep in mind that $("#form\\:radioDT") is based on the full client id of the datatable component in the PrimeFaces showcase. Replace it with yours.
How and where to add this to your page and how to re-add it in the case of ajax updates is also covered in Q/A in Stackoverflow.

PrimeFaces paginator selection

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

Disabling ability to change the sort-order of a sorted OpenFaces Datatable

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.

JSF: How to get the selected item from selectOneMenu if its rendering is dynamic?

At my view I have two menus that I want to make dependent, namely, if first menu holds values "render second menu" and "don't render second menu", I want second menu to be rendered only if user selects "render second menu" option in the first menu. After second menu renders at the same page as the first one, user has to select current item from it, fill another fields and submit the form to store values in database. Both the lists of options are static, they are obtained from the database once and stay the same. My problem is I always get null as a value of the selected item from second menu. How to get a proper value? The sample code of view that holds problematic elements is:
<h:selectOneMenu id="renderSecond" value="#{Bean.renderSecondValue}"
valueChangeListener="#{Bean.updateDependentMenus}"
immediate="true"
onchange="this.form.submit();" >
<f:selectItems value="#{Bean.typesOfRendering}" />
</h:selectOneMenu><br />
<h:selectOneMenu id="iWillReturnYouZeroAnyway" value="#{Bean.currentItem}"
rendered="#{Bean.rendered}" >
<f:selectItems value="#{Bean.items}" />
</h:selectOneMenu><br />
<h:commandButton action="#{Bean.store}" value="#Store" />
However, if I remove "rendered" attribute from the second menu, everything works properly, except for displaying the menu for all the time that I try to prevent, so I suggest the problem is in behavior of dynamic rendering. The initial value of isRendered is false because the default item in first menu is "don't render second menu". When I change value in first menu and update isRendered with valueChangeListener, the second menu displays but it doesn't initialize currentItem while submitting.
Some code from my backing bean is below:
public void updateDependentMenus(ValueChangeEvent value) {
String newValue = (String) value.getNewValue();
if ("render second menu" == newValue){
isRendered = true;
} else {
isRendered = false;
}
}
public String store(){
System.out.println(currentItem);
return "stored";
}
If you're using the rendered attribute on UIInput and UICommand components, then you have to make sure that the rendered condition evaluates exactly the same way in the subsequent request (during submitting the form) as it was during the initial request (during displaying the form). When it evaluates false, then the request values won't be applied/validated and the model values won't be updated and no action will be invoked for the component(s) in question.
An easy fix is to put the bean in the session scope, but this has caveats as well (poor user experience when opening same page in multiple browser tabs/windows). On JSF 2.0 you could use the view scope instead. On JSF 1.x you would use Tomahawk's t:saveState for this.
The problem arises only when we have "don't render" as a first option. I decided to change the values in the database and now I have "render second menu" as a first one. With such an approach, everything works fine.

Resources