can't implemente p:selectBooleanButton - primefaces

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

Related

PropertyNotFoundException for p:column filterValue attribute

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']}"

PickList lose value

I have a simple persistent object (Hibernate, if it makes any different):
#Entity
Class ObjectA
{
private Long id;
private String name;
private String description;
private List<ObjectA> children = new LinkedList<>();
...
...
...
public org.primefaces.model.DualListModel<ObjectA> getDualList() {
org.primefaces.model.DualListModel<ObjectA> l = new org.primefaces.model.DualListModel<>();
l.setSource(this.children);
l.setTarget(database.getAllChildren()); // performs database query to retrieve all objectA that are not corrently linked to any objectA.
...
return l;
}
public setDualList(org.primefaces.model.DualListModel<ObjectA> l) {
this.children = l.getSource();
...
}
}
The PrimeFaces code looks like (relevant snippet):
...
<p:dataTable id="table" value="#{managedBeanA.getAllObjects}" var="iterator" paginator="true" rows="10" >
...
...
<p:rowExpansion>
<p:pickList value="#{iterator.dualList}" var="l" itemLabel="#{l.name}" itemValue="#{requirement.id}">
<f:facet name="sourceCaption">Linked Children</f:facet>
<f:facet name="targetCaption">Unlinked Children</f:facet>
<p:ajax event="transfer" listener="#{managedBeanA.handleTransfer(iterator)}"/>
</p:pickList>
</p:rowExpansion>
</p:dataTable>
What managedBeanA.handleTransfer does is simply persist the passed object.
Everything seems to work lovely, I can expand the row and getDualList is called. When I expand another row, another getDualList is called - all as expected.
When I move items from source to target, managedBeanA.handleTransfer is called and the relevant object is persisted in the database.
HOWEVER, and here is the question, when the table is updated - either form submit or ajax, I can see that setDualList is called for EVERY item in the p:dataTable with EMPTY getSource which, in essence, break all the links previously persisted (i.e. this.children = null). The previously linked ObjectA objects are still in database but they are no longer linked...
Any ideas what is going on?
I have found a solution to the problem. It is probably only a workaround as I am not sure what the problem actually is - in the setDualList method, I have added the following line:
if (l.getSource().isEmpty() && l.getTarget().isEmpty()) return;
which solves all my problems (as the symptom of the issues is that the setter is called with no values).

Selecting a SelectOneMenu populated with enum only after second click

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);

How do I render a String containing HTML code that a bean returns?

I have got a bean that have a method that checks if a user is logged in and returns a String containing HTML code. Is there any way that I can render this String on the webpage after it has been returned?
Of course. In your managed bean:
public String checkLogin() {
return "<h2><b>User was not logged in.</b></h2>";
}
And in your xhtml file:
<h:outputText escape="false" value="#{bean.checkLogin()}" />

How to display Date and Time value in a p:calender

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