Multiple Dateformat - html

i am task to change the dateformat according to the user's language. Currently the website runs in Chinese and English, However i am unable to change the format of the mask according to the user's language.
<h:outputText styleClass="outputText"
id="index_output_todate" value="#{msg.index_output_todate}">
</h:outputText>
<p:calendar value="#{pc_Index.w_message.am_todate_filter}"
id="index_input_todate" styleClass="calendar" maxlength="10"
pattern="#{pc_Index.dateDisplayFormat}" onfocus="$(this).mask('9999年99月99日');">
<p:watermark for="index_input_todate" value="#{pc_Index.watermarkDateDisplayFormat}" />
<f:convertDateTime pattern="#{pc_Index.dateDisplayFormat}" />
</p:calendar>
I need the date format of the mask to be 9999年99月99日 when the user login as a zh_CN user or a date format of DD/MM/YYYY for en_UK user.
Is there a way to do this?
I had already set the locale
public String getDateDisplayFormat() {
String locale = getUserLocale();
String DATEFORMAT_UK = "dd/MM/yyyy";
String DATEFORMAT_US = "mm/dd/yyyy";
String DATEFORMAT_CN = "yyyy年MM月dd日";
String _s = DATEFORMAT_UK;
if(!isEmptyNull(locale) && locale.equals("en_US")) {
_s = DATEFORMAT_US;
}
else if(!isEmptyNull(locale) && locale.equals("zh_CN")) {
_s = DATEFORMAT_CN;
}
return _s;
}
EDIT:
HTML
<h:form> <p:outputLabel for="index_output_frdate" value="#{msg.index_output_frdate}" />
<p:calendar id="index_output_frdate" value="#{pc_Index.w_message.am_todate_filter}"
styleClass="calendar" maxlength="10"
pattern="#{pc_Index.dateDisplayFormat}" mask="true" />
<p:watermark for="index_output_frdate" value="#{pc_Index.watermarkDateDisplayFormat}" /> </h:form>
Manage Bean:
if (isPageFirstLoad(JSP)) {
_w.setIndex_viewtype("11961003");
if (isEmptyNull(_w.getAm_todate_filter())) {
_w.setAm_todate_filter(getTodayDate());
}
Date _todate = _w.getAm_todate_filter();
Date d = _w.addDaysToDate(_todate, -7);
_w.setAm_frdate_filter(d);
_w.setViewNew(true);
_w.populateAlertsMessages();
}
if (this.trigger_viewtype_change) {
this.trigger_viewtype_change = false;
}
}
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getDateDisplayFormat() {
String locale = getUserLocale(); //WARNING!! Hard-coded!!
final String DATEFORMAT_UK = "dd/MM/yyyy";
final String DATEFORMAT_US = "mm/dd/yyyy";
final String DATEFORMAT_CN = "yyyy年MM月dd日";
if(!locale.isEmpty() && locale.equals("en_US")) {
return DATEFORMAT_US;
}
if(!locale.isEmpty() && locale.equals("zh_CN")) {
return DATEFORMAT_CN;
}
return DATEFORMAT_UK;
}
Doesn't seems to have anything wrong. but the mask just doesnt seem to come out

I don´t know what snippet of your code fails exactly. I've tried an easier example and works very well, so I recommend you debug all your involved code in this functionality.
<h:form>
<p:outputLabel for="mask" value="Mask:" />
<p:calendar id="mask" value="#{dumpController.date}" pattern="#{dumpController.dateDisplayFormat}" mask="true" />
<p:watermark for="mask" value="Input a date" />
</h:form>
Method in charge to set the date's mask:
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getDateDisplayFormat() {
final String locale = "zh_CN"; //WARNING!! Hard-coded!!
final String DATEFORMAT_UK = "dd/MM/yyyy";
final String DATEFORMAT_US = "mm/dd/yyyy";
final String DATEFORMAT_CN = "yyyy年MM月dd日";
if(!locale.isEmpty() && locale.equals("en_US")) {
return DATEFORMAT_US;
}
if(!locale.isEmpty() && locale.equals("zh_CN")) {
return DATEFORMAT_CN;
}
return DATEFORMAT_UK;
}

Related

PrimeFaces selectOneMenu displayed value not resetting

I have two combo boxes. The items of the second one are retrieved using the selected value of the first one. When the default empty value is selected in the first combo box, the second combo box is not rendered.
Everything works well except for one scenario :
select a value in the first combo box -> the second combo box appears
select a value in the second combo box
select the default empty value in the first combo box -> the second combo box disappears
select the same value that was selected at step 1 in the first combo box
The second combo box should appear with the empty default value selected, but instead displays the value that was selected at step 2.
If I select a different value at step 4, the second combo box is loaded correctly, with the default empty value selected.
The view :
<ui:composition template="/pages/include/templatePrincipal.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui" xmlns:d="http://iec.composants"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core">
<ui:define name="pageActive">
<f:view>
<h:form>
<p:panel id="panelModifierUnParametreFonctionnel"
header="LISTE DES FE FILLES ORPHELINES">
<h:panelGrid columns="6">
<p:outputLabel
value="#{feFillesOrphelinesBean.labelComboRegion}" />
<p:selectOneMenu
value="#{feFillesOrphelinesBean.regionOption}"
valueChangeListener="#{feFillesOrphelinesBean.regionChanged}"
onchange="submit()">
<f:selectItems value="#{feFillesOrphelinesBean.listRegion}" />
</p:selectOneMenu>
<p:outputLabel
value="#{feFillesOrphelinesBean.labelComboCorps}"
rendered="#{feFillesOrphelinesBean.rendreComboCorps}" />
<p:selectOneMenu
value="#{feFillesOrphelinesBean.corpsOption}"
rendered="#{feFillesOrphelinesBean.rendreComboCorps}"
valueChangeListener="#{feFillesOrphelinesBean.corpsChanged}"
onchange="submit()">
<f:selectItems value="#{feFillesOrphelinesBean.listCorps}" />
</p:selectOneMenu>
</h:panelGrid>
</p:panel>
</h:form>
</f:view>
</ui:define>
</ui:composition>
The java bean :
public class FEFillesOrphelinesBean implements Serializable {
public final static String LABEL_COMBO_REGION = "Chaîne fonctionnelle :";
public final static String LABEL_COMBO_CORPS = "Corps :";
private String labelComboRegion;
private String labelComboCorps;
private List<SelectItem> listRegion;
private Integer regionOption;
private List<SelectItem> listCorps;
private Integer corpsOption;
private Boolean rendreComboCorps;
public String init() {
this.chargerRegions();
this.chargerCorps();
this.setLabelComboRegion(LABEL_COMBO_REGION);
this.setLabelComboCorps(LABEL_COMBO_CORPS);
return "success";
}
public void chargerRegions() {
this.setListRegion(new ArrayList<>());
this.setRegionOption(new Integer(-1));
RegionAdmin[] tabRegions = ServiceFactory.getInstance().getGestionRegionSrv().findAll();
this.getListRegion().add(new SelectItem(new Integer(-1), " "));
for (RegionAdmin region : tabRegions) {
SelectItem regionItem = new SelectItem(region.getId(), region.getLib() + ": " + region.getLibelle());
this.getListRegion().add(regionItem);
}
}
public void chargerCorps() {
this.setListCorps(new ArrayList<>());
this.setCorpsOption(new Integer(-1));
if (this.getRegionOption().equals(new Integer(-1))) {
this.setRendreComboCorps(false);
} else {
Corps[] tabCorps = ServiceFactory.getInstance().getGestionCorpsSrv().findCorps(this.getRegionOption());
this.getListCorps().add(new SelectItem(new Integer(-1), " "));
for (Corps corps : tabCorps) {
SelectItem corpsItem = new SelectItem(corps.getId(), corps.getLib() + ": " + corps.getLibelle());
this.getListCorps().add(corpsItem);
}
this.setRendreComboCorps(true);
}
}
public void regionChanged(ValueChangeEvent event) {
Integer newRegionOption = (Integer) event.getNewValue();
this.setRegionOption(newRegionOption);
this.chargerCorps();
}
public void corpsChanged(ValueChangeEvent event) {
Integer newCorpsOption = (Integer) event.getNewValue();
this.setCorpsOption(newCorpsOption);
}
public String getLabelComboRegion() {
return labelComboRegion;
}
public void setLabelComboRegion(String labelComboRegion) {
this.labelComboRegion = labelComboRegion;
}
public String getLabelComboCorps() {
return labelComboCorps;
}
public void setLabelComboCorps(String labelComboCorps) {
this.labelComboCorps = labelComboCorps;
}
public List<SelectItem> getListRegion() {
return listRegion;
}
public void setListRegion(List<SelectItem> listRegion) {
this.listRegion = listRegion;
}
public Integer getRegionOption() {
return regionOption;
}
public void setRegionOption(Integer regionOption) {
this.regionOption = regionOption;
}
public List<SelectItem> getListCorps() {
return listCorps;
}
public void setListCorps(List<SelectItem> listCorps) {
this.listCorps = listCorps;
}
public Integer getCorpsOption() {
return corpsOption;
}
public void setCorpsOption(Integer corpsOption) {
this.corpsOption = corpsOption;
}
public Boolean getRendreComboCorps() {
return rendreComboCorps;
}
public void setRendreComboCorps(Boolean rendreComboCorps) {
this.rendreComboCorps = rendreComboCorps;
}
}
As you can see, the regionChanged method is called when the selected value of the first combo box changes, then it calls the chargerCorps method which set the corpsOption to the -1 default value. This means that in the scenario that I've described, the displayed selected value is not the same as the selected value in the bean, which can cause a lot of issues.

Allowing user inputs that have spaces (" ")

I am creating a program that takes an address that the user inputs, and using GeoCoder, places that address on a map. This is done through oracle adf thematic map and java for the backing bean. The issue I'm getting is that the input works, but only if there are no spaces in the user's input. When an input is entered that DOES have a space, I get this error:
<oracle.adf.view> <PartialResponseUtils> <handleError> <ADF_FACES-60096:Server Exception during PPR, #1>
javax.el.ELException: .../map.jsf #76,86 pointX="#{row.lattitude}": java.lang.NullPointerException
Since GeoCoder doesn't care about spaces, I'm guessing the error is in the map code? Here's the code for the map jsf page:
<af:form id="f1">
<af:panelStretchLayout topHeight="50px" id="psl1">
<f:facet name="top">
<af:panelHeader text="Regional Map" id="ph1">
<f:facet name="context"/>
<f:facet name="menuBar"/>
<f:facet name="toolbar"/>
<f:facet name="legend"/>
<f:facet name="info"/>
</af:panelHeader>
</f:facet>
<f:facet name="center">
<af:panelSplitter id="ps1" splitterPosition="289">
<f:facet name="first">
<af:decorativeBox id="db1">
<f:facet name="center">
<af:panelGroupLayout layout="scroll" id="pgl1">
<af:panelFormLayout id="pfl1">
<f:facet name="footer">
<af:commandButton text="Add Location" id="cb1" partialSubmit="true"
actionListener="#{locationsCollector.addCurrentLocation}"/>
</f:facet>
<af:inputText label="Label" id="it1" autoSubmit="true"
value="#{currentLocation.label}"/>
<af:inputText label="Description" id="it1a" autoSubmit="true"
value="#{currentLocation.description}"/>
<af:inputText label="Location (NO SPACES)" id="it2" autoSubmit="true"
value="#{currentLocation.location}"/>
</af:panelFormLayout>
<af:spacer id="spac1" height="40"/>
<af:table value="#{locationsCollector.locations}" var="row"
rowBandingInterval="0" id="t1" partialTriggers="::cb1">
<af:column sortable="false" headerText="Label" align="start" id="c1">
<af:outputText value="#{row.label}" id="ot1"
shortDesc="#{row.description}"/>
</af:column>
<af:column sortable="false" headerText="Description" align="start" id="c2">
<af:outputText value="#{row.description}" id="ot2"/>
</af:column>
<!--<af:column sortable="false" headerText="Country" align="start" id="c3">
<af:outputText value="#{row.country}" id="ot3"/>
</af:column>-->
</af:table>
</af:panelGroupLayout>
</f:facet>
<!--<f:facet name="top">
<af:panelHeader text="Enter location details" id="ph2">
<f:facet name="context"/>
<f:facet name="menuBar"/>
<f:facet name="toolbar"/>
<f:facet name="legend"/>
<f:facet name="info"/>
</af:panelHeader>
</f:facet>-->
</af:decorativeBox>
</f:facet>
<f:facet name="second">
<dvt:thematicMap basemap="usa" id="tm1" partialTriggers="::cb1" summary="map">
<dvt:areaLayer layer="states" id="al1" rendered="true">
<dvt:pointDataLayer id="pdl1c" value="#{locationsCollector.locations}" var="row">
<dvt:pointLocation id="pl1c" type="pointXY" pointX="#{row.lattitude}"
pointY="#{row.longitude}">
<dvt:marker id="m1c" labelDisplay="on" value="#{row.label}"
labelPosition="top"
shortDesc="#{row.description} #{row.location} "/>
</dvt:pointLocation>
</dvt:pointDataLayer>
</dvt:areaLayer>
</dvt:thematicMap>
</f:facet>
</af:panelSplitter>
<!-- id="af_one_column_header_stretched" -->
</f:facet>
</af:panelStretchLayout>
</af:form>
And here is the bean for getting the latitude and longitude from Geocoder to add to the map's point detail:
public class Location {
private String location;
private String country;
private String label;
private String description;
private float[] coordinates;
private static float[] getCoordinatesForLocation(String location) {
URL geoCodeUrl;
String url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + location
+ "&oe=utf8&sensor=false";
try {
geoCodeUrl
= new URL(url);
} catch (MalformedURLException e) {
System.out.println(e.getMessage() + " url=" + url);
return null;
}
BufferedReader in;
String coord = null;
try {
in = new BufferedReader(new InputStreamReader(geoCodeUrl.openStream()));
char[] buf = new char[8000];
in.read(buf);
coord = new StringBuilder().append(buf).toString();
in.close();
} catch (IOException e) {
System.out.println(e.getMessage() + " IO Exception ");
return null;
}
if (coord != null) {
float[] coordinates;
try {
// find first occurrence of lat
int posLAT = coord.indexOf("\"lat\"");
String latString = coord.substring(posLAT, posLAT + 21);
String lat = latString.split(":")[1].replaceAll(" ", "").replaceAll(",", "");
// find first occurrence of lng
int posLNG = coord.indexOf("\"lng\"");
String lngString = coord.substring(posLNG, posLNG + 21);
String lng = lngString.split(":")[1].replaceAll(" ", "").replaceAll(",", "");
coordinates
= new float[]{Float.parseFloat(lat), Float.parseFloat(lng)};
return coordinates;
} catch (Exception e) {
System.out.println("Coordinates stank " + coord);
}
}
System.out.println("Failed to create proper coordinates; sorry!");
return null;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountry() {
return country;
}
public void setLabel(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void setCoordinates(float[] coordinates) {
this.coordinates = coordinates;
}
public float[] getCoordinates() {
if (coordinates == null) {
coordinates = getCoordinatesForLocation(location);
}
return coordinates;
}
public float getLongitude() {
return getCoordinates()[0];
}
public float getLattitude() {
return getCoordinates()[1];
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
All I'm looking for is the ability for the program to accept an address with spaces so the program is more user friendly. Thanks for looking this over!

PrimeFaces add row to DataTable

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.

MySQL YEAR field - how to input from jsf

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>

primefaces selectOneMenu not outputting correctly

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