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);
Related
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 am trying to combine primefaces (v6.0) tabView and editable dataTable in jsf 2.2 framework. From reading many excellent threads from this forum, I was able to add/remove tab dynamically and implement editable table which allows add/remove a row dynamically.
However I am having a trouble to read a property "name" belongs to Hobby object. To be precise, instead of viewing a property belong to Hobby object, IDE displays properties of Person object.
I am hoping experienced JSF developers be able to find my mistake and advise me what I've done wrong and how to correct it.
FYI-The example I pasted here is water down version.
<p:tabView value="#{bean.people}" var="person">
<p:tab title="#{person.name}">
<h:panelGrid>
<p:dataTable value="#{person.hobbies}" var="hobby">
<p:column headerText="my hobby">
#{hobby.name}
</p:column>
</p:datatTable>
</h:panelGrid>
</p:tab>
Managed bean:
#ManagedBean(name="bean")
#ViewScoped
public class Bean {
private List<Person> people;
#PostConstruct
public void init() {
people = new ArrayList<>();
}
// getter/setter for people
.....
}
Person model:
public class Person {
private List<Hobby> hobbies;
private String name;
public Person() {
hobbies = new ArrayList<>();
}
// getter/setter for hobbies and name
....
}
Hobby Model:
public class Hobby {
private String name;
// getter/setter for 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 wanted to create in JSF a combobox (selectOneMenu). I want to fill this combobox with all logins from one column from Database (SELECT logins FROM database).
Will be much gratefull from any help.
In your backing bean (YourBean in the example) you should have an array of Strings (or of objects with a getter method that returns the String you want). For instance lets assume you have the following code in your backing bean:
private ArrayList<String> logins; // read from DB
private String selectedLogin; // this will hold the selected value
// this method will be called by the JSF framework to get the list
public ArrayList<String> getLogins()
{
return logins;
}
public String getSelectedLogin()
{
return selectedLogin;
}
public String setSelectedLogin(String sl)
{
selectedLogin = sl;
}
In you Facelets page, assuming you are on JSF 2.x:
<h:selectOneMenu value="#{YourBean.selectedLogin}">
<f:selectItems value="#{YourBean.logins}" itemLabel="#{l}" itemValue="#{l}" var="l"/>
</h:selectOneMenu>
This will create a select menu with all the options in the array. Once the form is submitted the value will be set in the String value of your backing bean.
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