i have a simple problem but i didnot find a solution for it.
I have a simple p:selectCheckboxMenu and i want use the selectedDates after click on the button.
I tried it with f:convertDateTime
<h:form id="mainform">
<p:panelGrid columns="2">
<p:selectCheckboxMenu label="Date" value="#{myBean.selectedDates}">
<f:selectItems value="#{myBean.dates}" var="date" itemValue="#{date}" itemLabel="#{myBean.convertDate(date)}"/>
<f:convertDateTime type="date" pattern="dd-MM-yyyy"/>
</p:selectCheckboxMenu>
<p:commandButton value="Test" actionListener="#{myBean.printDates}"/>
</p:panelGrid>
but than i get an Error- Message: "Invaild Value".
Than i tried a Converter:
#FacesConverter("myDateConverter")
public class MyDateConverter extends DateTimeConverter{
public MyDateConverter(){
setPattern("MM/dd/yyyy");
}}
and
<p:selectCheckboxMenu label="Date" value="#{myBean.selectedDates}" converter="myDateConverter">
But same error message. When i use no converter i get "String"- Values in my Date-List because type erasure.
Question: How i get the selected dates as dates?
Here is my bean for completeness:
#ManagedBean(name = "myBean")
#ViewScoped
public class MyBean implements Serializable {
private List<Date> dates;
private List<Date> selectedDates;
private SimpleDateFormat dateFormat;
#PostConstruct
public void init() {
System.out.println("POST CONSTRUCT!");
dateFormat = new SimpleDateFormat("yyyy.MM.dd");
dates = new ArrayList<Date>();
dates.add(new Date());
}
/**
*
*/
public void printDates(){
for(Date d : selectedDates){
System.out.println(d);
}
}
/**
*
* #param date
* #return
*/
public String convertDate(Date date){
return dateFormat.format(date);
}
The converter is the source of the problem as it removes the time and then it uses the default time when converting back to Date.
You can use
< f:convertDateTime pattern="yyyy-MM-dd HH:mm:ss.SSS Z" />
or try with a < f:datetimeconverter >
Related
Have a nice day. I don't know if i'm wrong about this. I have a form in my xhtml like this:
<p:outputLabel value="Número de pasajeros" />:
<p:inputText value="#{vueloMB.instancia.numPasajeros}" maxlength="3" >
</p:inputText>
<br />
<p:outputLabel value="Hora de salida" />:
<p:calendar value="#{vueloMB.instancia.fechaHoraSalida}" navigator="true"
mode="popup" pattern="dd/MM/yyyy HH:mm" />
<br />
<p:outputLabel value="Avión" />:
<p:selectOneMenu value="#{vueloMB.instancia.avion}" >
<f:selectItems value="#{vueloMB.aviones}" var="avi"
itemLabel="#{avi.modelo}" itemValue="#{avi}" />
</p:selectOneMenu>
<br />
<p:outputLabel value="Pais de salida" />:
<p:selectOneMenu value="#{vueloMB.instancia.paisSalida}" converter="omnifaces.SelectItemsConverter" >
<f:selectItems value="#{vueloMB.paises}" var="pai"
itemLabel="#{pai.nombre}" itemValue="#{pai}" />
<f:param name="tipoPais" value="S"></f:param>
<p:ajax update="ciusal" listener="#{vueloMB.cargarListaCiudades}" process="#this" >
</p:ajax>
</p:selectOneMenu>
<br />
<p:outputLabel value="Ciudad de salida" />:
<p:selectOneMenu value="#{vueloMB.instancia.ciudadSalida}" converter="omnifaces.SelectItemsConverter"
id="ciusal" disabled="#{vueloMB.instancia.paisSalida==null}" >
<f:selectItems value="#{vueloMB.ciudadesSalida}" var="ciu"
itemLabel="#{ciu.nombre}" itemValue="#{ciu}" />
</p:selectOneMenu>
<br />
<p:commandButton value="Guardar" rendered="#{vueloMB.instancia.id == null}" action="#{vueloMB.guardar()}" process="#form" ajax="true" />
</h:form>
The dropdown labeled "Ciudad de salida" refreshes another dropdown after i choose a country here, updates the list that feeds the second dropdown and it works fine. The problem is when i press the "Guardar" button to save the entity (vueloMB.instancia is my entity) with JPA, because it doesn't do anything.
So, i added the attribute immediate="true" to the button, it calls the ManagedBean method, but when i see the entity, only the field vueloMB.instancia.paisSalida isn't null, even if i fill all the fields. Because of that, i assumed that, because the dropdown calls an MB method because it refresh the second dropdown, it's value is refreshed on the MB. Based on that, i modified the first field like this:
<p:inputText value="#{vueloMB.instancia.numPasajeros}" maxlength="3" >
<p:ajax />
</p:inputText>
I added the ajax tag to my inputText. After doing that, i press the "Guardar" button and the field that i've modified (Número de pasajeros) now it carries the value on vueloMB.instancia.numPasajeros.
So, if i add to all my fields, when i press the submit button it will work, it will save the entity without problems and all the fields will travel to the managed bean, but is necessary to do that with every field? There's no automatic way JSF does this? Or i have something wrong with my code?
EDIT: Here is the code of the managed bean. A CDI Managed Bean with #ConversationScoped:
package com.saplic.fut.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import com.saplic.fut.daos.VueloDAO;
import com.saplic.fut.entity.Avion;
import com.saplic.fut.entity.Ciudad;
import com.saplic.fut.entity.Pais;
import com.saplic.fut.entity.Vuelo;
#Named("vueloMB")
#ConversationScoped
public class VueloManagedBean implements Serializable {
private static final long serialVersionUID = -203436251219946811L;
#Inject
private VueloDAO vueloDAO;
#Inject
private Conversation conversation;
#PostConstruct
public void iniciarConversacion() {
if(conversation.isTransient())
conversation.begin();
}
public void finalizarConversacion() {
if(!conversation.isTransient())
conversation.end();
}
private Vuelo instancia;
private List<Vuelo> vuelos;
private List<Avion> aviones = new ArrayList<Avion>();
private List<Pais> paises = new ArrayList<Pais>();
private List<Ciudad> ciudadesSalida = new ArrayList<Ciudad>();
private List<Ciudad> ciudadesAterrizaje = new ArrayList<Ciudad>();
private Integer idVuelo;
public String cargarLista() {
iniciarConversacion();
vuelos = vueloDAO.cargarVuelos();
return "/vuelos/lista";
}
public void cargarListaCiudades() {
String tipoLista = FacesContext.getCurrentInstance().
getExternalContext().getRequestParameterMap().get("tipoPais");
if(tipoLista.equalsIgnoreCase("S"))
setCiudadesSalida(vueloDAO.cargarCiudades(getInstancia().getPaisSalida()));
if(tipoLista.equalsIgnoreCase("A"))
setCiudadesAterrizaje(vueloDAO.cargarCiudades(getInstancia().getPaisAterrizaje()));
}
public String cargarDetalle() {
Vuelo fltVuelo = new Vuelo();
fltVuelo.setId(getIdVuelo());
instancia = vueloDAO.cargarDetalle(fltVuelo);
if(instancia == null)
setInstancia(new Vuelo());
//Cargamos lista de aviones para combo
setAviones(vueloDAO.cargarAviones());
setPaises(vueloDAO.cargarPaises());
return "/vuelos/detalle";
}
public String guardar() {
vueloDAO.guardar(instancia);
finalizarConversacion();
return cargarLista();
}
public String actualizar() {
vueloDAO.actualizar(instancia);
finalizarConversacion();
return cargarLista();
}
public String eliminar() {
vueloDAO.eliminar(instancia);
finalizarConversacion();
return cargarLista();
}
public Vuelo getInstancia() {
return instancia;
}
public void setInstancia(Vuelo instancia) {
this.instancia = instancia;
}
public List<Vuelo> getVuelos() {
return vuelos;
}
public void setVuelos(List<Vuelo> vuelos) {
this.vuelos = vuelos;
}
public Integer getIdVuelo() {
return idVuelo;
}
public void setIdVuelo(Integer idVuelo) {
this.idVuelo = idVuelo;
}
public List<Avion> getAviones() {
return aviones;
}
public void setAviones(List<Avion> aviones) {
this.aviones = aviones;
}
public List<Pais> getPaises() {
return paises;
}
public void setPaises(List<Pais> paises) {
this.paises = paises;
}
public List<Ciudad> getCiudadesSalida() {
return ciudadesSalida;
}
public void setCiudadesSalida(List<Ciudad> ciudadesSalida) {
this.ciudadesSalida = ciudadesSalida;
}
public List<Ciudad> getCiudadesAterrizaje() {
return ciudadesAterrizaje;
}
public void setCiudadesAterrizaje(List<Ciudad> ciudadesAterrizaje) {
this.ciudadesAterrizaje = ciudadesAterrizaje;
}
}
Regards.
Your entities must implements the method equals() hashCode() and toString as specified in the omnifaces showcase. I can't help you much more than that since I'm not familiar with omnifaces and the ConversationScope. I think it's because the two objects are not at the same place in memory so when you use equals the result is false. In the case of omnifaces I read it uses toString() to see if two objects are equal so if the method is not reimplemented you will have different results.
In other words you have null values because when the value as string comes back from the form it cannot be converted back to the original object. I'd appreciate if someone could attest this as I'm not 100% positive that's what is happening.
I have created a client for my SOAP web service using JSF and RichFaces. Below is my view:
<h:form>
<h:panelGrid id="panel" width="80%" columns="2" columnClasses="col1,col2">
<rich:panel>
<h:outputLabel value="Application Name " />
<h:selectOneMenu value="#{userComplaintBean.appName}">
<f:selectItem itemValue="1" itemLabel="Select" />
<f:selectItem itemValue="App1" itemLabel="App1" />
<f:selectItem itemValue="App2" itemLabel="App2" />
<f:selectItem itemValue="App3" itemLabel="App3" />
<f:selectItem itemValue="App4" itemLabel="App4" />
<f:selectItem itemValue="App5" itemLabel="App5" />
</h:selectOneMenu>
<br />
<h:outputLabel value="Complaint Description " />
<h:inputTextarea value="#{userComplaintBean.complaintDesc}" />
<br />
<h:outputLabel value="Date Expected "/>
<rich:calendar datePattern="yyyy/MM/dd" />
<br/>
<h:commandButton value="submit" action="#{userComplaintBean.save()}" />
</rich:panel>
</h:panelGrid>
</h:form>
Below is my managed bean:
#ManagedBean(name = "userComplaintBean")
#RequestScoped
public class UserComplaintBean {
UserComplaintVO userComplaintVO;
UserComplaintWS userComplaintWS;
UserComplaintWSImplService userComplaintWSImplService;
private int id;
private String appName;
private String complaintDate;
private String complaintDesc;
private Date tentativeDate;
public XMLGregorianCalendar getComplaintDate() throws DatatypeConfigurationException {
XMLGregorianCalendar xgc = null;
GregorianCalendar gc;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
complaintDate = dateFormat.format(date);
gc = (GregorianCalendar) GregorianCalendar.getInstance();
gc.setTime(date);
xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
return xgc;
}
public void setComplaintDate(String complaintDate) {
this.complaintDate = complaintDate;
}
/*
public XMLGregorianCalendar getTentativeDate() throws DatatypeConfigurationException {
XMLGregorianCalendar xgc = null;
GregorianCalendar gc;
String td;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
td = dateFormat.format(tentativeDate);
gc = (GregorianCalendar) GregorianCalendar.getInstance();
gc.setTime(tentativeDate);
xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
return xgc;
}
public void setTentativeDate(Date tentativeDate) {
this.tentativeDate = tentativeDate;
}
*/
public String save() throws DatatypeConfigurationException {
userComplaintWSImplService = new UserComplaintWSImplService();
userComplaintWS = userComplaintWSImplService.getUserComplaintWSImplPort();
UserComplaintVO userComplaintVO = new UserComplaintVO();
userComplaintVO.setAppName(getAppName());
userComplaintVO.setComplaintDate(getComplaintDate());
userComplaintVO.setComplaintDesc(getComplaintDesc());
//userComplaintVO.setTentativeDate(getTentativeDate());
userComplaintWS.userComplaintMethod(userComplaintVO);
System.out.println("Complaint Saved...");
return "Success";
}
}
Here I am taking complaintDate from <rich:calendar> which I need to convert to XMLGregorianCalendar format and I am not able to do it.
How can I do the abovementioned conversion?
You're basically making a major design mistake. You shouldn't be mingling a SOAP-specific model into your JSF-specific model. The <rich:calendar> takes a java.util.Date. You should design your model in such way that you provide exactly what the view expects. You should do the SOAP-specific model conversion only afterwards, in the business service method during processing the JSF form submit as preparation for the SOAP request.
Thus, ideally you should be using:
private Date copmlaintDate; // +getter+setter
with
<rich:calendar value="#{userComplaintBean.complaintDate}" />
and then in save() method
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(complaintDate);
XMLGregorianCalendar xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
But if you have really a hard head in for some reason, then you could always hack it around as follows, given that your environment supports EL 2.2 (your action method syntax confirms that this is the case):
private XMLGregorianCalendar copmlaintDate; // +getter (no setter necessary!)
with
<rich:calendar value="#{userComplaintBean.complaintDate.toGregorianCalendar().time}" />
Otherwise, you could always add a new getter, returning the concrete java.util.Calendar instance:
public Calendar getComplaintDateAsCalendar() {
return complaintDate.toGregorianCalendar();
}
with
<rich:calendar value="#{userComplaintBean.complaintDateAsCalendar.time}" />
Although I don't fully understand the reason behind using an XMLGregorianCalendar for keeping the date instances instead of the good old java.util.Date, the way to go is to create your own #FacesConverter that will do the desired transformation for you. Also, beware of doing business logic / performing potentially lengthy calculations in the getter methods that you're doing righ now. One of the ways of achieving that is to extend the JSF-builtin DateTimeConverter.
The kickoff Converter example is provided next:
#FacesConverter("XMLGregorianCalendarConverter")
public class XMLGregorianCalendarConverter extends DateTimeConverter {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if(value == null || value.equals("")) {
return null;
}
Date date = super.getAsObject(context, component, value);
GregorianCalendar gc = new GregorianCalendar();
cg.setTime(date);
XMLGregorianCalendar xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
if(xgc == null) {
throw new ConverterException(new FacesMessage("Error converting to XMLGregorianCalendar."));
}
return xgc;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (!(value instanceof XMLGregorianCalendar) || (value == null)) {
return null;
}
Date date = ((XMLGregorianCalendar)value).toGregorianCalendar().getTime();
return super.getAsString(context, component, date);
}
}
I'm trying to implement a list of users names which can be rearranged by clicking on UP or DOWN links.
<ul>
<ui:repeat var="user" value="#{cc.attrs.value}">
<li>
#{user.name}
<h:link outcome = "user" value = "left" onclick="#{accountController.moveDown}">
<f:param name="id" value = "${user.id}" />
</h:link>
</li>
</ui:repeat>
</ul>
The problem here is that it seems that I'm not using the onclick attribute correctly. What is the proper way for doing this?
Edit: Following your advices I placed all the links in a form:
<h:form>
<ui:repeat value="#{cc.attrs.value}" var = "user">
<div class = "user">
<h:commandLink id = "Link1" value = "Up" binding = "#{accountController.ommandLink}" action = "#{accountController.moveUserUp}">
<f:attribute name = "userId" value = "#{user.id}" />
</h:commandLink>
<h:commandLink id = "Link2" value = "Down" binding = "#{accountController.commandLink}" action = "#{accountController.moveUserDown}">
<f:attribute name = "userId" value = "#{user.id}" />
</h:commandLink>
<h:commandLink id = "Link3" value = "Delete" binding = "#{accountController.commandLink}" action = "#{accountController.deleteUser}">
<f:attribute name = "userId" value = "#{user.id}" />
</h:commandLink>
</div>
</h:form>
the Managed Bean:
private UIComponent commandLink;
public void moveUserUp(){
Integer userId = (Integer)commandLink.getAttributes().get("userId");
System.out.println("MOVE TAB LEFT :" + userId);
}
public void moveUserDown(){
Integer userId = (Integer)commandLink.getAttributes().get("userId");
System.out.println("MOVE TAB RIGHT: " + userId);
}
public void deleteUser(){
Integer userId = (Integer)commandLink.getAttributes().get("userId");
System.out.println("DELETE TAB: " + userId);
}
public UIComponent getCommandLink() {
return commandLink;
}
public void setCommandLink(UIComponent commandLink) {
this.commandLink = commandLink;
}
The communication between the command Link and the managed bean is working but in the UI only the last commandLink (close action) is displayed.
In order to invoke a bean action method on click of a link, you need <h:commandLink>. This must be enclosed in a <h:form>.
<h:form>
<h:commandLink ... action="#{bean.action}" />
</h:form>
public String action() {
// ...
return "/other.xhtml";
}
In JSF, only the attributes which interpret the EL expression as a MethodExpression can be used to declare action methods. All other attributes are interpreted as ValueExpression and they are immediately executed when the HTML output is generated by JSF. This covers the onclick attribute, whose value should actually represent a JavaScript function.
In case you actually want to use a GET link, then move the action method to a <f:viewAction> in the target page. This will be invoked on page load of the target page.
<h:link ... outcome="/other.xhtml" />
<f:metadata>
<f:viewAction action="#{bean.onload}" />
</f:metadata>
public void onload() {
// ...
}
See also:
When should I use h:outputLink instead of h:commandLink?
How to send form input values and invoke a method in JSF bean
How do I process GET query string URL parameters in backing bean on page load?
How to navigate in JSF? How to make URL reflect current page (and not previous one)
Following your advices I placed all the links in a form
The communication between the command Link and the managed bean is working but in the UI only the last commandLink (close action) is displayed.
You should not bind multiple physically different components to one and same bean property. Also the <f:attribute> to pass arguments is hacky and not necessary anymore in JSF2. Assuming that you're using a Servlet 3.0 / EL 2.2 container (your question history confirms that you're using Glassfish 3), rather just pass the argument as method argument directly:
<h:commandLink id="Link1" value="Up" action="#{accountController.moveUserUp(user)}" />
<h:commandLink id="Link2" value="Down" action="#{accountController.moveUserDown(user)}" />
<h:commandLink id="Link3" value="Delete" action="#{accountController.deleteUser(user)}" />
with
public void moveUserUp(User user) {
// ...
}
public void moveUserDown(User user) {
// ...
}
public void deleteUser(User user) {
// ...
}
See also:
How does the 'binding' attribute work in JSF? When and how should it be used?
Invoke direct methods or methods with arguments / variables / parameters in EL
The onclick attribute is used to invoke JavaScript function (client-side). It is be used when you want to attach a JavaScript click event hanlder.
"#{accountController.moveDown}" is a method-expression. And as the name suggests looks like accountController is a managed bean.
As the h:link doc says:
javax.el.ValueExpression (must evaluate to java.lang.String)
Can be a value expression that must ultimately evaluate to a string.
Javascript code executed when a pointer button is clicked over this element.
Update:
May be what you are looking for is h:commandLink. You can use the action attribute to invoke the backing bean method.
I have modified your code, let me know if this is what you are looking at achive
<h:form>
<a4j:outputPanel id="userList" ajaxRendered="false">
<ui:repeat value="#{manageUser.userList}" var="user">
<div class="user">
<h:panelGrid columns="3">
<h:outputText value="#{user.userId} ---- #{user.userName} ---- " />
<a4j:commandLink id="LinkUp" value="Up" execute="#this"
action="#{manageUser.moveUserUp}" limitRender="true" render="userList" >
<f:setPropertyActionListener value="#{user}" target="#{manageUser.user}" />
</a4j:commandLink>
<a4j:commandLink id="LinkDown" value="down"
action="#{manageUser.moveUserDown}" execute="#this" limitRender="true" render="userList" >
<f:setPropertyActionListener value="#{user}" target="#{manageUser.user}" />
</a4j:commandLink>
</h:panelGrid>
</div>
</ui:repeat>
</a4j:outputPanel>
</h:form>
Managed Beans (ManageUser)
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean(name="manageUser")
#ViewScoped
public class ManageUser implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5338764155023244249L;
private List<UserBean> userList;
private UserBean user;
/**
* #return the user
*/
public UserBean getUser() {
return user;
}
/**
* #param user the user to set
*/
public void setUser(UserBean user) {
this.user = user;
}
/**
* #return the userList
*/
public List<UserBean> getUserList() {
return userList;
}
/**
* #param userList the userList to set
*/
public void setUserList(List<UserBean> userList) {
this.userList = userList;
}
public ManageUser() {
UserBean user1= new UserBean();
user1.setUserId("1");
user1.setUserName("userName1");
UserBean user2= new UserBean();
user2.setUserId("2");
user2.setUserName("userName2");
UserBean user3= new UserBean();
user3.setUserId("3");
user3.setUserName("userName3");
userList = new ArrayList<UserBean>();
userList.add(user1);
userList.add(user2);
userList.add(user3);
}
public void moveUserDown(){
if(user !=null){
int indexObj= userList.indexOf(user);
if(indexObj < userList.size()-1){
UserBean tempUser=userList.get(indexObj+1);
userList.set(indexObj+1, user);
userList.set(indexObj, tempUser);
}
}
}
public void moveUserUp(){
if(user !=null){
int indexObj= userList.indexOf(user);
if(indexObj > 0){
UserBean tempUser=userList.get(indexObj-1);
userList.set(indexObj-1, user);
userList.set(indexObj, tempUser);
}
}
}
}
UserBean
import java.io.Serializable;
public class UserBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3820279264217591645L;
private String userName;
private String userId;
/**
* #return the userName
*/
public String getUserName() {
return userName;
}
/**
* #param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* #return the userId
*/
public String getUserId() {
return userId;
}
/**
* #param userId the userId to set
*/
public void setUserId(String userId) {
this.userId = userId;
}
}
I have a <h:selectOneMenu> that has <f:selectItems> with CategoryHistory objects loaded in it. I only show the Date date field as itemLabel.
That works but I want to format the date:
I created a converter that extends javax.faces.convert.DateTimeConverter and change the fields in the constructor. But my dates only show in default format :(
DateAndTimeConverter.java
import javax.faces.bean.ManagedBean;
import javax.faces.convert.Converter;
import javax.faces.convert.DateTimeConverter;
import javax.faces.convert.FacesConverter;
#FacesConverter(value = "dateAndTimeconverter")
#ManagedBean
public class DateAndTimeConverter extends DateTimeConverter implements Converter {
public DateAndTimeConverter(){
this.setDateStyle("short");
}
xhtml
<h:selectOneMenu valueChangeListener="#{admin.categoryHistoryListener}"
onchange="submit()" value="#{admin.categoryHistory.id}" converter="#{dateAndTimeconverter}">
<f:selectItems value="#{admin.categoryHistories}" var="n"
itemValue="#{n.id}" itemLabel="#{n.date}">
</f:selectItems>
</h:selectOneMenu>
It also doesn't work when I try:
<h:selectOneMenu valueChangeListener="#{admin.categoryHistoryListener}"
onchange="submit()" value="#{admin.categoryHistory.id}">
<f:converter converterId="dateAndTimeconverter"/>
<f:selectItems value="#{admin.categoryHistories}" var="n"
itemValue="#{n.id}" itemLabel="#{n.date}">
</f:selectItems>
</h:selectOneMenu>
CategoryHistory Has a Date date, and Long id +...
Thank you
Unfortunately, the JSF converters only applies on the input value, not on the input label.
You'll need to solve this other ways. E.g. a getter which uses SimpleDateFormat to format the date. Or if your environment supports EL 2.2, simply invoke the converter method directly (you've it as managed bean already):
<f:selectItems value="#{admin.categoryHistories}" var="n" itemValue="#{n.id}"
itemLabel="#{dateAndTimeconverter.getAsString(facesContext, component, n.date)}">
If you happen to use JSF utility library OmniFaces, then you can also use its of:formatDate() function. E.g.:
<f:selectItems value="#{admin.categoryHistories}" var="n" itemValue="#{n.id}"
itemLabel="#{of:formatDate(n.date, 'd MMM yyyy')}">
You can use a converter method in your bean, as:
public class Admin{
...
public String formatDate(Date fecha, String pattern) {
return (new SimpleDateFormat(pattern)).format(fecha);
}
...
}
And, in your xhtml page inside f:selectItems:
<f:selectItems value="#{admin.categoryHistories}" var="n"
itemValue="#{n.id}" itemLabel="#{admin.formatDate(n.date,'d MMM yyyy')}">
</f:selectItems>
Example
xhtml
<h:selectOneMenu value="#{tbMonitoreoController.fechaMonitoreo}">
<f:selectItems value="#{tbMonitoreoController.fechasMonitoreo}" />
Method in tbMonitoreoController
public SelectItem[] getFechasMonitoreo(){
Collection<Date> entities = getEjbFacade().getFechasMonitoreo();
return JsfUtil.getSelectItemsFechasMonitoreo(entities, true);
}
public static SelectItem[] getSelectItemsFechasMonitoreo(Collection<Date> listDate, boolean selectOne) {
int size = selectOne ? (listDate.size() + 1) : listDate.size();
SelectItem[] items = new SelectItem[size];
int i = 0;
if (selectOne) {
items[0] = new SelectItem(null, "---");
i++;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
for (Date x : listDate) {
items[i++] = new SelectItem(x, simpleDateFormat.format(x));
}
return items;
}
I have a input in which I want current date to be displayed.
It looks like this:
<p:inputMask id="kalendarz" autocomplete="false" styleClass="#{cc.attrs.styleClass}" mask="99.99.9999"
value="#{cc.attrs.value}" required="#{cc.attrs.required and param['fillDataAction']==null}" disabled="#{cc.attrs.isDisabled}"
style="#{cc.attrs.style}" onchange="#{cc.attrs.onchange}" readonly="#{cc.attrs.readonly}" label="#{cc.attrs.label}"
onblur="#{cc.attrs.onblur}" onselect="#{cc.attrs.onselect}">
<f:converter converterId="#{cc.attrs.converter}">
</p:inputMask>
How can I display current date in this inputMask? I was trying using javascript to setAttribute placeHolder, but it doesn't work
try
#Named("cc")
#Viewscoped
public class YourBean implements Serializable{
....
#PostConstruct
public void init(){
...
this.attrs.setValue(new Date());//this should
...
}
...
}