I'm working with Primefaces 3.4, Apache Tomcat 7 and Java EE. I read the GoogleMaps API but I can't get this feature to work.
I have a PrimeFaces input box, and when i write an address on it, i want to suggest other addresses provided by GoogleMaps library.
Nothing happens when a put the JavaScript code on my XHTML. I have the library of GoogleMaps too.
This is my XHTML:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initia(domicilioDesde, domicilioHasta) {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var oldDirections = [];
var currentDirections = null;
var cordoba = " ,Cordoba, Argentina";
var direccion = domicilioDesde; /* '#{busquedaplayaMB.direccionDesde}'; */
var start = direccion.concat(cordoba);
var fin = domicilioHasta; /*'#{busquedaplayaMB.playaselected.domicilio}';*/
var end = fin.concat(cordoba);
var request = {
origin : start,
destination : end,
travelMode : google.maps.DirectionsTravelMode.DRIVING
}
var myOptions = {
zoom : 13,
center : new google.maps.LatLng(#{busquedaplayaMB.latitudCentro},#{busquedaplayaMB.longitudCentro}),
mapTypeId : google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
directionsDisplay = new google.maps.DirectionsRenderer({
'map' : map,
'preserveViewport' : true,
'draggable' : true
});
directionsDisplay.setPanel(document
.getElementById("directions_panel"));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
dlg2.show();
}
function undo() {
currentDirections = null;
directionsDisplay.setDirections(oldDirections.pop());
if (!oldDirections.length) {
setUndoDisabled(true);
}
}
function setUndoDisabled(value) {
document.getElementById("undo").disabled = value;
}
</script>
<h:form id="form">
<p:growl id="messages" showSummary="false" autoUpdate="true"
globalOnly="true" />
<div align="left" style="margin: 10px 0 10px 0;">
<p:panel>
<h:panelGrid columns="1" width="100%" cellspacing="5"
cellpadding="5">
<h:panelGrid columns="2" width="80%">
<p:column style="vertical-align:text-center;">
<h:panelGrid columns="2">
<p:column>
<p:watermark for="direccionBusqueda"
value="Dirección de búsqueda" />
<p:inputText id="direccionBusqueda"
value="#{busquedaplayaMB.direccionBusqueda}" required="true"
requiredMessage="Campo dirección de búsqueda obligatorio"
style="width:250px;">
<p:ajax event="blur" update="direccionBusquedaMsg" />
</p:inputText>
</p:column>
<p:column>
<p:message id="direccionBusquedaMsg" display="icon"
for="direccionBusqueda" />
</p:column>
</h:panelGrid>
</p:column>
<p:column>
<div align="center">
<h:outputLabel value="N° de cuadras: " />
<h:outputLabel id="nroCuadras"
value="#{busquedaplayaMB.distancia}" />
<h:inputHidden id="distancia"
value="#{busquedaplayaMB.distancia}" />
<p:slider for="distancia" minValue="1" maxValue="50"
style="width:100px;" update="nroCuadras" display="nroCuadras" />
</div>
</p:column>
</h:panelGrid>
<h:panelGrid columns="5" cellspacing="5" cellpadding="5"
width="100%">
<p:column style="vertical-align:text-center;">
<p:selectOneMenu value="#{busquedaplayaMB.categoriaParameter}"
effect="fade" style="width:160px;height:25px;line-height:17px;">
<f:selectItem itemLabel="Todas las categorías"
itemValue="#{null}" />
<f:selectItems
value="#{categoriaVehiculoMB.categoriaVehiculoList}"
var="categoria" itemValue="#{categoria}"
itemLabel="#{categoria.nombre}" />
<f:converter converterId="categoriaVehiculoConverter" />
</p:selectOneMenu>
</p:column>
<p:column style="vertical-align:text-center;">
<p:selectOneMenu value="#{busquedaplayaMB.tipoEstadiaParameter}"
effect="fade" style="width:160px;height:25px;line-height:17px;">
<f:selectItem itemLabel="Todas los tipos estadías"
itemValue="#{null}" />
<f:selectItems value="#{tipoEstadiaMB.tipoEstadiaList}"
var="tipoEstadia" itemValue="#{tipoEstadia}"
itemLabel="#{tipoEstadia.nombre}" />
<f:converter converterId="tipoEstadiaConverter" />
</p:selectOneMenu>
</p:column>
<p:column style="vertical-align:text-center;">
<div align="right">
<h:panelGrid columns="2">
<p:selectBooleanCheckbox id="check"
value="#{busquedaplayaMB.checkPromociones}" />
<p:outputLabel for="check" value="Sólo con promociones" />
</h:panelGrid>
</div>
</p:column>
<p:column>
<div align="right">
<p:commandButton id="btnBuscarAvanzado" update="playas,mapa"
value="Buscar" action="#{busquedaplayaMB.busquedaAvanzada}"
ajax="false" icon="ui-icon-search" style="width:85px;" />
</div>
</p:column>
</h:panelGrid>
</h:panelGrid>
</p:panel>
</div>
<div>
<p:panel>
<f:view contentType="text/html">
<!-- <h1>Playas encontradas:</h1> -->
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<p:gmap center="#{busquedaplayaMB.coordenadas}" zoom="14"
type="ROADMAP" model="#{busquedaplayaMB.advancedModel}"
style="width:99,5%; height:350px;">
<p:ajax event="overlaySelect"
listener="#{busquedaplayaMB.onMarkerSelect}" />
<p:gmapInfoWindow>
<ui:fragment
rendered="#{busquedaplayaMB.marker.data.playa == null}">
<div align="center">
<ui:fragment rendered="#{busquedaplayaMB.usuario == null}">
<h:outputText style="font-weight:bold;" value="¡Usted está aquí!" />
</ui:fragment>
<ui:fragment rendered="#{busquedaplayaMB.usuario != null}">
<h:panelGrid column="1" style="text-align:center;"
cellspacing="0px" cellpadding="0px">
<p:column>
<h:graphicImage library="fotos_perfil_usuarios"
name="sinfoto.jpg"
styleClass="bordes-foto-perfil-comentario"
rendered="#{busquedaplayaMB.usuario.fotoUsuario == null}" />
<h:graphicImage library="fotos_perfil_usuarios"
name="#{busquedaplayaMB.usuario.nombreUser}.jpg"
styleClass="bordes-foto-perfil-comentario"
rendered="#{busquedaplayaMB.usuario.fotoUsuario != null}" />
</p:column>
<p:column>
<h:outputText style="font-weight:bold;"
value="#{busquedaplayaMB.usuario.nombre} #{busquedaplayaMB.usuario.apellido}" />
</p:column>
<p:column>
<h:link id="linkUsuario" tittle="Ir a mi perfil"
value="Ir a mi perfil" outcome="/cliente/perfilcliente" />
</p:column>
</h:panelGrid>
</ui:fragment>
</div>
</ui:fragment>
<ui:fragment
rendered="#{busquedaplayaMB.marker.data.playa != null}">
<div align="center">
<h:panelGrid column="1" style="text-align:center;"
cellspacing="0px" cellpadding="0px">
<p:column>
<h:graphicImage library="fotos_perfil_playas"
name="#{busquedaplayaMB.marker.data.id}_#{busquedaplayaMB.marker.data.nombreFoto}"
styleClass="bordes-foto-perfil-comentario"
rendered="#{busquedaplayaMB.marker.data.nombreFoto != null}" />
<h:graphicImage library="fotos_perfil_playas"
name="sinfoto.jpg"
styleClass="bordes-foto-perfil-comentario"
rendered="#{busquedaplayaMB.marker.data.nombreFoto == null}" />
</p:column>
<h:outputText style="font-weight:bold;"
value="#{busquedaplayaMB.marker.data.playa.nombreComercial}" />
<h:outputText
value="#{busquedaplayaMB.marker.data.playa.domicilio} - #{busquedaplayaMB.marker.data.playa.barrio.nombre}" />
<h:link id="link" tittle="Ir a playa" value="Ver información"
outcome="/viewperfilplaya.html?id=#{busquedaplayaMB.marker.data.playa.id}" />
</h:panelGrid>
</div>
</ui:fragment>
</p:gmapInfoWindow>
</p:gmap>
</f:view>
</p:panel>
</div>
<div style="margin: 5px;">
<p:dataTable id="playas" var="playa" paginator="true"
paginatorPosition="bottom" rows="5"
emptyMessage="¡No existen playas!"
value="#{busquedaplayaMB.playaResultadoBusqueda}">
<p:column headerText="Nombre Comercial" styleClass="column-font">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{playa.nombreComercial}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{playa.nombreComercial}"
styleClass="input-font" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Barrio" styleClass="column-font">
<h:outputText value="#{playa.barrio.nombre}" />
</p:column>
<p:column headerText="Domicilio" styleClass="column-font">
<h:outputText value="#{playa.domicilio}" />
</p:column>
<p:column headerText="Perfil" style="text-align:center; width:50px;">
<h:link id="verPerfil" title="Ver perfil"
outcome="/viewperfilplaya.html?id=#{playa.id}">
<h:graphicImage library="images/icons" name="go.png" />
</h:link>
</p:column>
<p:column headerText="Ruta" style="text-align:center; width:50px;">
<p:commandLink id="view2" oncomplete="dlgOrigen.show();"
title="¿Cómo llegar a esta playa?" update=":dlgO" process="#this">
<f:setPropertyActionListener value="#{playa}"
target="#{busquedaplayaMB.playaselected}" />
<h:graphicImage library="images/icons" name="search-map.png"
style="height:40px; width:40px" />
</p:commandLink>
</p:column>
</p:dataTable>
</div>
<!-- </h:form> -->
<p:dialog widgetVar="dlg2" width="800" height="400" modal="true"
id="dialog" draggable="false" closable="true">
<!-- <h:form id="frmComoLlegar"> -->
<f:facet name="header">
<h:outputText value="¿Cómo llegar a la playa?" />
</f:facet>
<div id="map_canvas" style="float: left; width: 65%; height: 100%"></div>
<div style="float: right; width: 35%; height: 100%; overflow: auto">
<div id="directions_panel" style="width: 100%"></div>
</div>
<f:facet name="footer" style="text-align=right;">
<p:commandButton id="undo" value="Volver"
style="float:right; width:274px; height: 42px" onclick="undo();"></p:commandButton>
</f:facet>
</p:dialog>
</h:form>
<p:dialog header="Dirección de origen" id="dlgO" widgetVar="dlgOrigen"
resizable="false" closable="true">
<h:form id="frmComoLlegar">
<h:panelGrid columns="2" cellspacing="10" cellpadding="10">
<h:outputLabel for="dirOrigen" value="Dirección de origen: " />
<p:inputText id="dirOrigen" required="true"
value="#{busquedaplayaMB.direccionDesde}"
onkeyup="if (event.keyCode == 13) { document.getElementById(':frmComoLlegar:siguiente').click(); return false; }" />
<p:column />
<p:column>
<div align="right">
<p:commandButton id="siguiente" value="Siguiente" ajax="true"
onclick="initia(jQuery('#frmComoLlegar\\:dirOrigen').val(), '#{busquedaplayaMB.playaselected}');"
update=":dialog" process="#this"
action="#{busquedaplayaMB.tomarDomicilioDesde}" />
</div>
</p:column>
</h:panelGrid>
</h:form>
</p:dialog>
I have implemented this feature using GMap3 jQuery Plugin (also in combination with JSF + Primefaces). See this for an example: https://github.com/jbdemonte/gmap3/blob/master/examples/autocomplete/autocomplete.html
Related
In my application i added java autocomplete to searchitem.
This item is working good. But it s not working after create row.
i recorded video to youtube.
https://www.youtube.com/watch?v=0FM52YNsDZY
page :
<p:autoComplete id="autocomplete" dropdown="true" value="#{126Controller.tesisAuto}" var="auto"
completeMethod="#{211Controller.complete}" forceSelection="true"
itemLabel="#{auto.tesisAdi}" itemValue="#{auto}">
<f:facet name="itemtip">
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="Tesis Adı: "/>
<h:outputText value="#{auto.tesisAdi}"/>
<h:outputText value="Şeflik Adı: "/>
<h:outputText value="#{211Controller.getSeflik(auto.seflikKodu)}"/>
<h:outputText value="Adres: "/>
<h:outputText value="#{auto.adres}"/>
</h:panelGrid>
</f:facet>
<p:ajax event="itemSelect" listener="#{126Controller.itemByTesisAuto()}" update=":126ListForm:display"/>
</p:autoComplete>
Complete method:
public List<211> complete(String query) {
return autoComplete(query);
}
public List<211> autoComplete(String auto){
List<211> completed = new ArrayList<211>();
for (211 m211: this.getFacade().getTesisByYetkiIsyeriKodu(yetkiSeflik)){
if(m211.getTesisAdi().startsWith(auto.toUpperCase())){
completed.add(m211);
}
}
return completed;
}
Create method:
public void create() {
persist(PersistAction.CREATE, "Oluşturma");
if (!JsfUtil.isValidationFailed()) {
items = null; // Invalidate list of items to trigger re-query.
}
}
Thanks god.
I solved. I added h:head and worked.
Thank u so much.
<p:panelGrid id="sef" columns="1" style="width: 100%">
<h:head>
<h:form>
<h:panelGrid columns="2" style="width: 100%">
<h:outputText value="Şeflik Seçiniz : " style="width: 20%" rendered="#{211Controller.yetkiliSeflikSayisi gt 1}"/>
<p:selectOneMenu id="seflik" value="#{211Controller.yetkiSeflik}" effect="fold" rendered="#{211Controller.yetkiliSeflikSayisi gt 1}" >
<f:selectItem itemLabel="Seçiniz" itemValue=""/>
<f:selectItems value="#{211Controller.list}"/>
<p:ajax update="autocomplete"/>
</p:selectOneMenu>
<h:outputText value="Tesis Seçiniz : " style="width: 20%"/>
<p:autoComplete id="autocomplete" dropdown="true" value="#{126Controller.tesisAuto}" var="auto"
completeMethod="#{211Controller.complete}" forceSelection="true"
itemLabel="#{auto.tesisAdi}" itemValue="#{auto}">
<f:facet name="itemtip">
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="Tesis Adı: "/>
<h:outputText value="#{auto.tesisAdi}"/>
<h:outputText value="Şeflik Adı: "/>
<h:outputText value="#{211Controller.getSeflik(auto.seflikKodu)}"/>
<h:outputText value="Adres: "/>
<h:outputText value="#{auto.adres}"/>
</h:panelGrid>
</f:facet>
<p:ajax event="itemSelect" listener="#{126Controller.itemByTesisAuto()}" update=":126ListForm:display :126ListForm:sef"/>
</p:autoComplete>
</h:panelGrid>
</h:form>
</h:head>
</p:panelGrid>
I have problem with "" component in my application. I have a datatable with 2 fields editable first is an inputtext and second field is a dateInput.
Inside fields I put to update value in list but when submit it to bean not updated the values.
Below is my page.xhtml and bean.
<p:dialog id="modalNovosParametrosRecesso" header="Salvar Novos Parâmetros de Estagiário"
widgetVar="widgetvarNovoParametro"
draggable="true" resizable="false"
closable="false" modal="true" width="630">
<h:outputText styleClass="modalRecessoAuto" value="#{msg.MN064}" escape="false" />
<br />
<h:panelGroup>
<br />
<p:dataTable id="tableRegRecessoAuto" var="recessoAuto"
value="#{parametroEstagiarioMB.visao.listaOcorrenciaRegistroRecesso}"
styleClass="hide-column-names" rowIndexVar="rowIndex" >
<p:column style="width:98px;">
<h:outputLabel value="#{rowIndex+1}º Recesso de " style="color: #0039BA" />
<p:inputText value="#{recessoAuto.diasRecesso}" size="2">
<p:ajax event="blur" update=":frmFiltro:tableRegRecessoAuto" ignoreAutoUpdate="true" global="false" />
</p:inputText>
<h:outputLabel value="dia(s) começando em " style="color: #0039BA" />
<p:inputMask value="#{recessoAuto.dtInicioOcorrencia}" mask="99/99/9999" size="10">
<f:convertDateTime pattern="dd/MM/yyyy" locale="pt_BR" />
<p:ajax event="blur" update=":frmFiltro:tableRegRecessoAuto" ignoreAutoUpdate="true" global="false"/>
</p:inputMask>
<h:outputLabel value=" e finalizando em " style="color: #0039BA; margin-left: 5px;"/>
<h:outputLabel id="dtLbl1" value="#{recessoAuto.dtFimOcorrencia}" style="color: #0039BA; margin-left: 5px;" >
<f:convertDateTime for="dtLbl1" pattern="dd/MM/yyyy" locale="pt_BR"/>
</h:outputLabel>
</p:column>
-->
<div style="padding-left: 170px;">
<p:commandLink styleClass="btnLaranja marginTop"
ignoreAutoUpdate="true" global="false" ajax="false" action="#{parametroEstagiarioMB.salvarRecessoPrimeiraParametrizacao()}"
update=":frmFiltro:tableRegRecessoAuto">
<span>Confirmar</span>
</p:commandLink>
<p:commandLink styleClass="btnLaranja marginTop"
id="btnCancelarRecessoAuto"
oncomplete="PF('widgetvarNovoParametro').hide();"
ignoreAutoUpdate="true" global="false" actionListener="#{parametroEstagiarioMB.cancelar}">
<f:setPropertyActionListener
target="#{parametroEstagiarioMB.visao.exibirModal}"
value="#{false}" />
<span>Cancelar</span>
</p:commandLink>
<p:commandLink styleClass="btnLaranja marginTop"
id="btnVerRegrasAuto"
oncomplete="PF('widgetvarModalRegras').show();"
ignoreAutoUpdate="true" global="false">
<span>Regras</span>
</p:commandLink>
</div>
</p:dialog>
My Bean:
public void salvarRecessoPrimeiraParametrizacao(){
int count = 0;
final DataTable dataTable = (DataTable) FacesContext.getCurrentInstance().getViewRoot()
.findComponent(":frmFiltro:tableRegRecessoAuto");
List<OcorrenciaPonto> teste = new ArrayList<OcorrenciaPonto>();
for(OcorrenciaPonto c : (List<OcorrenciaPonto>) dataTable.getValue()){
teste.add(c);
count+=1;
}}
datatable.getValues() not get new values and yes old values that displayed in screen.
Are you using getters and setters correctly?
Have you tried to use immediate="true" on input fields?
I saw you are using <p:ajax> . I had some troubles with this. Maybe, if you change to **<f:ajax>** this must works so well.
I'm using Mojarra, PF 3.5 SNAPSHOT, Tomcat 7.0.32 and trying to make a datatable update itself when changes have been done by other clients. I'm also using CDF beans along with MyCODI, #ViewAccessScoped.
When I was using 3.4, in-row editing (instead of in-cell editing) and standard #ConversationScoped it was working.
This is the xhtml:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:pe="http://primefaces.org/ui/extensions"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:t="http://myfaces.apache.org/tomahawk">
<ui:composition template="commonLayout.xhtml">
<ui:define name="content">
<p:growl id="growlmessage" showDetail="false" autoUpdate="true"/>
<p:contextMenu for="staffTable">
<p:menuitem value="Open" update="staffTable" icon="ui-icon-close" actionListener="#{staffbean.onOpen}" />
<p:menuitem value="Delete" update="staffTable" icon="ui-icon-close" onclick="confirmation.show()" />
</p:contextMenu>
<p:confirmDialog id="confirmDialog" message="#{text['viewedit.delete.confirm']}"
header="#{text['viewedit.delete.header']}" severity="alert" widgetVar="confirmation" appendToBody="true" closable="false" visible="false" >
<p:commandButton action="#{staffbean.onDelete}" ajax="true" value="Yes" oncomplete="confirmation.hide()" icon="ui-icon-check" />
<p:commandButton value="No" onclick="confirmation.hide()" type="button" icon="ui-icon-closethick" />
</p:confirmDialog>
<p:dataTable id="staffTable" var="staff" widgetVar="staffList" value="#{staffbean.objectList}" paginator="true" rows="15" paginatorPosition="bottom" paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" currentPageReportTemplate="#{text['table.staff.filter.count']}" rowsPerPageTemplate="15,25,50,100" emptyMessage="#{text['table.staff.filter.notfound']}" filteredValue="#{staffbean.filteredObject}" editable="true" editMode="cell" draggableColumns="true" rowKey="#{staff.id}" selection="#{staffbean.selectedObject}" selectionMode="single">
<f:facet name="header">
<p:columnGroup type="header">
<p:row>
<p:column colspan="4">
<h:outputText value="#{text['table.staff.header']}" />
</p:column>
</p:row>
<p:separator/>
<p:row>
<p:panelGrid columns="5" styleClass="headerGrid">
<p:column colspan="2">
<h:outputText value="#{text['table.filter.global']}" />
<p:inputText id="globalFilter" onkeyup="staffList.filter()" style="width:150px" />
</p:column>
<p:column colspan="2">
<p:selectOneMenu id="pageonly" value="#{staffbean.pageOnly}" >
<f:selectItem itemLabel="#{text['dataexporter.pageonly']}" itemValue="true" />
<f:selectItem itemLabel="#{text['dataexporter.entirepage']}" itemValue="false" />
<p:ajax event="change" listener="#{staffbean.exportXLS}" update="#form" immediate="true" />
</p:selectOneMenu>
<h:commandLink>
<p:graphicImage id="exportPage" value="/resources/img/excel.png" />
<p:dataExporter type="xls" target="staffTable" fileName="staff" pageOnly="#{staffbean.pageOnly}"/>
<p:tooltip for="exportPage" value="#{text['dataexporter.tooltip']}" showEffect="fade" hideEffect="fade" />
</h:commandLink>
</p:column>
</p:panelGrid>
</p:row>
</p:columnGroup>
</f:facet>
<p:column id="nameColumn" headerText="#{text['label.name']}" sortBy="#{staff.name}" filterBy="#{staff.name}" filterMatchMode="contains">
<p:cellEditor>
<f:facet id="nameoutput" name="output">
<h:outputText value="#{staff.name}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{staff.name}" style="width:100%" required="true" requiredMessage="#{text['validation.error.required.name']}"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column id="staffnoColumn" headerText="#{text['label.staffno']}" sortBy="#{staff.staffno}" filterBy="#{staff.staffno}" filterMatchMode="contains">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{staff.staffno}" />
</f:facet>
<f:facet id="staffliststaffno" name="input">
<p:inputText value="#{staff.staffno}" style="width:100%" required="true" requiredMessage="#{text['validation.error.required.staffno']}">
<pe:keyFilter regEx="/^\d+$/" preventPaste="false"/>
<f:validator validatorId="staffnoValidator" />
<f:validator validatorId="numericValidator" />
</p:inputText>
</f:facet>
</p:cellEditor>
</p:column>
<f:facet name="footer" id="footer">
There are #{fn:length(staffbean.objectList)} staff in total.
</f:facet>
<p:ajax event="cellEdit" listener="#{staffbean.onEdit}" update="#form" />
</p:dataTable>
</ui:define>
<ui:define name="socket">
<p:socket channel="/ba" >
<p:ajax event="message" update="ba_staffTable" />
</p:socket>
</ui:define>
</ui:composition>
Bean:
public void update(Object object) {
if (!getEm().getTransaction().isActive()) {
getEm().getTransaction().begin();
}
try {
get().merge(object);
get().getTransaction().commit();
} catch (PersistenceException e) {
if (ExceptionUtil.is(e, ConstraintViolationException.class) || ExceptionUtil.is(e, RollbackException.class)) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ResourceLoader.MESSAGES.getProperty("staff.error.dbconstraint"), null));
if (getEm().getTransaction().isActive()) {
getEm().getTransaction().rollback();
}
}
}
PushContextFactory.getDefault().getPushContext().push("/ba", "");
}
Your table id is staffTable not ba_staffTable
I have a very strange problem when I try to implement click on table row with AJAX. This is the JS code that I use for click on row:
//for tabs
$(document).ready(function () {
$("#tabs").tabs();
});
$(window).load(function() {
jsf.ajax.addOnEvent(function (data) {
if (data.status === "success") {
$("#tabs").tabs();
}
});
});
$("tr").not(':first').hover(
function () {
$(this).toggleClass('highlited');
// $(this).css("background","#707070");
},
function () {
$(this).toggleClass('highlited');
// $(this).css("background","");
}
);
function highlight(param) {
var row = jQuery(param).parent().parent().children();
row.toggleClass('highlited');
// row.css("background","#707070");
}
var inputs = document.getElementsByTagName("INPUT");
for (var i in inputs) {
if (inputs[i].checked) {
highlight(inputs[i]);
}
}
//for clicking on a row and opening new page
function addOnclickToDatatableRows() {
//gets all the generated rows in the html table
var trs = document.getElementById('form:dataTable').getElementsByTagName('tbody')[0]
.getElementsByTagName('tr');
//on every row, add onclick function (this is what you're looking for)
for (var i = 0; trs.length > i; i++) {
var cells = trs[i].cells;
for(var j=1; j < cells.length; j++){
cells[j].onclick = new Function("rowOnclick(this.parentElement)");
}
}
}
function rowOnclick(tr) {
var elements = tr.cells[0].childNodes;
for(var i = 0; elements.length > i; i++) {
if ((typeof elements[i].id != "undefined") && (elements[i].id.indexOf("lnkHidden") > -1)) {
//opne in a new window// window.open(elements[i].href);
location.href=elements[i].href
break;
}
}
return false;
}
This is the JSF page:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" type="image/x-icon" href="resources/css/themes/nvidia.com/images/favicon.ico" />
<link href="resources/css/helper.css" media="screen" rel="stylesheet" type="text/css" />
<link href="resources/css/dropdown.css" media="screen" rel="stylesheet" type="text/css" />
<link href="resources/css/default.advanced.css" media="screen" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="resources/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="resources/js/jquery-ui-1.8.18.custom.min.js"></script>
<link href="resources/css/jquery-ui-1.8.18.custom.css" media="screen" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="resources/js/tabs.js"></script>
</h:head>
<h:body onload="addOnclickToDatatableRows();">
<h1><img src="resources/css/images/icon.png" alt="DX-57" /> History Center</h1>
<!-- layer for black background of the buttons -->
<div id="toolbar" style="margin: 0 auto; width:1180px; height:30px; position:relative; background-color:black">
<!-- Include page Navigation -->
<ui:insert name="Navigation">
<ui:include src="Navigation.xhtml"/>
</ui:insert>
</div>
<div id="logodiv" style="position:relative; top:35px; left:0px;">
<h:graphicImage alt="Dashboard" style="position:relative; top:-20px; left:9px;" value="resources/images/logo_sessions.png" />
</div>
<div id="main" style="margin: 0 auto; width:1190px; height:700px; position:absolute; background-color:transparent; top:105px">
<div id="mainpage" style="margin: 0 auto; width:1190px; height:500px; position:absolute; background-color:transparent; top:80px">
<div id="settingsHashMap" style="width:750px; height:400px; position:absolute; background-color:r; top:20px; left:1px">
<h:form id="form">
<!-- The sortable data table -->
<h:dataTable id="dataTable" value="#{SessionsController.dataList}" binding="#{table}" var="item">
<!-- Check box -->
<h:column>
<f:facet name="header">
<h:outputText value="Select" />
</f:facet>
<h:selectBooleanCheckbox onclick="highlight(this)" value="#{SessionsController.selectedIds[item.aSessionID]}" />
<!-- Click on table code -->
<h:outputLink id="lnkHidden" value="HistoryLink.xhtml" style="display:none">
<f:param name="id" value="#{item.aSessionID}" />
</h:outputLink>
</h:column>
<!-- Row number -->
<h:column>
<f:facet name="header">
<h:commandLink value="№" actionListener="#{SessionsController.sort}">
<f:attribute name="№" value="№" />
</h:commandLink>
</f:facet>
<h:outputText value="#{table.rowIndex + SessionsController.firstRow + 1}" />
</h:column>
<h:column>
<f:facet name="header">
<h:commandLink value="Account Session ID" actionListener="#{SessionsController.sort}">
<f:attribute name="sortField" value="Account Session ID" />
</h:commandLink>
</f:facet>
<h:outputText value="#{item.aSessionID}" />
</h:column>
<h:column>
<f:facet name="header">
<h:commandLink value="User ID" actionListener="#{SessionsController.sort}">
<f:attribute name="sortField" value="User ID" />
</h:commandLink>
</f:facet>
<h:outputText value="#{item.userID}" />
</h:column>
<h:column>
<f:facet name="header">
<h:commandLink value="Activity Start Time" actionListener="#{SessionsController.sort}">
<f:attribute name="sortField" value="Activity Start Time" />
</h:commandLink>
</f:facet>
<h:outputText value="#{item.activityStart}" />
</h:column>
<h:column>
<f:facet name="header">
<h:commandLink value="Activity End Time" actionListener="#{SessionsController.sort}">
<f:attribute name="sortField" value="Activity End Time" />
</h:commandLink>
</f:facet>
<h:outputText value="#{item.activityEnd}" />
</h:column>
<h:column>
<f:facet name="header">
<h:commandLink value="Activity" actionListener="#{SessionsController.sort}">
<f:attribute name="sortField" value="Activity" />
</h:commandLink>
</f:facet>
<h:outputText value="#{item.activity}" />
</h:column>
</h:dataTable>
<!-- The paging buttons -->
<h:commandButton value="first" action="#{SessionsController.pageFirst}"
disabled="#{SessionsController.firstRow == 0}" >
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandButton>
<h:commandButton value="prev" action="#{SessionsController.pagePrevious}"
disabled="#{SessionsController.firstRow == 0}" >
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandButton>
<h:commandButton value="next" action="#{SessionsController.pageNext}"
disabled="#{SessionsController.firstRow + SessionsController.rowsPerPage >= SessionsController.totalRows}" >
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandButton>
<h:commandButton value="last" action="#{SessionsController.pageLast}"
disabled="#{SessionsController.firstRow + SessionsController.rowsPerPage >= SessionsController.totalRows}" >
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandButton>
<h:outputText value="Page #{SessionsController.currentPage} / #{SessionsController.totalPages}" />
<br />
<!-- The paging links -->
<ui:repeat value="#{SessionsController.pages}" var="page">
<h:commandLink value="#{page}" actionListener="#{SessionsController.page}"
rendered="#{page != SessionsController.currentPage}" >
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandLink>
<h:outputText value="#{page}" escape="false"
rendered="#{page == SessionsController.currentPage}" />
</ui:repeat>
<br />
<!-- Set rows per page -->
<h:outputLabel for="rowsPerPage" value="Rows per page" />
<h:inputText id="rowsPerPage" value="#{SessionsController.rowsPerPage}" size="3" maxlength="3" />
<h:commandButton value="Set" action="#{SessionsController.pageFirst}" >
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandButton>
<h:message for="rowsPerPage" errorStyle="color: red;" />
<h:commandButton value="Delete" action="#{SessionsController.deleteSelectedIDs}" >
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandButton>
<!-- <span class="ui-icon ui-icon-newwin"></span>Open Dialog
-->
<script type="text/javascript" src="resources/js/tabs.js"></script>
</h:form>
</div>
<div id="settingsdivb" style="width:350px; height:400px; position:absolute; background-color:transparent; top:20px; left:800px">
</div>
</div>
</div>
</h:body>
</html>
When I remove the AJAX code I can successfully click on datatable row and open a new page. But when I add the AJAX code when I load the table on the first page it works, but when I switch on the second page the JS code is not working. What maybe the problem?
I also call the JS code twice - in the header and at the end of the form.
Use onmouseover.
<h:dataTable onmouseover="addOnclickToDatatableRows();">
I have a JSF datatable. I want to highlight the row when I select the the corresponding check box . How I must edit the JavaScript code to achieve this effect?
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<ui:insert name="header">
<ui:include src="header.xhtml"/>
</ui:insert>
<script type="text/javascript" src="resources/js/jquery-1.7.2.min.js"></script>
</h:head>
<h:body>
<h1><img src="resources/css/images/icon.png" alt="NVIDIA.com" /> History Center</h1>
<!-- layer for black background of the buttons -->
<div id="toolbar" style="margin: 0 auto; width:1180px; height:30px; position:relative; background-color:black">
<!-- Include page Navigation -->
<ui:insert name="Navigation">
<ui:include src="Navigation.xhtml"/>
</ui:insert>
</div>
<div id="greenBand" class="ui-state-default ui-corner-allh" style="position:relative; top:35px; left:0px;">
<h:graphicImage alt="Dashboard" style="position:relative; top:-20px; left:9px;" value="resources/images/logo_sessions.png" />
</div>
<div id="main" style="margin: 0 auto; width:1190px; height:700px; position:absolute; background-color:transparent; top:105px">
<div id="mainpage" style="margin: 0 auto; width:1190px; height:500px; position:absolute; background-color:transparent; top:80px">
<div id="settingsHashMap" style="width:750px; height:400px; position:absolute; background-color:r; top:20px; left:1px">
<h:form id="form">
<!-- The sortable data table -->
<h:dataTable id="dataTable" value="#{SessionsController.dataList}" var="item">
<h:column>
<f:facet name="header">
<h:commandLink value="Account Session ID" actionListener="#{SessionsController.sort}">
<f:attribute name="sortField" value="Account Session ID" />
</h:commandLink>
</f:facet>
<h:outputText value="#{item.aSessionID}" />
</h:column>
<h:column>
<f:facet name="header">
<h:commandLink value="User ID" actionListener="#{SessionsController.sort}">
<f:attribute name="sortField" value="User ID" />
</h:commandLink>
</f:facet>
<h:outputText value="#{item.userID}" />
</h:column>
<h:column>
<f:facet name="header">
<h:commandLink value="Activity Start Time" actionListener="#{SessionsController.sort}">
<f:attribute name="sortField" value="Activity Start Time" />
</h:commandLink>
</f:facet>
<h:outputText value="#{item.activityStart}" />
</h:column>
<h:column>
<f:facet name="header">
<h:commandLink value="Activity End Time" actionListener="#{SessionsController.sort}">
<f:attribute name="sortField" value="Activity End Time" />
</h:commandLink>
</f:facet>
<h:outputText value="#{item.activityEnd}" />
</h:column>
<h:column>
<f:facet name="header">
<h:commandLink value="Activity" actionListener="#{SessionsController.sort}">
<f:attribute name="sortField" value="Activity" />
</h:commandLink>
</f:facet>
<h:outputText value="#{item.activity}" />
</h:column>
</h:dataTable>
<!-- The paging buttons -->
<h:commandButton value="first" action="#{SessionsController.pageFirst}"
disabled="#{SessionsController.firstRow == 0}" />
<h:commandButton value="prev" action="#{SessionsController.pagePrevious}"
disabled="#{SessionsController.firstRow == 0}" />
<h:commandButton value="next" action="#{SessionsController.pageNext}"
disabled="#{SessionsController.firstRow + SessionsController.rowsPerPage >= SessionsController.totalRows}" />
<h:commandButton value="last" action="#{SessionsController.pageLast}"
disabled="#{SessionsController.firstRow + SessionsController.rowsPerPage >= SessionsController.totalRows}" />
<h:outputText value="Page #{SessionsController.currentPage} / #{SessionsController.totalPages}" />
<br />
<!-- The paging links -->
<ui:repeat value="#{SessionsController.pages}" var="page">
<h:commandLink value="#{page}" actionListener="#{SessionsController.page}"
rendered="#{page != SessionsController.currentPage}" />
<h:outputText value="#{page}" escape="false"
rendered="#{page == SessionsController.currentPage}" />
</ui:repeat>
<br />
<!-- Set rows per page -->
<h:outputLabel for="rowsPerPage" value="Rows per page" />
<h:inputText id="rowsPerPage" value="#{SessionsController.rowsPerPage}" size="3" maxlength="3" />
<h:commandButton value="Set" action="#{SessionsController.pageFirst}" />
<h:message for="rowsPerPage" errorStyle="color: red;" />
</h:form>
</div>
<div id="settingsdivb" style="width:350px; height:400px; position:absolute; background-color:transparent; top:20px; left:800px">
</div>
</div>
</div>
<script type="text/javascript">
$("tr").not(':first').hover(
function () {
$(this).css("background","#787878");
},
function () {
$(this).css("background","");
}
);
</script>
</h:body>
</html>
I can't really tell where your checkboxes are or what their names are but, I did notice you are using jQuery in your script. I created a quick little jsFiddle demo to show you what you can do with jQuery. In my example, I created a .highlight class where I set the background-color to the color I want. In jQuery, I group all of the checkboxes and attach a .change() handler to them where I toggle the highlight class on/off every click.
Check out the jsFiddle demo
HTML:
<div id="row-1"><input type="checkbox" id="chk-1" />Row 1</div>
<div id="row-2"><input type="checkbox" id="chk-2" />Row 2</div>
<div id="row-3"><input type="checkbox" id="chk-3" />Row 3</div>
<div id="row-4"><input type="checkbox" id="chk-4" />Row 4</div>
CSS:
div
{
display: block;
height: 20px;
padding: 20px;
border-bottom: dashed 1px #000;
}
input
{
margin-right: 10px;
}
.highlight
{
background-color: yellow;
}
jQuery:
$("input[type=checkbox]").on("change", function() {
var $chk = $(this),
num = $chk.attr("id").substring(4),
$row = $("#row-" + num);
$row.toggleClass("highlight");
});
Output:
Well my approach with jQuery is this :
<p:column >
<h:selectBooleanCheckbox onclick="highlight(this)" />
</p:column>
Create .highlighted class in your CSS file:
.highlighted {
background-color: red;
}
And finally actual function:
function highlight(param) {
var row = jQuery(param).parent().parent(); //children() available as well
row.toggleClass('highlighted');
}
You just get the row of the clicked checkbox and handle assigning of the CSS class. Straight and simple.
EDIT: Of course number of .parent() depends on your html elements composition. Edited the function to fit on your case, I've tried it with different composition of elements.
Here is an example of what I've done for getting Javascript to change background colors when checkboxes are checked:
<html>
<body>
<table>
<tr id="changeme1">
<td><input type="checkbox" onclick="highlight('changeme1');" /></td>
<td>Test Box</td>
</tr>
<tr id="changeme2">
<td><input type="checkbox" onclick="highlight('changeme2');" /></td>
<td>Test2</td>
</tr>
</table>
<script>
function highlight(id)
{
object = document.getElementById(id).style.backgroundColor;
if(object == "yellow")
{
document.getElementById(id).style.backgroundColor = "white";
}else{
document.getElementById(id).style.backgroundColor = "yellow";
}
}
</script>
</body>
</html>