I have an xhtml page
<p:outputPanel>
<p:outputLabel id="temp1"
for="temp11" value="Start Date:" />
<p:calendar id="startDateId"
widgetVar="startDateFromVar" title="#"
showOn="button" disabled="true"/>
</p:outputPanel>
bean
private String date;
/**
* #return the Date
*/
public String getDate() {
date = "11/10/2012 19:15";
return date;
}
/**
* #param Date the Date to set
*/
public void setDate(String ate) {
this.date = date;
}
How to show date in xhtml? I have been adding this line in p:calendar
value=#{bean.date}
but it's not showing the date as well as the calender icon.
Any help would be appreciated.
The value you display with <p:calendar/> should be type of java.util.Date (as kolossus already pointed out). In case if you already have a known string representation of the date, you need to parse that string with java.text.SimpleDateFormat to get a java.util.Date object:
private void parserDate() {
String dateStr = "11/10/2012 19:15";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm");
try {
date = formatter.parse(dateStr);
} catch (ParseException ex) {
// handle
}
}
public Date getDate() {
if (date == null)
parserDate();
return date;
}
public void setDate(Date date) {
this.date = date;
}
The display pattern of the calendar element can also be formatted. To display the date with the same formatting as dateStr use the pattern attribute:
<p:calendar id="startDateId" value="#{bean.date}" disabled="true"
widgetVar="startDateFromVar" pattern="dd/MM/yyyy HH:mm"/>
if you use the disabled="true"option on your calendar, use p:inputText instead to display your private String date. Then you can eliminate the additional parsing and formatting:
<p:inputText value="#{bean.date}" disabled="true"/>
pointing to an ID in <p:outputLabel for="..."/> which doesn't exist, results in FacesException. Maybe you wanted:
<p:outputLabel id="temp1" for="startDateId" value="Start Date:" />
Since the StackOverflow just epically revived this question into the homepage, let me try to answer it.
There are lots of problems here. Let's start in the begin:
1) Your date in the bean is not a real date. It is a String! The solution is that easy: change your bean to handle java.util.Date instead of java.lang.String if you want to handle dates.
import java.util.Date;
public class MyDateBean {
private Date date;
public Date getDate() {
return this.date;
}
public void setDate(Date date) {
this.date = date;
}
}
2) If you want just to show the date, use the default outputtext JSF component to do it. Remember to add the converter with the desired format:
<h:outputText value="#{myDateBean.date}" >
<f:convertDateTime pattern="dd/MM/yyyy HH:mm" />
</h:outputText>
By the way, the component you have used:
<p:calendar id="startDateId"
widgetVar="startDateFromVar" title="#"
showOn="button" disabled="true"/>
Is a primefaces calendar component to allow users to pick dates from a calendar panel. If you need it do something like that:
<p:calendar id="startDateId" value="#{myDateBean.date}" pattern="MM/dd/yyyy HH:mm:ss"/>
to obtain:
There are some customisations you can apply. Please refer the Primefaces Demo Page to learn more about the Calendar Primefaces Component: https://www.primefaces.org/showcase/ui/input/calendar.xhtml
Related
I need to edit datetime value that is on the HTML table. I got the table data as a string then convert to Datetime and get the value in a time field of Html I mean <input type="time" >. I can get the value but I cannot edit from the HTML. Here is my code:
<input type="time" style="width:100%" #bind="#my_DateTime" />
Here is my model class. Note that I got the data as a string then convert it as a Datetime.
private DateTime? _my_DateTime;
[Parameter]
public DateTime? my_DateTime
{
get
{
if (mytimestring != "") //This is String I got data
{
_my_DateTime = Convert.ToDateTime(mytimestring);
return _my_DateTime ;
}
else
{
_my_DateTime = null;
return _my_DateTime ;
}
}
set
{
_my_DateTime = value;
OnPropertyChanged("my_DateTime");
//}
// NotifyOfPropertyChange(() => 並び順);
}
}
This is the string property I got from table:
private string _mytimestring;
[Parameter]
public string mytimestring
{
get
{
return _mytimestring ;
}
set
{
_mytimestring = value;
OnPropertyChanged(mytimestring");
// NotifyOfPropertyChange(() => 並び順);
}
}
Note I bind value to textbox like <input type="text" #bind="#名称Str" /> and it works but only Datetime I cause issue.
I think this is one of the things that have changed after a lot of advice was already on the internet. I found that the binding works perfectly without any parsing or formatting.
I was also very surprised to see that when you bind an html time input to a C# DateTime, it will actually fill in today's time and date automatically. (Not needed for your question, but a very interesting thing to know I think)
The following worked fine for me.
#page "/time"
<input type="time" #bind="#SomeTime" />
<br />
#SomeTime.ToString("hh:mm tt")
<br />
#SomeTime.ToString()
#code {
public DateTime SomeTime = new DateTime();
}
I work with oracle DB, in my table I have one field string datatype (value: true or false)
I have tried to transform for this field p:selectOneMenu with p:selectBooleanButton by inspired solution from Convert h:selectBooleanCheckbox value between boolean and String,
I have tried this code in my persistence layer or in myBean
#Size(max = 5)
#Column(name = "CHAMP04")
private String champ04;
public boolean isChamp04() {
return "true".equals(champ04);
}
public void setChamp04(boolean champ04) {
this.champ04 = champ04 ? "true" : "false";
}
I get error
javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.
Caused By: java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.CharSequence.
this error be came when I go back to the p:dataTable list after save/cancel Dialogs views Edit or Create selected row.
<p:column>
<f:facet name="header">
<h:outputText value="#{bundle.ListTitle_champ04}" />
</f:facet>
<h:outputText value="#{item.champ04}" />
</p:column>
If I change declaration for the field, I get error
private boolean champ04;
javax.validation.UnexpectedTypeException: HV000030: No validator could be found for type: java.lang.Boolean
thank you in advance for your help and attention
we are trying to migrate our application from tomcat/websphere to was liberty profile.
Additionally we are upgrading the myfaces-version, we are using 2.1, to myfaces-2.2.
To save the current state of a table (filtering) we store the filtered value in a map and read it when loading the table (filterValue attribute of p:column).
When initially loading the table the correct method will be used (in our case its getFilterValue in the DataModel). But if we start filtering a column, the method wont be found anymore and the following exception occurs:
javax.el.PropertyNotFoundException: Die Eigenschaft 'getFilterValue' wurde nicht im Typ package.LazyModel gefunden.
javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:245)
javax.el.BeanELResolver$BeanProperties.access$300(BeanELResolver.java:222)
javax.el.BeanELResolver.property(BeanELResolver.java:332)
javax.el.BeanELResolver.getType(BeanELResolver.java:83)
javax.el.CompositeELResolver.getType(CompositeELResolver.java:99)
org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getType(FacesCompositeELResolver.java:150)
org.apache.el.parser.AstValue.setValue(AstValue.java:199)
org.apache.el.ValueExpressionImpl.setValue(ValueExpressionImpl.java:257)
org.jboss.weld.el.WeldValueExpression.setValue(WeldValueExpression.java:64)
org.apache.myfaces.view.facelets.el.ContextAwareTagValueExpression.setValue(ContextAwareTagValueExpression.java:153)
org.primefaces.component.datatable.DataTable.processUpdates(DataTable.java:746)
org.apache.myfaces.context.servlet.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:787)
org.apache.myfaces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:213)
org.primefaces.component.api.UIData.visitTree(UIData.java:822)
The table:
<p:dataTable id="table" var="group"
value="#{bean.lazyModel}"
selection="#{bean.selectedMulti}"
rows="#{bean.lazyModel.rows}" paginator="true"
currentPageReportTemplate="#{msg['data.table.pagereport']}"
paginatorTemplate="#{msg['data.table.paginator']}"
rowsPerPageTemplate="#{msg['data.table.rows']}"
resizableColumns="true" rowKey="#{group.pkId}" lazy="true"
filterDelay="1000" emptyMessage="#{msg['data.table.empty']}"
style="font-size: 8pt;"
tableStyle="font-size: 8pt; table-layout:auto;"
first="#{bean.lazyModel.first_m}"> >
<p:column headerText="Name"
sortBy="#{group.name}" filterBy="#{group.name}"
filterValue="#{bean.lazyModel.getFilterValue('name')}"
filterStyleClass="column_filter" styleClass="wrap">
<h:outputText value="#{group.name}" />
</p:column>
...
The lazymodel:
#Named
#Scope(value = "prototype")
public class LazyModel extends AbstractLazyModel<Brand> {
private static final long serialVersionUID = 2247660292777600670L;
/**
* Konstruktor
*/
public LazyModel() {
super();
}
public Object getFilterValue(final String keyForColumn) {
return this.filterManager.getFilterField(this.getKeyForPage(), keyForColumn);
}
I think this should be the most important things to know.
So, i dont understand what changed between these versions that trigger the exception.
Every help would be great. TIA!
I don't know why this has worked before (it should not have (properly)), but the error you are currently getting is sort of expected. The filterValue attribute should be bound to a property with read and write access. You could bind each column filter value to an individual property, but it is more convenient to use a Map<String,Object> for your filter values.
Bean (lazy model in your case):
private Map<String,Object> filterValues = new HashMap<>();
// ... add getter and setter for filterValues
XHTML:
filterValue="#{bean.lazyModel.filterValues['name']}"
I read some articles here and they always say:
Don't create components programatically, all you can do by code is possible in xhtml too
So I have an interesting question.
I have component Calendar:
<p:calendar>
<f:attribute name="value" value="#{column.properties['from_value']}" />
</p:calendar>
Or you can simplify it:
<p:calendar value="#{column.properties['from_value']}" />
Properties
column is var of <p:columns> component
It has variable properties which is Map<String,String>
In properties I have key from_value and inside it I have String : "#{bean.object.dateFrom}"
My question is:
How can i convert this string to ValueExpression ?
Because when I run this code. Inside p:calendar is value "#{bean.object.dateFrom}" ... I need to set it as valueExpression and not String
What I get:
Calendar: #{bean.object.dateFrom}
What I want to achieve:
Calendar: 02.11.2017
-
Same code but Programmatically :
public ValueExpression createValueExpression(String valueExpression, Class<?> valueType) {
FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().getExpressionFactory().createValueExpression(context.getELContext(), valueExpression, valueType);
}
...
Calendar fromCalendar = new Calendar();
fromCalendar.setValueExpression("value", createValueExpression(properties.get("from_value"), Object.class));
Hope it's clear what I want to achieve.
Thank's for replies
I'm trying to use enums to populate a PrimeFaces selectOneMenu, but could not get the selected value. After the first click, the value assigned is always the one in the post-constructor.
HTML:
<p:selectOneMenu id="periodo"
value="#{dashboardMB.enumDate}">
<f:selectItems value="#{dashboardMB.enumDates}"
var="enumDate"
itemValue="#{enumDate}"
itemLabel="#{enumDate.label}" />
</p:selectOneMenu>
Backing bean:
private EnumDate enumDate;
#PostConstruct
public void init() {
enumDate = EnumDate.YEAR;
}
EnumDate:
public enum EnumData {
EMPTY("- Select -"), DAY("Day"), WEEK("Week"), FORTNIGHT("Fortnight"), MONTH("Month"), BIMESTER("Bimester"), TRIMESTER("Trimester"), SEMESTER("Semester"), YEAR("Year");
public String label;
public static final EnumSet<EnumDate> all = EnumSet.of(EMPTY, DAY, WEEK, FORTNIGHT, MONTH, BIMESTER, TRIMESTER, SEMESTER, YEAR);
private EnumDate(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
}
Thus, it has always the value "Year". Until the button which sends the form is clicked again.
Solved using OmniFaces converter:
<p:selectOneMenu id="period"
converter="omnifaces.SelectItemsConverter"
style="width: 237px !important"
value="#{dashboardMB.enumDate}"
filter="true"
filterMatchMode="contains"
panelStyleClass="oneMenuPanel"
styleClass="oneMenu">
<f:selectItems value="#{dashboardMB.enumDateArray}"
var="enum"
itemValue="#{enum}"
itemLabel="#{enum.label}" />
</p:selectOneMenu>
The enumDateArray attribute is of EnumDate[] type. Its getter returns EnumDate.values().
Better to use the omnifaces generic enum converter. It keeps your code cleaner compared to 'manually' doing conversions of lists etc...
Convert enums into Strings
EnumData[] eds = EnumData.values();
String EDtoString = eds[0].name();
You can pass function String[] EnumDatasToString() to XHTML.
To convert from String to Enum use
EnumData ed = EnumData.valueOf(EDToString);