Reputation: 54802
In my application I want to enter a date in an <input>
field which is programatically created for a JSF page.
The creation of the input field looks like this:
// Input
String jsfValue = String.format("#{%s.item.%s}", getELClassname(), property.getKey());
ValueExpression valueExpression = JSFUtils.createValueExpression(jsfValue, property.getValue());
HtmlInputText input = (HtmlInputText) app.createComponent(HtmlInputText.COMPONENT_TYPE);
input.setId(property.getKey());
input.setValueExpression("value", valueExpression);
The property
is an instance of java.util.Date
and the <input>
field is just an HtmlInputText
component without any converter assigned to it.
When the <input>
tag is rendered, then the following value can be seen for a date:
Tue Mar 11 18:31:20 CET 2014
If I know want to save the form, then the JSF page complains about the format of the date because it is not able to convert the input value to a java.util.Date
.
Can someone tell me how I can create a converter programatically for a HtmlInputText
component?
When I was using MyFaces
for my application then the conversion was done automatically because I never had this problem before.
Upvotes: 0
Views: 810
Reputation: 54802
The trick is to apply a DateTimeConverter
to the dynamically created input field so that JSF knows how to convert the given String into a proper java.util.Date
.
Here is a code sample:
HtmlInputText input = (HtmlInputText) app.createComponent(HtmlInputText.COMPONENT_TYPE);
...
DateTimeConverter converter = (DateTimeConverter) app.createConverter(DateTimeConverter.CONVERTER_ID);
converter.setPattern("mm/dd/yyyy");
input.setConverter(converter);
If other date formats are needed, you can take a look at Wikipedia: Date format by country.
Upvotes: 0
Reputation: 7459
DateTimeConverter converter = (DateTimeConverter) application.createConverter(Date.class);
converter.setPattern(somePattern);
input.setConverter(converter);
Upvotes: 1