How to download file when I click on table row - java

I need help in implementing file download in JSF page. So far I managed to create this:
<?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"
xmlns:p="http://primefaces.org/ui">
<h:head>
<ui:insert name="header">
<ui:include src="header.xhtml"/>
</ui:insert>
</h:head>
<h:body>
<h1><img src="resources/css/images/icon.png" alt="DX-57" /> Settings Center</h1>
<!-- layer for black background of the buttons -->
<div id="toolbar" style="margin: 0 auto; width:100%; 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="Glassfish" style="position:relative" value="resources/images/logo_glassfish_settings.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="settingsdiv" style="width:350px; height:400px; position:absolute; background-color:r; top:20px; left:1px">
<div id="settingsHashMap" style="width:1050px; height:400px; position:absolute; background-color:r; top:20px; left:1px">
<h:form id="form" >
<p:growl id="growl" showDetail="true" sticky="true" />
<!-- The sortable data table -->
<h:dataTable onmouseover="addOnclickToDatatableRows();" id="dataTable" headerClass="columnHeader" value="#{GlassfishController.dataList}" binding="#{table}" var="item">
<!-- Check box -->
<h:column>
<f:facet name="header">
<h:selectBooleanCheckbox style="margin-left: 0px;" value="#{GlassfishController.mainSelectAll}" class="checkall" >
<f:ajax listener="#{GlassfishController.selectAll}" render="#form" />
</h:selectBooleanCheckbox>
</f:facet>
<h:selectBooleanCheckbox onclick="highlight(this)" value="#{GlassfishController.selectedIds[item.filename]}" >
<!-- if the user deselects one row deselect the main checkbox -->
<f:ajax listener="#{GlassfishController.deselectMain}" render="#form" />
</h:selectBooleanCheckbox>
<!-- Click on table code -->
<h:outputLink id="lnkHidden" onclick="document.getElementById('form:btnHello').click(); return false;" style="text-decoration:none; color:white; background-color:black">
</h:outputLink>
</h:column>
<!-- Row number -->
<h:column>
<f:facet name="header">
<h:outputText value="№" />
</f:facet>
<h:outputText value="#{table.rowIndex + GlassfishController.firstRow + 1}" />
</h:column>
<h:column>
<f:facet name="header">
<h:commandLink value="File Name" actionListener="#{GlassfishController.sort}" style="text-decoration:none; color:white; background-color:black">
<f:attribute name="sortField" value="filename" />
<f:ajax render="#form" />
</h:commandLink>
</f:facet>
<h:outputText value="#{item.filename}" />
</h:column>
<h:column>
<f:facet name="header">
<h:commandLink value="Size" actionListener="#{GlassfishController.sort}" style="text-decoration:none; color:white; background-color:black">
<f:attribute name="sortField" value="size" />
<f:ajax render="#form" />
</h:commandLink>
</f:facet>
<h:outputText value="#{item.size} bytes" />
</h:column>
</h:dataTable>
<!-- The paging buttons -->
<h:commandButton value="first" action="#{GlassfishController.pageFirst}"
disabled="#{GlassfishController.firstRow == 0}" >
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandButton>
<h:commandButton value="prev" action="#{GlassfishController.pagePrevious}"
disabled="#{GlassfishController.firstRow == 0}" >
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandButton>
<h:commandButton value="next" action="#{GlassfishController.pageNext}"
disabled="#{GlassfishController.firstRow + GlassfishController.rowsPerPage >= GlassfishController.totalRows}" >
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandButton>
<h:commandButton value="last" action="#{GlassfishController.pageLast}"
disabled="#{GlassfishController.firstRow + GlassfishController.rowsPerPage >= GlassfishController.totalRows}" >
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandButton>
<h:outputText value="Page #{GlassfishController.currentPage} / #{GlassfishController.totalPages}" />
<br />
<!-- The paging links -->
<ui:repeat value="#{GlassfishController.pages}" var="page">
<h:commandLink value="#{page}" actionListener="#{GlassfishController.page}"
rendered="#{page != GlassfishController.currentPage}" style="text-decoration:none;color:white;">
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandLink>
<h:outputText value="#{page}" escape="false"
rendered="#{page == GlassfishController.currentPage}" style="text-decoration:none;color:gray;"/>
</ui:repeat>
<br />
<!-- Set rows per page -->
<h:outputLabel for="rowsPerPage" value="Rows per page" />
<h:inputText id="rowsPerPage" value="#{GlassfishController.rowsPerPage}" size="3" maxlength="3" />
<h:commandButton value="Set" action="#{GlassfishController.pageFirst}" >
<f:ajax render="#form" execute="#form"></f:ajax>
</h:commandButton>
<h:message for="rowsPerPage" errorStyle="color: red;" />
<!-- hidden button -->
<h:commandButton id="deleterow" value="HiddenDelete" action="#{GlassfishController.deleteSelectedIDs}" style="display:none">
<f:ajax render="#form"></f:ajax>
</h:commandButton>
<!-- the delete button -->
<h:button value="Delete" onclick="deletedialog(this, 'Do you want to delete the selected rows?'); return false;" />
<script type="text/javascript" src="resources/js/tabs.js"></script>
<h:commandLink id="btnHello" value="Download Files"
action="#{GlassfishController.downloadFile}">
</h:commandLink>
</h:form>
</div>
</div>
</div>
</div>
</h:body>
</html>
// Execute the download procedure
public void executeDownload(String filename) throws IOException{
int DEFAULT_BUFFER_SIZE = 10240;
String filePath = "/opt/glassfish3/glassfish/domains/domain1/logs/" + filename;
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
File file = new File(filePath);
if (!file.exists())
{
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("text");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment;filename=\""
+ file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try
{
input = new BufferedInputStream(new FileInputStream(file),
DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(),
DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0)
{
output.write(buffer, 0, length);
}
}
finally
{
input.close();
output.close();
}
context.responseComplete();
}
There is a problem that I cannot solve and I need help. When I click on the download button I successfully can download the log file.
I want to download a file into the JSF table when I click on it. Can you please help me to implement it? Or can you give me some advice how to do it?
Best wishes

Based in your comments, you can use a commandLink/commandButton to call another commandLink/commandButton in the same page. Remember that these components will behave like normal HTML components. Posting a sample of this behavior
<h:form id="frmTest">
<h:commandLink value="I will call the commandButton below me"
onclick="document.getElementById('frmTest:btnHello').click(); return false;" />
<br />
<h:commandButton id="btnHello" value="I'm the commandButton below the commandLink"
action="#{bean.someAction}" />
</h:form>
EDIT: Based on your comment on the question, you have several ways to pass the parameter to your commandButton action. I'll show you one that uses JavaScript. The logic is simple:
Use an <h:inputHidden> tag component which value will be the name of the file you want to download.
Before sending the onclick event, fill this hidden component with the value you need.
Let the HTML request continue with its work.
<h:form id="frmTest">
<h:commandLink id="hidFileName" value="#{bean.fileToDownload}" />
<h:commandLink value="I will call the commandButton below me"
onclick="document.getElementById('frmTest:hidFileName').value='#{bean.fileName}'; document.getElementById('frmTest:btnHello').click(); return false;" />
<br />
<h:commandButton id="btnHello" value="I'm the commandButton below the commandLink"
action="#{bean.someAction}" />
</h:form>

Related

primefaces dialog close makes inputs disabled on main page

Here is the dialog code
<title><ui:insert name="title">#{msg['trip.bus.unsaved.warning']}</ui:insert></title>
<h:outputStylesheet library="css" name="theme.css" />
</h:head>
<h:body>
<ui:composition>
<h:form id="unsavedBusValidationReturnToCharterForm" width="450px">
<p:panelGrid columns="1">
<p:row>
<p:outputLabel value="#{msg['trip.bus.unsaved.validation.string1']}" style="color:red; font-weight:bold; font-size:12px;"/>
</p:row>
<p:row>
<p:outputLabel value="#{msg['trip.bus.unsaved.validation.string2']}" style="color:red; font-weight:bold; font-size:12px"/>
</p:row>
<p:row>
<p:outputLabel value="#{msg['trip.bus.unsaved.validation.string3']}" style="color:red; font-weight:bold; font-size:12px"/> </p:row>
</p:panelGrid>
<p:commandButton value="#{msg['trip.bus.cancellation.button.ok']}" style="width:140px;" type="submit" onclick="PF('unsavedBusValidReturnToChartDialog').hide();"
action="#{tripInformationController.returnToTripInfo}" update="busPg">
<!-- <f:ajax listener="PF('unsavedBusValidReturnToChartDialog').hide();" /> -->
</p:commandButton>
<p:spacer width="4px"></p:spacer>
<p:commandButton value="#{msg['trip.bus.cancellation.button.cancel']}" style="width:140px;"
onclick="PF('unsavedBusValidReturnToChartDialog').hide();"></p:commandButton>
</h:form>
</ui:composition>
</h:body>
</html>
This is the dialog that includes that code
<p:dialog widgetVar="unsavedBusValidReturnToChartDialog" showHeader="true" showEffect="clip" hideEffect="clip" appendToBody="true" width="auto"
height="auto" resizable="true" draggable="true" modal="true"
styleClass="customDialog dialogTitleNone">
<ui:include src="/charter/unsaved_bus_validation_return_to_charter.xhtml" />
</p:dialog>
Then this method runs when I click on ok to navigate back one page.
public String returnToTripInfo() {
logger.info("returnToTripInfo() entry");
doRemoveUnsavedBus();
if (getBusInfoListVo().size() > 0) {
busbutton = "Edit Buses";
List<FinancialDetailVo> tempFinancialDetails = busInfoSer.getFinancialDetails(tripInfoVo.getCharterId());
if (tempFinancialDetails != null && tempFinancialDetails.size()>0 ) {
tripInfoVo.setFinancialDetailVoSet(tempFinancialDetails);
calculateFinancialtotalAmount();
}
else
{
tripInfoVo.setFinancialDetailVoSet(null);
tripInfoVo.setFinancialTotalAmount(null);
calculateFinancialtotalAmount();
}
if(getBusInfoVo().getSelectStatus()==4)
{
setDisableBus(false);
setDisableCharges(false);
setDisableBusStatus(false);
setDisableBusSave(false);
}
}
logger.info("returnToTripInfo() exit");
return "Charter_information_tab.xhtml";
}
When the dialog closes and navigates back one screen, the input field on that screen are acting as if they are disabled. I tried the appendToBody="true" and appendTo="#(body)". I am running primefaces version 6.
I just need the inputs on the navigated to screen to be editable after the dialog navigates and closes.
The page was navigating before the hideEffect was able to finalize, so the dialog could not close before the page navigated. I took the hideEffect out, and the dialog was able to fully close before navigating.
<p:dialog widgetVar="unsavedBusValidReturnToChartDialog" showHeader="true" showEffect="clip" appendToBody="true" width="auto"
height="auto" resizable="true" draggable="true" modal="true"
styleClass="customDialog dialogTitleNone">
<ui:include src="/charter/unsaved_bus_validation_return_to_charter.xhtml" />
</p:dialog>

Primefaces ajax not working update on field datatable

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.

Autocomplete address with google map library in Primefaces

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

Click on row table is not working when I use AJAX

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();">

How to highlight entire row when the checkbox is selected

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>

Categories