2

I´m having a problem with my picklist I thing it´s because I don´t have a converter, when I try to view the items that I choose clicking in the commandbutton, I get the following exception:

java.lang.ClassCastException: java.lang.String cannot be cast to model.Employee

Here´s the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>PickList Test</title>
</h:head>
<h:body>
    <h:form id="form">
             <p:pickList value="#{pickListBean.employeeList}" var="employee" itemLabel="#  {employee.employeeName}" converter="pickListConverter" itemValue="#{employee.employeeCode}" />  
             <p:commandButton value="View targets" action="#{pickListBean.viewTargets}" style="margin-    left: 12px;"/>
    </h:form>


 </h:body>
 </html>

bean

@ManagedBean
@RequestScoped
public class PickListBean {
@EJB
private BussinessList bl = new BussinessList();
private DualListModel<Employee> employeeList;
List<Employee> source = new ArrayList<Employee>();
List<Employee> target = new ArrayList<Employee>();
private Employee employee;
/**
* Creates a new instance of PickListBean
*/
public PickListBean() {


}
@PostConstruct
public void postConstruct(){
source = bl.getEmployeeList();
employeeList = new DualListModel<Employee>(source, target);
}
public void viewTargets(){
    target = employeeList.getTarget();
    for(int i = 0; i < target.size(); i++)
        System.out.println("Targets: " + target.get(i).getEmployeeName());
}
public DualListModel<Employee> getEmployeeList() {
return employeeList;
}

public void setEmployeeList(DualListModel<Employee> employeeList) {
this.employeeList = employeeList;
}
 public Employee getEmployee() {
 return employee;
 }

 public void setEmployee(Employee employee) {
this.employee= employee;
}
}

converter

@FacesConverter(value = "pickListConverter")
public class PickListConverter implements Converter {
private static Map<Object, String> entities = new WeakHashMap<Object, String>();

@Override
public String getAsString(FacesContext context, UIComponent component, Object entity) {
    synchronized (entities) {
        if (!entities.containsKey(entity)) {
            String uuid = UUID.randomUUID().toString();
            entities.put(entity, uuid);
            return uuid;
        } else {
            return entities.get(entity);
        }
    }
}

@Override
public Object getAsObject(FacesContext context, UIComponent component, String uuid) {
    for (Entry<Object, String> entry : entities.entrySet()) {
        if (entry.getValue().equals(uuid)) {
            return entry.getKey();
        }
    }
    return null;
}

}

Employee = Funcionario

  @Entity
  @Table(name = "funcionario")
 @XmlRootElement
 @NamedQueries({
@NamedQuery(name = "Funcionario.findAll", query = "SELECT f FROM Funcionario f"),
@NamedQuery(name = "Funcionario.findByCodigoFuncionario", query = "SELECT f FROM   Funcionario f WHERE f.codigoFuncionario = :codigoFuncionario"),
@NamedQuery(name = "Funcionario.findByNomeFuncionario", query = "SELECT f FROM Funcionario f WHERE f.nomeFuncionario = :nomeFuncionario"),
@NamedQuery(name = "Funcionario.findByUsernameFuncionario", query = "SELECT f FROM    Funcionario f WHERE f.usernameFuncionario = :usernameFuncionario"),
@NamedQuery(name = "Funcionario.findBySenhaFuncionario", query = "SELECT f FROM    Funcionario f WHERE f.senhaFuncionario = :senhaFuncionario")})
public class Funcionario implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "codigo_funcionario")
private Integer codigoFuncionario;
@Size(max = 45)
@Column(name = "nome_funcionario")
private String nomeFuncionario;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 300)
@Column(name = "username_funcionario")
private String usernameFuncionario;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 300)
@Column(name = "senha_funcionario")
private String senhaFuncionario;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "codigoFuncionario")
private Collection<EquipaResponsavel> equipaResponsavelCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "funcionario")
private Collection<EquipaFuncionario> equipaFuncionarioCollection;
@OneToMany(mappedBy = "codigoFuncionario")
private Collection<Ticket> ticketCollection;

public Funcionario() {
}

public Funcionario(Integer codigoFuncionario) {
    this.codigoFuncionario = codigoFuncionario;
}

public Funcionario(Integer codigoFuncionario, String usernameFuncionario, String senhaFuncionario) {
    this.codigoFuncionario = codigoFuncionario;
    this.usernameFuncionario = usernameFuncionario;
    this.senhaFuncionario = senhaFuncionario;
}

public Integer getCodigoFuncionario() {
    return codigoFuncionario;
}

public void setCodigoFuncionario(Integer codigoFuncionario) {
    this.codigoFuncionario = codigoFuncionario;
}

public String getNomeFuncionario() {
    return nomeFuncionario;
}

public void setNomeFuncionario(String nomeFuncionario) {
    this.nomeFuncionario = nomeFuncionario;
}

public String getUsernameFuncionario() {
    return usernameFuncionario;
}

public void setUsernameFuncionario(String usernameFuncionario) {
    this.usernameFuncionario = usernameFuncionario;
}

public String getSenhaFuncionario() {
    return senhaFuncionario;
}

public void setSenhaFuncionario(String senhaFuncionario) {
    this.senhaFuncionario = senhaFuncionario;
}

@XmlTransient
public Collection<EquipaResponsavel> getEquipaResponsavelCollection() {
    return equipaResponsavelCollection;
}

public void setEquipaResponsavelCollection(Collection<EquipaResponsavel> equipaResponsavelCollection) {
    this.equipaResponsavelCollection = equipaResponsavelCollection;
}

@XmlTransient
public Collection<EquipaFuncionario> getEquipaFuncionarioCollection() {
    return equipaFuncionarioCollection;
}

public void setEquipaFuncionarioCollection(Collection<EquipaFuncionario> equipaFuncionarioCollection) {
    this.equipaFuncionarioCollection = equipaFuncionarioCollection;
}

@XmlTransient
public Collection<Ticket> getTicketCollection() {
    return ticketCollection;
}

public void setTicketCollection(Collection<Ticket> ticketCollection) {
    this.ticketCollection = ticketCollection;
}

@Override
public int hashCode() {
    int hash = 0;
    hash += (codigoFuncionario != null ? codigoFuncionario.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof Funcionario)) {
        return false;
    }
    Funcionario other = (Funcionario) object;
    if ((this.codigoFuncionario == null && other.codigoFuncionario != null) || (this.codigoFuncionario != null && !this.codigoFuncionario.equals(other.codigoFuncionario))) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "modelo.Funcionario[ codigoFuncionario=" + codigoFuncionario + " ]";
}

}
Vanilson Lourenço
  • 117
  • 1
  • 2
  • 9

1 Answers1

4

For Autocomplete or picklist use this generic converter

import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.WeakHashMap;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter(value = "entityConverter")
public class EntityConverter implements Converter {

    private static Map<Object, String> entities = new WeakHashMap<Object, String>();

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object entity) {
        synchronized (entities) {
            if (!entities.containsKey(entity)) {
                String uuid = UUID.randomUUID().toString();
                entities.put(entity, uuid);
                return uuid;
            } else {
                return entities.get(entity);
            }
        }
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String uuid) {
        for (Entry<Object, String> entry : entities.entrySet()) {
            if (entry.getValue().equals(uuid)) {
                return entry.getKey();
            }
        }
        return null;
    }

}

For other select list items use the converter from Omnifaces here.

Update:

Change

     <p:pickList value="#{pickListBean.employeeList}" 
     var="employee" itemLabel="#{employee.employeeName}"
     converter="pickListConverter" 
     itemValue="#{employee.employeeCode}" />  

to

 <p:pickList value="#{pickListBean.employeeList}" 
 var="employee" itemLabel="#{employee.employeeName}"
 converter="pickListConverter" 
 itemValue="#{employee}" />  

I change itemValue to #{employee}

Try above and see if that work.

Makky
  • 17,117
  • 17
  • 63
  • 86