primeFaces select oneMenu Show Cases has select advance .and it has one attribute ( converter ) .
primeFaces Code:
<p:selectOneMenu id="advanced" value="#{selectOneMenuView.theme}" converter="#{themeConverter}" panelStyle="width:180px"
effect="fade" var="t" style="width:160px" filter="true" filterMatchMode="startsWith">
<f:selectItems value="#{selectOneMenuView.themes}" var="theme" itemLabel="#{theme.displayName}" itemValue="#{theme}" />
<p:column style="width:10%">
<h:graphicImage name="showcase/images/themeswitcher/themeswitcher-#{t.name}.png" alt="#{t.name}" styleClass="ui-theme" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Name"/>
</f:facet>
<h:outputText value="#{t.displayName}" />
</p:column>
<f:facet name="footer">
<p:separator />
<h:outputText value="#{selectOneMenuView.themes.size()} themes" style="font-weight:bold;"/>
</f:facet>
</p:selectOneMenu>
i'm looking for where's converter="#{themeConverter}" in the code (page.xhtml and manage Bean , class) i don't find it . they don't mention it(themeConverter) in other class whether annotation or class name or variable.
anybody has idea how use it ?
with example
thank you
ThemeConverter source code is right here:
https://github.com/primefaces/primefaces-showcase/blob/master/src/main/java/org/primefaces/showcase/convert/ThemeConverter.java
package org.primefaces.showcase.convert;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.inject.Inject;
import javax.inject.Named;
import org.primefaces.showcase.domain.Theme;
import org.primefaces.showcase.service.ThemeService;
#Named
#FacesConverter(value = "themeConverter", managed = true)
public class ThemeConverter implements Converter<Theme> {
#Inject private ThemeService themeService;
#Override
public Theme getAsObject(FacesContext context, UIComponent component, String value) {
if(value != null && value.trim().length() > 0) {
try {
return themeService.getThemes().get(Integer.parseInt(value));
} catch(NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid theme."));
}
}
else {
return null;
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Theme value) {
if(value != null) {
return String.valueOf(value.getId());
}
else {
return null;
}
}
}
Related
I am trying to pass an object from populated with items table to Controller. Then I use JS alert to verify success. However I fail to pass anything from the table.
Any help would be appreciated.
issues.xhtml
<p:dataTable var="issue" value="#{issuesController.findWithParameter(issues, startenddates)}" styleClass="list" selectionMode="single" selection="#{issuesController.issue}" rowKey="#{issue.id}" >
<p:ajax event="rowSelect" update="mainForm" listener ="#{issuesController.onRowSelect}"
oncomplete="alert(args.name)"/>
<p:column headerText="Id" id = "head_id" style="width:0%; padding: 0px;">
<h:outputText value="#{issue.id}"/>
</p:column>
<p:column headerText="Child" id = "head_child" style="width:12%;">
<h:outputText value="#{issue.child}"/>
</p:column>
...
</p:dataTable>
IssuesController.java
#Named("issuesController")
#RequestScoped
public class IssuesController implements Serializable {
#Inject
private Issues issue;
....
public void onRowSelect(SelectEvent event) throws IOException {
Issues i = (Issues) event.getObject();
String toWrite;
if (i == null) {
toWrite = "Item is not recieved";
} else {
toWrite = i.toString();
}
RequestContext.getCurrentInstance().addCallbackParam("name", toWrite);
}
Issues.java
#Named("issues")
#SessionScoped
#XmlRootElement
public class Issues implements Serializable {
....
}
I tried different types of scope, tried f:attribute...neither of this worked...
Try using process="#this" and change the scope to
#ViewScoped.
I'm pretty new to Primefaces and I'm having trouble understanding how it works. I'm trying to create a datatable that will show a series of records that are grouped according to one of the fields (area), with a header row indicating the area of the rows beneath it. There is a tag in Primefaces (since 6.0.11), "p:headerRow", but it's unavailable for my version, Primefaces 5.3. There is also an attribute in the "column" tag, "groupRow", but it's unavailable for my version as well. One idea that comes to mind is to use a conditional header row that will show the value of area for the following rows, depending on whether the area has changed (if not, do not show the header; if yes, show it). I wanted to use a variable "areaActual" to keep track of the area being rendered, to be compared with the area of the next row in the table. I hope I'm being clear... But the variable does not seem to work, and the header row does not show up as a header (if I remove the "rendered" condition). Please help!
This is the xhtml.:
<h:panelGroup id="pgbody" styleClass="backBeanChangeBody" rendered="#{informacionpersonal$kardex.existe}">
<p:dataTable id="dataTablePrincipal"
style="height:100%;width:100%" value="#{informacionpersonal$kardex.listaKardex}" var="currentRow" rows="10"
paginator="true" rowsPerPageTemplate="10,15,20,25,30" reflow="true" >
<p: rendered="#{!currentRow.area eq areaActual}">
<p:column id="encabezado" colspan="7">
<p:outputLabel value="#{areaActual}" />
</p:column>
</p:row>
<ui:param name="areaActual" value="#{currentRow.area}" />
<p:row>
<p:column id="column3" sortBy="#{currentRow.espAsignatura}">
<p:outputLabel id="outputText5" value="#{currentRow.espAsignatura}"/>
<f:facet name="header">
<p:outputLabel value="Asignatura"/>
</f:facet>
</p:column>
<p:column id="column5" sortBy="#{currentRow.espPeriodoescolar}">
<p:outputLabel value="#{currentRow.espPeriodoescolar}" />
<f:facet name="header">
<p:outputLabel value="Periodo escolar"/>
</f:facet>
</p:column>
<p:column id="column6" sortBy="#{currentRow.creditos}">
<p:outputLabel value="#{currentRow.creditos}" />
<f:facet name="header">
<p:outputLabel value="Créditos"/>
</f:facet>
</p:column>
<p:column id="column7" sortBy="#{currentRow.espTipoevaluacion}">
<p:outputLabel value="#{currentRow.espTipoevaluacion}" />
<f:facet name="header">
<p:outputLabel value="Tipo de evaluación"/>
</f:facet>
</p:column>
<p:column id="column12" sortBy="#{currentRow.calificacion}">
<p:outputLabel value="#{currentRow.calificacion}"/>
<f:facet name="header">
<p:outputLabel value="Calificación"/>
</f:facet>
</p:column>
</p:row>
</p:dataTable>
</h:panelGroup>
This is the bean:
#ManagedBean(name = "informacionpersonal$kardex")
#ViewScoped
public class kardex extends FacesBean implements Serializable {
private int __placeholder;
private void _init() throws Exception {
selectOneMenu1DefaultItems.setItems(new String[]{"10", "15", "20", "25", "30"});
}
private FormaModal formaModal = (FormaModal) getValue("#{plantilla.formaModal}");
private Boolean notselectedrow = true;
private DefaultSelectionItems selectOneMenu1DefaultItems = new DefaultSelectionItems();
public DefaultSelectionItems getSelectOneMenu1DefaultItems() {
return selectOneMenu1DefaultItems;
}
public void setSelectOneMenu1DefaultItems(DefaultSelectionItems dsi) {
this.selectOneMenu1DefaultItems = dsi;
}
public Boolean getNotselectedrow() {
return notselectedrow;
}
public void setNotselectedrow(Boolean notselectedrow) {
this.notselectedrow = notselectedrow;
}
private TableListDataModel tabla;
public TableListDataModel getTabla() {
return tabla;
}
public void setTabla(TableListDataModel tabla) {
this.tabla = tabla;
}
// </editor-fold>
private Persona alumno;
private Boolean existe;
private List<VEscHistoriaacademica> listaKardex;
public kardex() {
}
#PostConstruct
public void init() {
try {
_init();
} catch (Exception e) {
log("Page1 Initialization Failure", e);
throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
}
listaKardex = new ArrayList<VEscHistoriaacademica>();
}
#PreDestroy
public void destroy() {
}
protected ApplicationBean1 getApplicationBean1() {
return (ApplicationBean1) getBean("ApplicationBean1");
}
protected Controlador getControlador() {
return (Controlador) getBean("Controlador");
}
public Persona getAlumno() {
return alumno;
}
public void setAlumno(Persona alumno) {
this.alumno = alumno;
listaKardex = new ArrayList<VEscHistoriaacademica>();
listaKardex.clear();
listaKardex = getControlador().findByAlumno(alumno.getId());
existe = !listaKardex.isEmpty();
}
public List<VEscHistoriaacademica> getListaKardex() {
return listaKardex;
}
public void setListaKardex(List<VEscHistoriaacademica> listaKardex) {
this.listaKardex= listaKardex;
}
public Boolean getExiste() {
return existe;
}
public void setExiste(Boolean existe) {
this.existe = existe;
}
}
Thank you!
I am using JSF 2.2 , Tomcat 7, primefaces 6.0 and iText 2.1.7.
I am quite new to primfaces, and I am having 2 problems:
Trying to sort a datable
Exporting the datatable to a pdf
The table is reloaded everytime the user makes a selection on a calendar.
My code is:
index.xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h:form id="form">
<p:layout fullPage="true">
<p:layoutUnit id="up" position="north" size="130" header="" resizable="true" closable="false" collapsible="true">
<h:panelGrid columns="4" cellpadding="5">
<p:row>
<h:graphicImage value="resources/images/logo_anamet.png" />
</p:row>
</h:panelGrid>
</p:layoutUnit>
<p:layoutUnit position="west" size="350" header="" resizable="true" closable="false" collapsible="false">
<p:growl id="growl" showDetail="true" />
<p:outputLabel for="inline" value="#{messages.selectDate}" />
<p:calendar id="inline" value="#{viewCompanyManagedBean.date}" mode="inline" >
<p:ajax event="dateSelect" listener="#{viewCompanyManagedBean.onDateSelect}" update="msgs" />
<p:ajax event="dateSelect" listener="#{viewCompanyManagedBean.onDateSelect}" update=":form:shredder" />
</p:calendar>
</p:layoutUnit>
<p:layoutUnit position="center">
<p:growl id="msgs" showDetail="true" />
<p:tabView id="shredder" >
<p:tab title="#{messages.tab1}">
<h:panelGrid id="display" columns="3" cellpadding="15">
<row>
<p:dataTable var="measurements" id="measure" value="#{viewCompanyManagedBean.measurements}" rendered="#{not empty viewCompanyManagedBean.measurements}" paginatorTemplate="{Exporters}" paginator="true" paginatorPosition="bottom">
<f:facet name="{Exporters}">
<h:commandLink>
<p:graphicImage name="images/pdf.png" width="22"/>
<p:dataExporter id="pdf" type="pdf" target="measure" fileName="#{viewCompanyManagedBean.fileName}" />
</h:commandLink>
</f:facet>
<p:column sortBy="#{measurements.dateTimeField}" sortOrder="DESCENDING">
<f:facet name="header">
<h:outputText value="#{messages.time}" />
</f:facet>
<h:outputText value="#{measurements.dateTimeField}" />
</p:column>
<p:column sortBy="#{measurements.scale.scaleId}" >
<f:facet name="header">
<h:outputText value="#{messages.scale}" />
</f:facet>
<h:outputText value="#{measurements.scale.scaleId}" />
</p:column>
<p:column sortBy="#{measurements.measurement}" >
<f:facet name="header">
<h:outputText value="#{messages.measurement}" />
</f:facet>
<h:outputText value="#{measurements.measurement}" />
</p:column>
</p:dataTable>
</row>
</h:panelGrid>
</p:tab>
<p:tab title="#{messages.tab2}">
<h:panelGrid columns="2" cellpadding="10">
<row>
<p:dataTable var="car" value="">
<p:column headerText="#{messages.saptrn}">
<h:outputText value="" />
</p:column>
<p:column headerText="#{messages.scalepics}">
<p:contentFlow value="#{viewCompanyManagedBean.images}" var="image">
<p:graphicImage value="images/#{image}" styleClass="content" />
<div class="caption">#{image}/div>
</p:contentFlow>
</p:column>
</p:dataTable>
</row>
</h:panelGrid>
</p:tab>
</p:tabView>
</p:layoutUnit>
</p:layout>
</h:form>
</h:body>
</html>
ViewCompanyManagedBean.java:
package com.example.beans;
import com.example.entities.Company;
import com.example.Scale;
import com.example.entities.ScaleMeasurement;
import com.example.services.CompanyService;
import com.example.services.ScaleMeasurementService;
import com.example.services.ScaleService;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
#ManagedBean
#RequestScoped
public class ViewCompanyManagedBean {
public ViewCompanyManagedBean() {
}
#PostConstruct
public void populateCompanyData() {
ScaleService ss = new ScaleService();
ScaleMeasurementService sms = new ScaleMeasurementService();
Scale right = ss.find("s02");
Scale left = ss.find("s03");
Date today = new Date();
this.measurements = sms.getMeasurementForScale(right,today);
this.measurements.addAll(sms.getMeasurementForScale(left,today));
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
this.fileName = "Shredder_Measurements_"+ sdf.format(today);
int counter = 1;
for ( ScaleMeasurement a : this.measurements ) {
counter++;
}
System.out.println(counter);
images = new ArrayList<String>();
for (int i = 1; i <= 7; i++) {
images.add("s_" + i + ".jpg");
}
}
#PostConstruct
public void onDateSelect(SelectEvent event) throws UnknownHostException {
FacesContext facesContext = FacesContext.getCurrentInstance();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
facesContext.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO, "Date Selected",format.format(event.getObject())));
String date = format.format(event.getObject());
try {
Date selectedDate = format.parse(date);
ScaleService ss = new ScaleService();
ScaleMeasurementService sms = new ScaleMeasurementService();
Scale right = ss.find("ANM02");
Scale left = ss.find("ANM03");
this.measurements = sms.getMeasurementForScale(right,selectedDate);
this.measurements.addAll(sms.getMeasurementForScale(left,selectedDate));
setMeasurements(this.measurements);
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
String newFileName = "Shredder_Measurements_"+ sdf.format(selectedDate);
setFileName(newFileName);
this.fileName = newFileName;
} catch (ParseException e) {
e.printStackTrace();
}
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<ScaleMeasurement> getMeasurements() {
return measurements;
}
public void setMeasurements(List<ScaleMeasurement> measurements) {
this.measurements = measurements;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
// Used for Calendar
private Date date;
// Used for Shredder Measurements
private List<ScaleMeasurement> measurements = new ArrayList<ScaleMeasurement>();
private String fileName;
// Used for Pictures
private List<String> images;
}
The problems that I am facing are:
- The table cannot be sorted - everytime I select sorting, the table is
reloaded to the current date
- In case current date does not fill in the table, then I cannot
extract the previous days in pdf
My understanding is that I am not handling ajax well.
Any help will be really appreciated.
I am trying to toggle between a simple "click the row to select" table and a "multi-select Checkbox in the first column table". I have a check box outside the table to change the state of the table. For the simple table (no check boxes in the first column) a selectionMode must be set in the p:datatable tag; either to "single" or "multiple". In this state everything works fine.
If the state is changed so that the multi-select column is rendered, the click event seems to be consumed by selecting the selecting the row. In general when using this multi-select check box table the selectionMode would not be set; hence the mouse event would change the state of the check box.
How do I "unset" the selectionMode. Here are the things that did not work:
table.setSelectionMode(null) - this breaks the selection (so does setting to "")
table.getAttributes().get("javax.faces.component.UIComponentBase.attributesThatAreSet") then removing the selectionMode (it isn't in the set attributes).
My xhtml looks like:
<h:form id="addForm">
<p:panel toggleable="false" closable="false" widgetVar="remarksPanel"
id="remarksPanel" style="margin-bottom:5px; overflow:auto;">
<p:selectBooleanCheckbox value="#{multipleSelectBean.bulkEdit}">
<p:ajax update="addForm:remarksTable"
listener="#{multipleSelectBean.editModeChanged}" />
</p:selectBooleanCheckbox>
<h:outputText value=" Bulk Edit" />
<p:dataTable var="remark" id="remarksTable" rowIndexVar="rowNum"
value="#{multipleSelectBean.remarkList}" rowKey="#{remark.id}"
selectionMode="multiple"
selection="#{multipleSelectBean.selectedRemarks}">
<p:column rendered="#{multipleSelectBean.bulkEdit}"
selectionMode="multiple" style="width:18px" />
<p:column headerText="Remark">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{remark.remark}" />
</f:facet>
<f:facet name="input">
<p:inputText style="width:98%" id="remark"
value="#{remark.remark}" />
</f:facet>
</p:cellEditor>
</p:column>
</p:dataTable>
</p:panel>
</h:form>
My Bean Looks Like:
package gov.gsa.krichards.sandbox;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.event.SelectEvent;
#ManagedBean
#SessionScoped
public class MultipleSelectBean implements Serializable {
private static final long serialVersionUID = 1L;
private final static String[] categoryList;
private List<Remark> remarkList = new ArrayList<Remark>();
private Remark[] selectedRemarks = null;
private String words = "Mauris interdum, turpis nec euismod c aliquet fermentum nisl, in tristique arcu tincidunt nec.";
private boolean bulkEdit = false;
private boolean initialized = false;
static {
categoryList = new String[4];
categoryList[0] = "Cat5";
categoryList[1] = "Cat4";
categoryList[2] = "Cat3-UTP";
categoryList[3] = "BNC";
}
public MultipleSelectBean() {
Random r = new Random();
for (int i = 0; i < 10; i++) {
String cat = categoryList[r.nextInt(4)];
int len = words.length();
int begIndex = r.nextInt(len / 2);
int endIndex = begIndex + r.nextInt(len - begIndex);
Remark rem = new Remark(i, cat, words.substring(begIndex, endIndex));
remarkList.add(rem);
}
}
public void editModeChanged() {
System.out.println("changed to " + bulkEdit);
}
public void setBulkEdit(boolean arg) {
DataTable table = (DataTable) FacesContext.getCurrentInstance()
.getViewRoot().findComponent("addForm:remarksTable");
bulkEdit = arg;
if (bulkEdit) {
table.setSelectionMode("single");
} else {
table.setSelectionMode("multiple");
}
}
public boolean isBulkEdit() {
return bulkEdit;
}
public List<Remark> getRemarkList() {
return remarkList;
}
public void setRemarkList(List<Remark> remarkList) {
this.remarkList = remarkList;
}
public String[] getCategoryList() {
return categoryList;
}
public Remark[] getSelectedRemarks() {
if (selectedRemarks == null || selectedRemarks.length == 0)
return null;
return selectedRemarks;
}
public void setSelectedRemarks(Remark[] selectedRemarks) {
this.selectedRemarks = selectedRemarks;
}
}
the situation is the following: I've got a treeTable with 3 different type of objects. The table contains the p:ajax with event="select". I wrote 3 different contextMenus, one for each type... and all works well.
My problem is that I want to enable/disable some of the menuItems; to do that I use the attribute "rendered" with condition based on properties of selected node.
All works, but only the second time I right-click on the same object (the first time the contextMenu isn't filtered).
Here is the code... (I'm including only one type of object for semplicity)
treeTable page:
<h:form id="form" prependId="false">
<p:treeTable value="#{documentsController.root}" var="document" id="docs"
selectionMode="single" selection="#{documentsController.selectedNode}">
<p:ajax event="select" process="#this" update=":form:menus"/>
<p:column headerText="#{msg['name']}">
<h:outputText value="#{document.name}" />
</p:column>
</p:treeTable>
<h:panelGroup id="menus">
<ui:include src="/menu/document_menu.xhtml"/>
</h:panelGroup>
<p:dialog id="document-rename-dialog" widgetVar="documentRenameDialog" header="#{msg.rename}">
<h:panelGrid id="doc-rename" columns="2">
<h:outputLabel for="name" value="#{msg.name}:" />
<h:inputText id="name" value="#{documentsController.name}"/>
</h:panelGrid>
<div class="spacer-10" />
<h:panelGroup layout="block">
<p:commandLink onclick="documentRenameDialog.hide();" value="#{msg.cancel}"/>
<p:commandLink actionListener="#{documentsController.renameDocument(documentsController.selectedNode.data)}"
process="#this :form:document-rename-dialog:doc-rename"
update=":form:docs"
oncomplete="documentRenameDialog.hide();"
value="#{msg.check}">
</h:panelGroup>
</common:dialog>
</h:form>
document_menu page:
<p:contextMenu id="contextMenuDocument" for="docs" nodeType="document">
<p:menuitem value="#{msg.rename}" process="#this docs" update=":form:document-rename-dialog:doc-rename"
actionListener="#{documentsController.setName(documentsController.selectedNode.data.name)}"
rendered="#{documentsController.canWrite}"
icon="ui-icon-pencil" oncomplete="documentRenameDialog.show();"/>
</p:contextMenu>
DocumentsController class:
#ManagedBean
#ViewScoped
public class DocumentsController {
private TreeNode root;
private TreeNode selectedNode;
private String name;
public TreeNode getSelectedNode() {
return selectedNode;
}
public void setSelectedNode(TreeNode selectedNode) {
this.selectedNode = selectedNode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void renameDocument(ArterDocument selectedDocument) {
if(name != null && !name.equals("")) {
System.out.println("Document renamed in: "+name);
((MyDocument)selectedNode.getData()).setName(name);
}
else
addErrorMessage("Error renaming document.");
}
public static boolean canWrite() {
if(((MyDocument)selectedNode.getData()).isWriteable())
return true;
return false;
}
}
The MyDocument class is a simple class with a String (name) and a boolean (writeable).
Can anyone tell me how I can show filtered contextMenu at first shot?
Thank you!