Sorry for my bad english.
I try to show a selectOneMenu using converter but throws error:
java.lang.Integer cannot be cast to pojos.HoraRango
java.lang.ClassCastException: java.lang.Integer cannot be cast to pojos.HoraRango
at managedBeans.HoraRangoConverter.getAsString(HoraRangoConverter.java:46)
at org.primefaces.util.ComponentUtils.getValueToRender(ComponentUtils.java:114)
at org.primefaces.util.ComponentUtils.getValueToRender(ComponentUtils.java:61)
at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeLabel(SelectOneMenuRenderer.java:202)
at or
my xhtml
<p:outputLabel for="console" value="Basic:" />
<p:selectOneMenu id="console" value="#{bPistasDisponibles.inicioHoraElegido}" style="width:125px" converter="HoraRangoConverter">
<f:selectItems value="#{bPistasDisponibles.inicioHora}" var="inicioHora"
itemLabel="#{inicioHora.hora}" itemValue="#{inicioHora}" />
</p:selectOneMenu>
my converter
public class HoraRangoConverter implements Converter{
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if(value != null && value.trim().length() > 0) {
try {
DaoHoraRango daohoraRango = new DaoImplHoraRango();
HoraRango cat= daohoraRango.verHoraRango(Integer.parseInt(value));
return cat;
} catch(NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Cine."));
}
}
else {
return null;
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if(value != null) {
return String.valueOf(((HoraRango)value).getIdHoraRango());
}
else {
return null;
}
}
}
Thanks
Related
I am using selectCheckboxMenu from Primefaces in a JSF project, the problem is that the "selectedDepartments" object in the Bean is always empty.
Here is the code:
Xhtml Page
<p:selectCheckboxMenu id="menu" label="name" style="width: 15rem" converter="#{departmentConverter}" value="#{StudentMB.selectedDepartments}"
multiple="true" filter="true" filterMatchMode="startsWith" panelStyle="width: 15rem" scrollHeight="250" >
<c:selectItems value="#{StudentMB.departmentList}" var="department" itemLabel="#{department.name}" itemValue="#{department}"/>
<p:ajax event="change" process="#this" update=":form2:dt-Students" global="false"/>
</p:selectCheckboxMenu>
The converter for selectCheckboxMenu:
#Named
#FacesConverter(value = "departmentConverter")
public class departmentConverter implements Converter {
#Inject
private departmentDAO departmentDAO;
#Override
public department getAsObject(FacesContext context, UIComponent component, String value) {
if (value != null && value.trim().length() > 0) {
try {
department c= departmentDAO.getdepartmentById(Integer.parseInt(value));
return c;
}
catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid country."));
}
}
else {
return null;
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value != null) {
department c=(department)value;
return String.valueOf(c.getId());
}
else {
return null;
}
}
}
The code of the Managed Bean
public class StudentMB implements Serializable{
private LazyDataModel<Student> lazyModel = null;
private List<department> departmentList;
private List<department> selectedDepartments;
#Inject
private departmentDAO departmentDAO;
#PostConstruct
public void init() {
this.selectedDepartments= new ArrayList<>();
this.departmentList= new ArrayList<>();
this.departmentList = this.departmentDAO.listDepartments();
lazyModel = new StudentLazyList(StudentDAO){
#Override
public List<Student> load(int first, int pageSize, Map<String, SortMeta> sortBy, Map<String, FilterMeta> filterBy) {
return load2(first, pageSize, sortBy, filterBy,selectedDepartments);
}
};
}
}
Thanks for help.
The solution is found for those who encounter the same problem. it was relative to the converter, indeed I don't know why we have to use a converter when it comes to a Pojo class because we already mentioned the name of class in the value property of selectItems.
Nevermind , here is the code that works
The selectCheckboxMenu component
<h:form id="form1">
<p:selectCheckboxMenu id="menu" label="department" converter="departmentConverter" value="#{studentMB.selectedDepartments}"
multiple="true" filter="true" filterMatchMode="startsWith" style="width: 15rem" panelStyle="width: 15rem" scrollHeight="250" >
<c:selectItems value="#{studentMB.departmentList}" var="department" itemLabel="#{department.name}" itemValue="#{department}"/>
<p:ajax event="change" update=":form2:dt-students"/>
</p:selectCheckboxMenu>
</h:form>
The converter class
#Named
#FacesConverter(value = "departmentConverter")
public class DepartmentConverter implements Converter {
#Override
public Department getAsObject(FacesContext context, UIComponent component, String value) {
if(value == null)
return null;
StudentMB data = context.getApplication().evaluateExpressionGet(context, "#{studentMB}", StudentMB.class);
int actualId=Integer.parseInt(value);
for(Department dep : data.getDepartmentList())
{
if(categ.getId()==actualId)
return dep;
}
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid department."));
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value != null) {
Department c=(Department)value;
return String.valueOf(c.getId());
}
else {
return null;
}
}
}
Hope this help
I´m trying to use the Primefaces component: p:selectOneListbox
I would like to use the grouping function.
Currently I´m getting only a String instead the POJO. I´m already using a converter, but I don´t know what is currently wrong. If I´m returning only the List then it´s working fine and I´ve get the values as expected...
Here is my JSF code:
<p:selectOneListbox id="diagramElementList" value="#{myBean.selectedDiagramElementFromList}"
converter="diagramElementConverter" style="width: 100%"
var="diagramElement" filter="true" filterMatchMode="contains">
<f:selectItems
value="#{availableAutomationComponentControllerView.generateListAvailableElements()}"
var="diagramElement" itemLabel="#{diagramElement.name}"
itemValue="#{diagramElement}" />
<p:column style="width: 10px;">
<h:outputText value="#{diagramElement.icon}" />
</p:column>
Here my backend bean:
public List<SelectItem> generateListAvailableElements() {
try {
List<SelectItem> list = new ArrayList<SelectItem>();
SelectItemGroup g1 = new SelectItemGroup("Workflow");
List<DiagramElement> workflowList = automationElementService.generateListAvailableElements(
loginBean.getCurrentEmployee(), localeBean.getLanguage(),
AutomationElementCategory.WORKFLOW.toString());
g1.setSelectItems(createItemList(workflowList));
list.add(g1);
return list;
} catch (Exception e) {
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
ErrorMessage.showErrorMessage();
}
return null;
}
private SelectItem[] createItemList(List<DiagramElement> list) {
List<SelectItem> newlist = new ArrayList<SelectItem>();
for (DiagramElement e : list) {
newlist.add(new SelectItem(e, e.getName()));
}
SelectItem[] arr = new SelectItem[newlist.size()];
arr = newlist.toArray(arr);
return arr;
}
And here my converter:
#FacesConverter("diagramElementConverter")
public class DiagramElementConverter implements Converter {
#Inject
private AutomationElementService automationElementService;
#Inject
private LoginBean loginBean;
#Inject
private LocaleBean localeBean;
public String getAsString(FacesContext context, UIComponent component, Object object) {
String field = (object instanceof DiagramElement) ? ((DiagramElement) object).getId() : null;
return (field != null) ? String.valueOf(field) : null;
}
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
try {
if (submittedValue == null) {
return null;
}
if (submittedValue.trim().equals("")) {
return null;
} else {
for (DiagramElement diagramElement : automationElementService.generateListAvailableElements(
loginBean.getCurrentEmployee(), localeBean.getLanguage(), null)) {
if (diagramElement.getId().equals(submittedValue)) {
return diagramElement;
}
}
}
} catch (Exception e) {
}
return null;
}
}
I could help me know how to get the selected object
xhtml:
<p:selectOneRadio id="selection" value="#{miCurso.respuestaDTO}">
<f:selectItems value="#{pregunta.respuestas}" var="respuesta" itemLabel="#{respuesta.respuesta}" itemValue="#{respuesta}" />
</p:selectOneRadio>
I want to get the whole object not just itemLabel
<p:selectOneRadio id="selection" value="#{miCurso.respuestaDTO}" converter="clientesConverter">
<f:selectItems value="#{pregunta.respuestas}" var="respuesta" itemLabel="#{respuesta.respuesta}" itemValue="#{respuesta}" />
coverter for selectoneradio:
package JSF_Converters;
#FacesConverter(value = "clientesConverter")
public class ClientesConverter implements Converter {
#Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
if (arg2 == null || arg2.equals("")) {
return "";
}
if (arg0 == null) {
throw new NullPointerException("context");
}
if (arg1 == null) {
throw new NullPointerException("component");
}
return ((EmpresaClienteUtil) arg2).getCodigo();
}
#Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
if (arg2.trim().equals("")) {
return null;
}
if (arg0 == null) {
throw new NullPointerException("context");
}
if (arg1 == null) {
throw new NullPointerException("component");
}
FacesContext ctx = FacesContext.getCurrentInstance();
ValueExpression vex = ctx.getApplication().getExpressionFactory().createValueExpression(ctx.getELContext(), "#{comunMB}", ComunMB.class);
ComunMB items = (ComunMB) vex.getValue(ctx.getELContext());
EmpresaClienteUtil item;
try {
item = items.getItemClientes(arg2);
} catch (Exception e) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Valor desconocido", "El valor es desconocido!");
throw new ConverterException(message + e.getMessage());
}
if (item == null) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Valor desconocido", "El valor es desconocido!");
throw new ConverterException(message);
}
return item;
}
}
ComunMB
package ManagedBean;
#Named(value = "comunMB")
#ApplicationScoped
public class ComunMB {
public ComunMB() {
}
private HashMap<String, EmpresaClienteUtil> myHPClientes = new HashMap<String,EmpresaClienteUtil>();
public EmpresaClienteUtil getItemClientes(String clave) {
return (EmpresaClienteUtil) myHPClientes.get(clave);
}
}
Here is my SelectOneMenu
<h:selectOneMenu value="#{bean.myObject}" >
<f:ajax render="componentToRender" listener="#{bean.onSelect}"/>
<f:converter converterId="myObjectConverter" />
<f:selectItem itemLabel="None" itemValue="#{null}" />
<f:selectItems value="#{bean.objects}" var="object" itemValue="#{object}" itemLabel="#{object.name}" />
</h:selectOneMenu>
And my converter
#FacesConverter("myObjectConverter")
public class MyObjectConverter implements Converter{
private List<MyObject> objects;
public MyObjectConverter(){
this.objects = MyController.getAllMyObjects();
}
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if(!StringUtils.isInteger(value)) {
return null;
}
return this.getMyObject(value);
}
public String getAsString(FacesContext context, UIComponent component, Object value) {
if(value == null) {
return null;
}
return String.valueOf(((MyObject) value).getId()).toString();
}
public MyObject getMyObject(String id) {
Iterator<MyObject > iterator = this.objects.iterator();
while(iterator.hasNext()) {
MyObject object = iterator.next();
if(object.getId() == Integer.valueOf(id).intValue()) {
return object;
}
}
return null;
}
}
The problem is that my ajax listener is never called and my component never rendered.
Is there something wrong with my converter or selectOneMenu? I follow an example and I can't figure the mistake out.
BTW : my simple method in the bean
public void onSelect() {
System.out.println(this.myObject);
if(this.myObject != null) {
System.out.println(this.myObject.getName());
}
}
I already had a problem like this and I changed my selected value from object to id. But here I want to make it work with objects because I know it's possible.
Thanks
I have the solution. I had to override the "equals" method in MyObject class!
Thanks.
EDIT: the code
#Override
public boolean equals(Object obj) {
if(this.id == ((MyObject) obj).id) {
return true;
}else {
return false;
}
}
i'm facing a problem with a Converter. In my xhtml file, i have a selectOneMenu with a list of object and i want to set an object in my managedBean.
If my managedBean has #SessionScoped, the object in the managedbean is filled but if the managedeban has #ViewScoped, the converter is never use and my object is null.
how to fix this problem ?
Xhtml :
<p:selectOneMenu value="#{rechercheBean.role}" converter="#{typConverter}">
<f:selectItems id="item" value="#{typBean.roles}" var="r" itemLabel="#{r.valeur}" itemValue="#{r}" />
</p:selectOneMenu>
typConverter :
public class TypConverter implements Converter{
#EJB
private TypFacadeLocal TypBean;
public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
if (submittedValue.trim().equals("")) {
return null;
}
else {
try {
Integer id = Integer.parseInt(submittedValue);
Typ typ = new Typ();
typ = TypBean.find(id);
return typ;
}
catch (NumberFormatException exception) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Typ non valide"));
}
}
}
public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
if (value == null || value.equals("")) {
return "";
}
else {
return String.valueOf(((Typ) value).getId());
}
}
}
Tx a lot
The problem is the component c:when. With the attribut renderer of the component , there is no problem.