I am creating a SelectOneMenu. The menu outputs correctly. However, along with the menu being outputted is an InputBox and then all the items of the menu being printed as text. I don't know what is causing it. I have included a image of the output below.
Here is my JSF code:
<p:panelGrid columns="2">
<h:outputLabel for="trader" value="Trader:" />
<p:selectOneMenu id="trader" value="#{fixBean.trader}">
<f:selectItem itemLabel="Select" itemValue="0" />
<f:selectItems value="#{fixBean.traderOption}" />
</p:selectOneMenu>
</p:panelGrid>
Below is the code to my Bean:
private SelectItem[] traderOption = createFilterOptions(traders);
private final static String[] traders;
private static String trader = "";
static {
traders = new String[9];
traders[0] = "Dowd";
traders[1] = "Dwyer";
traders[2] = "Edelman";
traders[3] = "Hughes";
traders[4] = "Kelley";
traders[5] = "Nauyokas";
traders[6] = "Options";
traders[7] = "Rafferty";
traders[8] = "Russillo";
}
public String getTrader() {
return trader;
}
public void setTrader(String trader) {
this.traderOption = trader;
}
public void setTraderOption() {
traderOption = createFilterOptions(traders);
}
private SelectItem[] createFilterOptions(String[] data) {
SelectItem[] options = new SelectItem[data.length + 1];
options[0] = new SelectItem("", "Select");
for(int i = 0; i < data.length; i++) {
options[i + 1] = new SelectItem(data[i], data[i]);
}
return options;
}
public SelectItem[] getTraderOption() {
return traderOption;
}
The SelectMenu has the correct options in it however, I don't know why the rest of the output is being create (i.e. InputBox and text list).
****update****
I rebuilt the page using the primfaces SelectOneMenu example and built out from there. That resolved the issue. Though still not sure what was causing the issue
Related
I want to use a LazyDataModel List inside a SelectOneMenu, but the selectoneMenu doesn't show anything . this is my code
public void show() {
beneficiaries = new LazyDataModel<Fournisseur>() {
private static final long serialVersionUID = 1L;
private List<Fournisseur> list;
#Override
public List<Fournisseur> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,Object> filters){
list = service.getAll((String)filters.get("benef.intitule"),first, pageSize);
this.setRowCount(service.count((String)filters.get("benef.intitule")));
return list;
}
#Override
public Object getRowKey(Fournisseur obj) {
return obj.getCpt();
}
#Override
public Fournisseur getRowData(String rowKey) {
Fournisseur o=null;
if(rowKey != null) {
for (Fournisseur obj : list) {
if(rowKey == obj.getCpt()) {
o = obj;
}
}
return o;
}else {
return null;
}
}
};
}
this is my html code
<p:selectOneMenu id="beneficiary" value="#
{documentController.doc.beneficiary}" converter="#
{beneficiaryConverter}" panelStyle="width:160px" required="true" >
<f:selectItem itemLabel="Selectionner" itemValue="" />
<f:selectItems value="#{beneficiaryController.beneficiaries}"
var="beneficiary" itemLabel="#{beneficiary.intitule}" itemValue="#
{beneficiary}" />
</p:selectOneMenu>
i've tested the list out side the selectOneMenu and it's work fine.
You are using PrimeFaces and want to allow the user to select one out of very many options. As Melloware mentioned, LazyDataModel is ment for use with DataTable or other components that support pagination this way ( e.g. DataGrid)
For your use case p:autoComplete seemes to be the best way to go.
dropdown="true" makes it look like a selectOneMenu, and you can limit the number of items show using maxResults="5".
<p:autoComplete dropdown="true" maxResults="5" value="#{autoCompleteView.txt6}"
completeMethod="#{autoCompleteView.completeText}" />
You'll need to write a custom autoComplete method that finds matches for given user search input:
public List<String> completeText(String query) {
List<String> results = new ArrayList<String>();
// fill the result matching the query from user input
return results;
}
I think i found a bug with livescroll in dataTable in Primefaces 6.1.
I have command link in second column that is saving row/rownumber to variables and calling method to save a file. It works on first 10 elements (size of page), but dont work on any other element that is appended by live pagination - instead something happens to invoke load with first set to 0. I dont see any errors in browser console or tomcat console. On my main project also page is losing all css elements, only text stays, but it could be liferay 6.2 issue.
If i disable liveScroll by replacing
scrollRows="10" liveScroll="true" scrollHeight="90%" scrollable="true"
with
paginatorTemplate="{PreviousPageLink} {NextPageLink}" paginator="true"
everything works. I have run out of ideas how to debug and fix it, any suggestions?
xhtml datatable:
<p:dataTable var="live" value="#{LiveLazyModel}" rows="10" lazy="true"
scrollRows="10" liveScroll="true" scrollHeight="90%" scrollable="true"
style="width: 1000px">
<p:column headerText="Id">
<h:outputText value="#{live.id}" id="idlive"/>
</p:column>
<p:column headerText=".txt" style="width: 80px" exportable="false">
<h:commandLink>
<h:outputText value="download"/>
<f:param name="liveId" value="#{live.id}" />
<f:setPropertyActionListener value="#{live}" target="#{LiveLazyModel.selectedRow}"/>
<p:fileDownload value="#{LiveLazyModel.liveStreamedContent}"/>
</h:commandLink>
</p:column>
</p:dataTable>
bean:
#ManagedBean(name = "LiveLazyModel")
#ViewScoped
public class LiveLazyModel extends LazyDataModel {
private Live selectedRow;
#Override
public List load(int first, int pageSize, String sortField, SortOrder sortOrder, Map filters) {
List list = addToList(first, pageSize);
this.setRowCount(100);
this.setPageSize(pageSize);
return list;
}
private List addToList(int first, int pageSize) {
List list = new ArrayList();
for (Integer i = first; i < first + pageSize; i++) {
list.add(new Live(i));
}
return list;
}
public StreamedContent getliveStreamedContent() throws IOException {
String idFrom = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("liveId");
if(selectedRow != null){
InputStream targetStream = IOUtils.toInputStream(selectedRow.id + (Double.toString(Math.random()).substring(1)));
return new DefaultStreamedContent(targetStream, "txt", "idLiveFromSelectedRow" + selectedRow.id + ".txt");
}
if (idFrom != null) {
InputStream targetStream = IOUtils.toInputStream(idFrom + (Double.toString(Math.random()).substring(1)));
return new DefaultStreamedContent(targetStream, "txt", "idLiveFromFacesContext" + idFrom + ".txt");
}
throw new RuntimeException("liveId is null & selectedRow is null ");
}
public void setSelectedRow(Live selectedRow) {
this.selectedRow = selectedRow;
}
}
Working barebone code could be found on:
https://github.com/TomaszKocinski/jsfPFLiveScrollBugPagination
to run it: mvn tomcat7:run should be enough, localhost:9966/live
i want to add multiple elements on an existing diagram in primefaces but it overwrites the created one all the time. It creates the first one and after that it keeps overwriting whenever i drop a new element on the diagram.
I'm using the panel via drag'n drop to add new element to the diagram.
See below my code (diagram.xhtml):
<h:form id="elementForm">
<p:panel id="epnl" header="Draggable Panel">
<h:outputText value="New Workflow Task" />
</p:panel>
<p:draggable for="epnl" helper="clone" />
<p:outputPanel id="selectedElements" style="height:600px">
<p:diagram id="diagramV" value="#{diagramFlowChartView.model}"
style="height:600px" styleClass="ui-widget-content" />
</p:outputPanel>
<p:droppable for="diagramV" widgetVar="dropWV">
<p:ajax listener="#{diagramFlowChartView.onElementDrop}"
update="elementForm, selectedElements, diagramV" />
</p:droppable>
</h:form>
<script type="text/javascript">
//<![CDATA[
PrimeFaces.widget.Droppable.prototype.bindDropListener = function() {
var _self = this;
this.cfg.drop = function(event, ui) {
if (_self.cfg.onDrop) {
_self.cfg.onDrop.call(_self, event, ui);
}
if (_self.cfg.behaviors) {
var dropBehavior = _self.cfg.behaviors['drop'];
if (dropBehavior) {
var ext = {
params : [ {
name : _self.id + '_dragId',
value : ui.draggable.attr('id')
}, {
name : _self.id + '_dropId',
value : _self.cfg.target
}, {
name : ui.draggable.attr('id') + '_left',
value : ui.position.left
}, {
name : ui.draggable.attr('id') + '_top',
value : ui.position.top
} ]
};
console.log(ui);
dropBehavior.call(_self, ext);
}
}
};
}
// ]]>
</script>
The related Bean (FormChartView.java):
#ManagedBean(name = "diagramFlowChartView")
#RequestScoped
public class FlowChartView {
private DefaultDiagramModel model;
private Element elm = new Element("", "25em", "10em");
private List<Element> elements = new ArrayList<Element>();
public void onElementDrop(DragDropEvent ddEvent) {
String dargId = ddEvent.getDropId();
System.out.println("dargId = " + dargId);
Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String left = params.get(dargId + "_left");
String top = params.get(dargId + "_top");
elment = new Element("Test", left, top);
elment.setId(UUID.randomUUID().toString());
System.out.println("elm.id = " + elm.getId());
model.addElement(elm);
}
#PostConstruct
public void init() {
model = new DefaultDiagramModel();
elm = new Element("", "25em", "10em");
model.setMaxConnections(-1);
FlowChartConnector connector = new FlowChartConnector();
connector.setPaintStyle("{strokeStyle:'#C7B097',lineWidth:3}");
model.setDefaultConnector(connector);
Element start = new Element("Fight for your dream", "20em", "6em");
start.addEndPoint(new BlankEndPoint(EndPointAnchor.BOTTOM));
start.addEndPoint(new BlankEndPoint(EndPointAnchor.LEFT));
start.setDraggable(true);
start.setStyleClass("background-color: #98AFC7");
Element trouble = new Element("Do you meet some trouble?", "20em", "18em");
trouble.addEndPoint(new BlankEndPoint(EndPointAnchor.TOP));
trouble.addEndPoint(new BlankEndPoint(EndPointAnchor.BOTTOM));
trouble.addEndPoint(new BlankEndPoint(EndPointAnchor.RIGHT));
trouble.setDraggable(true);
Element giveup = new Element("Do you give up?", "20em", "30em");
giveup.addEndPoint(new BlankEndPoint(EndPointAnchor.TOP));
giveup.addEndPoint(new BlankEndPoint(EndPointAnchor.LEFT));
giveup.addEndPoint(new BlankEndPoint(EndPointAnchor.RIGHT));
Element succeed = new Element("Succeed", "50em", "18em");
succeed.addEndPoint(new BlankEndPoint(EndPointAnchor.LEFT));
succeed.setStyleClass("ui-diagram-success");
Element fail = new Element("Fail", "50em", "30em");
fail.addEndPoint(new BlankEndPoint(EndPointAnchor.LEFT));
fail.setStyleClass("ui-diagram-fail");
model.addElement(start);
model.addElement(trouble);
model.addElement(giveup);
model.addElement(succeed);
model.addElement(fail);
elements.add(start);
elements.add(trouble);
elements.add(giveup);
elements.add(succeed);
elements.add(fail);
model.connect(createConnection(start.getEndPoints().get(0), trouble.getEndPoints().get(0), null));
model.connect(createConnection(trouble.getEndPoints().get(1), giveup.getEndPoints().get(0), "Yes"));
model.connect(createConnection(giveup.getEndPoints().get(1), start.getEndPoints().get(1), "No"));
model.connect(createConnection(trouble.getEndPoints().get(2), succeed.getEndPoints().get(0), "No"));
model.connect(createConnection(giveup.getEndPoints().get(2), fail.getEndPoints().get(0), "Yes"));
}
public DefaultDiagramModel getModel() {
return model;
}
public void setModel(DefaultDiagramModel model) {
this.model = model;
}
public Element getElment() {
return elment;
}
public void setElment(Element elment) {
this.elment = elment;
}
public List<Element> getElements() {
return elements;
}
public void setElements(List<Element> elements) {
this.elements = elements;
}
private Connection createConnection(EndPoint from, EndPoint to, String label) {
Connection conn = new Connection(from, to);
conn.getOverlays().add(new ArrowOverlay(20, 20, 1, 1));
if(label != null) {
conn.getOverlays().add(new LabelOverlay(label, "flow-label", 0.5));
}
return conn;
}
}
My fault.
This is caused by the element list to be reinitialized each time an (ajax)request was made. Which in turn was caused by the bean scope being #RequestScoped
Changing #RequestScoped to #ViewScoped solved the issue.
I want to make a Log-File-Reader. I have a Upload field, and a dataTable. First I choose the Log-File an Upload it. Then the program Split each line of the Log-File in the separate variables. Now the Log-File should be printet line for line into the table. But I dont know, how i should put the Lines in the Table. It works, when I define the Lines Static bevore. But now when the lines are not defined static it don't update the Table.
Here is my index.xhtml:
<h:form xmlns="http://www.w3.org/1999/xhtml"
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>
<title>LogReader</title>
</h:head>
<h:body>
<p:accordionPanel dynamic="true" cache="true" activeIndex="1" multiple="false">
<p:tab title="Upload File">
<h:panelGrid>
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}" mode="advanced" dragDropSupport="false"
update="messages" fileLimit="1" allowTypes="/(\.|\/)(log|txt|)$/" />
<p:growl id="messages" showDetail="true"/>
</h:panelGrid>
</p:tab>
</p:accordionPanel>
<p:dataTable id="dataTable" var="log" value="#{fileUpload.logsSmall}" widgetVar="dataTable"
emptyMessage="No Log found with given criteria" filteredValue="#{tableBean.filteredLogs}"
rowKey="#{log.datetime}" paginator="true" rows="20" paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" rowsPerPageTemplate="5,10,15,20,50,100" selection="#{tableBean.selectedLog}" selectionMode="single">
<f:facet name="header">
<p:outputPanel>
<h:outputText value="Search all fields:" />
<p:inputText id="globalFilter" onkeyup="dataTable.filter();" style="width:150px" />
</p:outputPanel>
</f:facet>
<p:column id="datetimeColumn" filterBy="datetime" sortBy="datetime"
headerText="DateTime" footerText=""
filterMatchMode="contains">
<h:outputText value="#{log.datetime}" />
</p:column>
<p:column id="levelColumn" filterBy="level"
headerText="LogLevel" footerText=""
filterOptions="#{tableBean.levelOptions}"
filterMatchMode="exact" sortBy="level">
<h:outputText value="#{log.level}" />
</p:column>
<p:column id="categoryColumn" filterBy="category" sortBy="category"
headerText="Category" footerText=""
filterMatchMode="contains">
<h:outputText value="#{log.category}" />
</p:column>
<p:column id="messageColumn" filterBy="message" sortBy="message"
headerText="Message" footerText="" filterMatchMode="contains">
<h:outputText value="#{log.message}" />
</p:column>
</p:dataTable>
</h:body>
Here my TableBean:
package com.rausch.logreader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import com.rausch.logreader.Log;
#ViewScoped
#ManagedBean(name = "tableBean")
#SessionScoped
public class TableBean implements Serializable {
private final static String[] level;
private SelectItem[] levelOptions;
private List<Log> filteredLogs;
private int i = 0;
private Log selectedLog;
private Log[] selectedLogs;
static {
level = new String[5];
level[0] = "DEBUG";
level[1] = "INFO";
level[2] = "WARN";
level[3] = "ERROR";
level[4] = "FATAL";
}
public TableBean() {
levelOptions = createLevelOptions(level);
}
public Log getSelectedLog() {
return selectedLog;
}
public void setSelectedLog(Log selectedLog) {
this.selectedLog = selectedLog;
}
public void listAdd(List<Log> list, String datetime, String level, String category, String message){
list.add(new Log(datetime, level, category, message));
}
public List<Log> getFilteredLogs() {
return filteredLogs;
}
public void setFilteredLogs(List<Log> filteredCars) {
this.filteredLogs = filteredCars;
}
private SelectItem[] createLevelOptions(String[] data) {
SelectItem[] options = new SelectItem[data.length + 1];
options[0] = new SelectItem("", "Select");
for(int i = 0; i < data.length; i++) {
options[i + 1] = new SelectItem(data[i], data[i]);
}
return options;
}
public SelectItem[] getLevelOptions() {
return levelOptions;
}
}
And here my FileUploadController:
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
#ViewScoped
#ManagedBean(name = "fileUploadController")
#SessionScoped
public class FileUploadController {
public List<Log> logsSmall;
public void handleFileUpload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
} catch (IOException e) {
e.printStackTrace();
}
}
private String destination="C:\\Java\\";
public void copyFile(String fileName, InputStream in) {
try {
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(destination + fileName));
int read;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
readFile(destination + fileName);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void readFile(String filePath){
try
{
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader(filePath));
String output;
String datetime = "";
String level = "";
String category = "";
String message;
TableBean table = new TableBean();
while ((sCurrentLine = br.readLine()) != null) {
//System.out.println(sCurrentLine.charAt(4) + "" + sCurrentLine.charAt(7) + sCurrentLine.charAt(13) + "" +sCurrentLine.charAt(16));
if(sCurrentLine.length()<1){
}
else{
if (sCurrentLine.length() >= 16 && sCurrentLine.charAt(4)=='-' && sCurrentLine.charAt(7)=='-' && sCurrentLine.charAt(13)==':' && sCurrentLine.charAt(16)==':'){
output = "";
message = "";
String[] leerzeichen = sCurrentLine.split(" ");
datetime = leerzeichen[0] + " " + leerzeichen[1];
level = leerzeichen[2];
category = leerzeichen[4];
int arraylength = leerzeichen.length;
for (int l=5; l<arraylength; l++){
message = message.concat(leerzeichen[l] + " ");
}
output = datetime + level + category + message;
} else {
message = sCurrentLine;
output = message;
}
logsSmall = new ArrayList<Log>();
table.listAdd(logsSmall, datetime, level, category, message);
System.out.println(output);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sorry for my bad English. I try to Ask an other way:
I want to have a program, where I can upload a *.log File and read it in a table. I open the xhtml, and there is a empty table. Than I Upload the File with the <:pFileUpload. The File Upload Controller takes the Log-File and split each line in the values (datetime, Level, Category and message). Then the Script should add a new row to the table width the datas of the Log-File-Line. Then it goes to the next Line and parses the Text. At the End the Table should show the content of the Log-File.
The Problem is, that the Table don't Reload. Or i don't know how i should reload it. When I upload the File, the script correctly read each Line of the Log-File. But the table keeps empty.
I quite don't understand what is yourt question what i see some lack of understanding on how to use the beans to manage the view.
First, you have #ViewScoped and #SessionScoped declared at the same time. There must be only one.
Second, the thing about defining managed beans it's that you don't have to manage the creation or destruction on them, the system does. Thats why they are called managed. So doing this:
TableBean table = new TableBean();
is useless. You are creating and instance of an object inside a funcion. Outside that function the object is unreacheable, as the annotations aren't considered if you create the object in your code.
I would have one managed bean that handles the events on the view, like this:
#ViewScoped
#ManagedBean(name = "logViewController")
public class LogViewController{
private List<Log> filteredLogs;
private List<Log> logsSmall;
public void handleFileUpload(FileUploadEvent event) {....}
// other private functions
//public getters and setters
}
Also, if you are working with java 7, maybe you want to look at the new file
I/O.
The tools created this field in the entity:
#Entity
#Table(name = "movies")
public class Movie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idmovie;
// etc
#Temporal(TemporalType.DATE)
#Column(name = "year_of_release")
#Past(message = "Back from the future ?") // added by me
#NotNull(message = "Please enter the year of the movie") // added by me
private Date yearOfRelease;
}
I want to enter the year from a form - I can't find anything that produces a year drop down and that converts it to an YEAR field (getting Data truncation exceptions).
The closest I got :
<h:outputLabel for="yearOfRelease">Year of release</h:outputLabel>
<h:inputText id="yearOfRelease"
value="#{movieController.movie.yearOfRelease}" redisplay="true"
converterMessage="Please enter date in yyyy-MM-dd format">
<f:convertDateTime pattern="yyyy-MM-dd" />
</h:inputText>
<h:message id="yearOfReleaseMessage" for="yearOfRelease" />
Do not seem to find a converter to tell jsf to convert to year.
Is integer my only option ?
Also ideally I would like a dropdown. I found things like
<h:selectOneListbox value="#{form.year}" size="5">
<f:selectItem itemValue="1900" itemLabel="1900"/>
<f:selectItem itemValue="1901" itemLabel="1901"/> ... </h:selectOneListbox>
but surely there is a way to have this automated ?
I am new to JSF and I'd rather stay vanilla JavaEE (no faces libraries). I am on glassfish 4.
Partial answer
// YEAR
private static final short MIN_YEAR = 1901;
private static final short MAX_YEAR = 2014; // (short) new
// java.util.Date().getYear(); // does not play with message
private static final List<Short> YEARS = new ArrayList<>(MAX_YEAR
- MIN_YEAR + 1);
static {
for (short i = MIN_YEAR; i <= MAX_YEAR; ++i) {
YEARS.add(i);
}
}
private static final String MIN_MSG = "Min release year: " + MIN_YEAR;
private static final String MAX_MSG = "Max release year: " + MAX_YEAR;
#Column(name = "year_of_release")
#NotNull(message = "Please enter the year of release of the movie")
#Min(value = 1901, message = MIN_MSG)
#Max(value = 2014, message = MAX_MSG)
private short yearOfRelease = 2014;
public List<Short> getYears() {
return YEARS;
}
And in the form:
<h:selectOneListbox id="yearOfRelease" redisplay="true"
value="#{movieController.movie.yearOfRelease}" size="8">
<f:selectItems value="#{movieController.movie.years}" var="entry"
itemValue="#{entry}" itemLabel="#{entry}" />
<f:ajax event="blur" render="yearOfReleaseMessage" />
</h:selectOneListbox>
If someone can come up with something more elegant (like some ready made Year dropdown that validates #Past and converts to something nice for a MySQL Year datatype) I would gladly accept it.
You can declare <f:selectItems /> and fill it with values from the bean, so something like
#RequestScoped
#ManagedBean
public class Form {
private List<String> items = new ArrayList<>();
#PostConstruct
public void init() {
for(int i=1900;i<2000;i++) {
items.add(i);
}
}
public List<String> getItems() {
return items;
}
}
and then in your page
<h:selectOneListbox value="#{form.year}" size="5">
<f:selectItems value="#{form.items}" var="entry"
itemValue="#{entry}" itemLabel="#{entry}" />
</h:selectOneListbox>