I have a scrollable dataTable with 100+ records when I add a new record (outside the default viewable area)and update the datatable the dataTable gets loaded from record 0, whereas I need datatable view at the previous position.
My dataTable code
<p:dataTable id="DataTable" value="#{dtMB.selectDataModel}" var="test" scrollable="TRUE" scrollHeight="500" styleClass="day-column2" selectionMode="single" >
<ui:insert name="TableInsert" >
<ui:include src="test.xhtml" />
</ui:insert>
</p:dataTable>
Command Button (inside a dialog) which updates the Datatable
<p:commandButton id="saveNew" value="Save" type="submit" process="#parent" onsuccess="addNew.hide()" action="#{dtMB.addNew()}" update=":FORM:usrMsg :FORM:TABView:DataTable"/>
currently I need to scroll back to the n'th record to see what was added or do any updates etc.
Is there any option in primeface datatable, or I need to write a javascript for the same.
I did the above using the following post
primeface datatable scrollbar position
datatable scroll
my code
script
function saveScrollPos() {
var scrollPos = jQuery('#receptionFORM\\:receptionTV\\:scheduleDataTable .ui-datatable-scrollable-body').prop('scrollTop');
document.getElementById('receptionFORM:scrollPos').value = scrollPos;
}
function autoScroll() {
var scrollPos = document.getElementById('receptionFORM:scrollPos').value;
jQuery('#receptionFORM\\:receptionTV\\:scheduleDataTable .ui-datatable-scrollable-body').animate({scrollTop:scrollPos}, scrollPos);
}
HiddenInput
<h:inputHidden id="scrollPos" />
In Ajax event of datatable row select
onstart="saveScrollPos()"
The below code in CommandButton while saving record
oncomplete="autoScroll()"
Related
I have a p:datatable in primefaces and i have different listeners for differents ways to select row event in datatable.
I need identify when the selected row in the table is already selected, how can i do that?
I need this because i dont wonna that p:blockUI runs when i select row in the table that is already selected.
There is my page code:
...
<pe:blockUI autoShow="true"
source="itemsDT"
event="rowSelect"
target=":processTab">
<au:loading />
</pe:blockUI>
<p:dataTable widgetVar="processesTable"
id="itemsDT"
var="item"
value="
{tasksbacking2.availableProcesses}"
selection="#{tasksbacking2.selectedProcess}"
rowKey="#{item.id}"
tableStyleClass="table
table-condensed table-bordered"
resizableColumns="true">
<p:ajax event="rowSelect"
listener="#{tasksbacking2.onClickFillDetails}"
update="#this,:processTab,:menuForm:menuBar" />
...
</p:dataTable>
...
On managed bean i have this listener:
...
public void onClickFillDetails(SelectEvent event) {
AnoProcess clickedProcess = (AnoProcess) event.getObject();
setSelectedProcess(clickedProcess);
Movement currentMovement = this.getProcessesLastMovement().get(clickedProcess);
if (currentMovement != null && !currentMovement.isViewed()) {
markAsRead(processes);
}
...
}
Here is the script to check for duplicate click on same row.
Put this script below your p:dataTable code.
<script type="text/javascript">
var prevRow ;
function checkDupRowClick(){
var currRow = $('tr.ui-widget-content.ui-datatable-selectable[aria-selected="true"]');
if($(currRow).is($(prevRow))){
//selected or clicked same row so return FALSE to prevent p:ajax from executing
return false;
}else{
//selected or clicked different row so return TRUE to allow p:ajax to execute
prevRow = currRow;
return true;
}
}
</script>
AND use function as a return parameter for p:ajax
<p:ajax event="rowSelect" onstart="return checkDupRowClick();" />
Post comment if you require more explanation.
I think that you need is some function in js and apply this in onstart.
like that
<p:ajax event="rowSelect" onstart="???" />
I have a primefaces datatable i need to display (selected row number) of (total number of rows) in the JSF page.I could get the row numbers displayed in one of the columns using rowIndexVar attribute but i am not getting any idea to display the same numbers separately in the input text on row select.
What should i need to do in JSF page or managed bean to get selected row number.
Please help me in this regard.
Below is my JSF page
<p:dataTable id="workSpaceList" var="data"
value="#{workSpaceBean.lpInfoList}" widgetVar="multiSelection"
selection="#{workSpaceBean.selectedRows}" resizableColumns="true"
liveScroll="true" scrollRows="55" scrollWidth="85%"
scrollHeight="81%" styleClass="datatable"
scrollable="true" rowIndexVar="rowIndex"
filteredValue="#{workSpaceBean.filteredWorkSpaceItems}">
<p:column selectionMode="multiple" style="width:3%" />
<p:column headerText="#" style="width:3%">
#{rowIndex+1}
</p:column>
<p:column headerText="Insured" filterBy="#{data.insuredName}"
sortBy="#{data.insuredName}" style="width:24%">
<h:outputText value="#{data.insuredName}" />
<!-- style="width:250px" -->
</p:column>
<p:column headerText="City" filterBy="#{data.custAddress_City}"
sortBy="#{data.custAddress_City}" style="width:12%">
<h:outputText value="#{data.custAddress_City}" />
</p:column>
.
.
.
.
</p:dataTable>
I believe that there's not a straight forward way to do so. Although using two ajax requests is not pretty, you can at least achieve the result you expect when using plain PrimeFaces. You can reduce this to one call if you replace the p:ajax with the PrimeFaces extensions pe:javascript which does not do a roundtrip to the server
Every row (tr) rendered by your datatable has a attribute called data-rk with your rowKey and another attribute called data-ri with your rowIndexVar value.
You can get the data-rk attribute through dtWidgetVar.selection (dtWidgetVar is the name of the widgetVar in your datatable).
You can now send the indexRow to your model using a remoteCommand
Here is the code I used to test it:
The View
<p:remoteCommand name="displayIndex" process="#this" update="index" actionListener="#{viewMBean.displayRowIndex}"/>
<p:dataTable id="dt" var="data"
value="#{viewMBean.dataModel}"
selection="#{viewMBean.selectedRow}"
selectionMode="single"
widgetVar="dtVar"
rowIndexVar="index">
<p:ajax event="rowSelect"
oncomplete="displayIndex([{name:'index', value:jQuery('tr[data-rk=' + dtVar.selection + ']').attr('data-ri')}])" process="#this" />
<p:column headerText="#">
#{index + 1}
</p:column>
<p:column headerText="Dados">
#{data.name}
</p:column>
</p:dataTable>
<br />
Row Index: <p:inputText id="index" value="#{viewMBean.index}" />
Managed Bean
public void displayRowIndex() {
FacesContext context = FacesContext.getCurrentInstance();
Map map = context.getExternalContext().getRequestParameterMap();
String pIndex = (String) map.get("index");
index = Integer.parseInt(pIndex);
}
In case you are using checkbox selection, you can retrieve the selected indexes like this:
function beforeDisplayingIndexes(){
var indexes = "";
jQuery("tbody .ui-chkbox-box").each(function(){
if (jQuery(this).hasClass("ui-state-active")){
indexes = indexes + (indexes === "" ? "" : ",") + jQuery(this).closest("tr").attr("data-ri");
}
});
//for debuging only
console.log(indexes);
displayIndex([{name:'index', value:indexes}])
}
You should now be able to make the proper modification to your code to make use of that.
I'm surprised by the complex solution in the other answer. Assuming you you have the #{workSpaceBean.lpInfoList} serverside when doing the 'select', you can easily do (code according to the PrimeFaces showcase, adapt according to your needs)
<p:ajax event="rowSelect" listener="#{dtSelectionView.onRowSelect}" update="..." />
public void onRowSelect(SelectEvent event) {
int rownum = cars.indexOf((Car)event.getObject());
}
In primefaces I have a confirm dialogue box and when I confirm the delete button my rows in the database are deleted however the page is not updated. Am I missing something that is not updating the page. My dialogue box is defined as below.
<h:form id="searchForm">
<p:commandButton id="showDialogButton" value="Delete Data" onclick="confirmation.show()"
style="margin:20px" type="button" immediate="true" />
<p:confirmDialog id="confirmDialog" message="Are you sure you want to delete all the data for this submission?"
header="Initiating delete process" severity="alert" widgetVar="confirmation">
<p:commandButton id="confirm" value="Yes Sure" update=":searchForm:rowDataTable" oncomplete="confirmation.hide()"
actionListener="#{myDataBean.deleteData}" immediate="true" ajax="true"/>
<p:commandButton id="decline" value="Not Yet" onclick="confirmation.hide()" type="button" immediate="true"/>
</p:confirmDialog>
In the same form I have defined a datatable
<p:dataTable var="row"
value="#{myDataBean.entries}"
id="rowDataTable" paginator="true"
rows="30"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="10,20,30"
>
which has a subtable inside it that shows all the data
<p:subTable id="rowSubTable" var="details" value="#{row.data}">
In my bean I have the following action listener. After the action listener is completed it calls the load intial view method to reload the data because of a pre render view event i have defined.
public List<SubmissionRow> entries = new ArrayList<SubmissionRow>();
public void loadInitialView() {
if (!postback) {
List<Submission> data = loadData();
//sort data and build entries list
}
}
#Transactional
public void deleteData(ActionEvent actionEvent) {
submission.deleteRows(submissionBean.getSubmission());
entries.clear();
postback = false;
}
As there was only the table visible on my page I just reloaded the page from the action listener using the external context. This way the datatable got updated.
I have a Prime Faces p:dialog that has been resized while new components are inserted when opened ('show' state). However its position doesn't change and it's size is increasing from the down left corner until the page bottom.
I need to reposition it every time I render new components dynamically. Is there any JavaScript function I can call to its widget to reposition?
I'm using PrimeFaces 3.5 with Mojarra 2.1.13.
I had a similar situation with a TabView inside a dialog. The TabView content was dynamically loaded.
<p:dialog widgetVar="dialogWidgetVar">
<p:tabView value="#{tabBean.tabs}" var="tabsVar"
onTabShow="PF('dialogWidgetVar').initPosition();" dynamic="true">
<p:tab id="Tab#{tabsVar.id}" title="#{tabsVar.name}">
...
</p:tab>
</p:tabView>
</p:dialog>
As you can see it will call the function initPosition() with every change of a Tab. This function will reposition your dialog. You can use this function in several cases.
http://forum.primefaces.org/viewtopic.php?f=3&t=16893
This is a method that should work in your case :
Bean code :
#ManagedBean
#ViewScoped
public class Bean
{
private boolean visible;
public void setVisible(boolean visible)
{
this.visible = visible;
}
public boolean getVisible()
{
return this.visible;
}
public void onBeforeShowDialog(AjaxBehaviorEvent event)
{
visible = true;
}
public void onBeforeHideDialog(AjaxBehaviorEvent event)
{
visible = false;
}
}
View code :
<h:commandButton value="Show dialog">
<f:ajax listener="#{bean.onBeforeShowDialog}" render="dialog" />
</h:commandButton>
<p:dialog id="dialog" visible="#{bean.visible}">
content
<h:commandButton value="Hide dialog">
<f:ajax listener="#{bean.onBeforeHideDialog}" render="dialog" />
</h:commandButton>
</p:dialog>
A second method should also work is by JavaScript :
To add in <h:head /> :
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<script>
function centerAndShowDialog(dialog)
{
$(dialog).css("top",Math.max(0,(($(window).height() - $(dialog).outerHeight()) / 2) + $(window).scrollTop()) + "px");
$(dialog).css("left",Math.max(0, (($(window).width() - $(dialog).outerWidth()) / 2) + $(window).scrollLeft()) + "px");
dialog.show();
}
</script>
View code :
<p:commandButton id="basic" value="Show Dialog" onclick="centerAndShowDialog(dlg);" type="button" />
<p:dialog id="dialog" header="Dynamic Dialog" widgetVar="dlg" dynamic="true">
Content
</p:dialog>
Note : Since I'm not using PrimeFaces, I've not tested this code so I hope it work well, but the idea is here!
Using PrimeFaces p:gmap component.
I have a page with a gmap component with a set of markers.
I want to display the street address in the gmapInfoWindow and pass it to the backing bean as well.
When I click on the map marker, I call a javascript function to get the reverse geocoder address.
I can fetch the address and display it in a javascript alert dialog, but I can't get it to fill the backing bean variable or in the info marker.
The variable does get filled, but it does not get updated until the next time I click on the marker.
As a result, the addresses are always one marker click behind.
Does anyone know how I can get the address to update during the current page session?
Thanks.
The backing bean code onMapMarkerSelect just has a System.out.println statement to show the mapAddress variable.
Here is the page code:
<h:form prependId="false" >
<p:gmap id="gmap" center="#{mappingSessionBean.mapCenter}" zoom="#{mappingSessionBean.mapZoom}" type="HYBRID" rendered="true"
style="#{mappingSessionBean.polygonGmapStyle}" onPointClick="handlePointClick(event);"
model="#{mappingSessionBean.mapModel}" fitBounds="#{mappingSessionBean.fitBoundsFlag}"
widgetVar="map" >
<p:ajax id="gmapAjax" event="overlaySelect" immediate="true" onstart="handlePointClick(event);" listener="#{mappingSessionBean.onMapMarkerSelect}" />
<p:gmapInfoWindow id="infoWindow" >
<p:outputPanel >
<h:panelGrid columns="1" >
<h:outputText id="infoWindowTitle" value="#{mappingSessionBean.selectedMarker.title}" />
<h:outputText id="infoWindowAddress" value="#{mappingSessionBean.mapAddress}" rendered="true" />
<p:commandButton value="Zoom In" action="#{mappingSessionBean.selectedViewInfoListener}" update="gmap" />
</h:panelGrid>
</p:outputPanel>
</p:gmapInfoWindow>
</p:gmap>
<h:inputHidden id="address" value="#{mappingSessionBean.mapAddress}" />
</h:form >
<script type="text/javascript" >
function handlePointClick(event) {
if(navigator.geolocation)
{
browserSupportFlag = true;
var latlng = event.latLng;
geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if( status == google.maps.GeocoderStatus.OK )
{
alert( results[0].formatted_address );
document.getElementById('address').value = results[0].formatted_address;
document.getElementById('infoWindowAddress').value = results[0].formatted_address;
}
else
{
alert( "Geocoder failed due to: " + status );
}
});
}
else
{
alert( "No Geolocation");
}
}
</script>
Here is a general solution, I guess you can do better if you will find a way to trigger an event on inputHidden without the use of the button
b.t.w : jQuery comes with primefaces so you can use it without any additional includes
instead of
<h:inputHidden id="address" value="#{mappingSessionBean.mapAddress}" />
place
<f:ajax listener="#{mappingSessionBean.myajax}" execute="address">
<h:inputHidden id="address" value="#{mappingSessionBean.mapAddress}" />
<h:commandButton id="addressBtn" style="display:none"/>
</f:ajax>
(you can replace execute="address" with execute="#form")
and in js code replace
document.getElementById('address').value = results[0].formatted_address;
with
jQuery("#address").val(results[0].formatted_address);
jQuery("#addressBtn").click(); // this will trigger the ajax listener
and finally in your bean add the implementation of the ajax listener itself
public void myajax(AjaxBehaviorEvent event) {
System.out.println(getMapAddress());
}