简体   繁体   中英

Primefaces how to get POJO from selectOneMenu

My question is how to get value from selection in 'selectOneMenu' component. I use POJO not String type. I try to display the name property of selected object in inputText. I use commandButton to refresh value in inputText as in code below. But the problem is that nothing appears in inputText. I'm not sure there is need to use converter but I tried and it also hasn't worked.

here is my .jsp file:

<p:selectOneMenu value="#{appointentBean.selectedSpecialization}">
    <f:selectItems value="#{appointentBean.specializationResult}" var="i" itemValue="#{i}" itemLabel="#{i.name}"/>
</p:selectOneMenu>

<p:commandButton value="Szukaj" >
    <p:ajax update="textid" />
</p:commandButton>

<p:inputText id="textid" value="#{appointentBean.selectedSpecialization.name}" />

appointmentBean:

@ManagedBean
@ViewScoped
@SessionScoped
public class appointentBean
{

private ArrayList<Specialization> specializationResult;
private Specialization selectedSpecialization;

  public ArrayList<Specialization> getSpecializationResult()
  {
    //Here retrievie objects list from database and it works

    return specializationResult;
  }

  public void setSpecializationResult(ArrayList<Specialization> result) {
    this.specializationResult = result;
  }

  public Specialization getSelectedSpecialization() {
    return selectedSpecialization;
  }

  public void setSelectedSpecialization(Specialization selectedSpecialization) {
    this.selectedSpecialization = selectedSpecialization;
  }
}

Specialization.java:

@Entity
@Table(name="Specializations")
public class Specialization
{
  @Id
  @GeneratedValue
  private int specialization_id;
  @Column(name="name")
  private String name;


  public int getSpecialization_id() {
    return specialization_id;
  }
  public void setSpecialization_id(int specialization_id) {
    this.specialization_id = specialization_id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
}

What is more. If I do not make selection on the list NullPointerExcetion appears. But when I make choice i doesn't. So the object is set after selection.

Give a name to your Managed Bean like this

1.    @ManagedBean(name ="appointentBean")
2.    It should be in Session Scoped or View Scoped not in Both

Your code works perfectly on my End. I did changes to

ArrayList<Specialization> getSpecializationResult() like this:

 public ArrayList<Specialization> getSpecializationResult()
  {
    //Here retrievie objects list from database and it works
    specializationResult = new ArrayList<Specialization>();
    Specialization specialize= new Specialization();  
    specialize.setName("Vinayak");
    specialize.setSpecialization_id(1);
    specializationResult.add(specialize);
    return specializationResult;
  }

It worked . So, make the necessary changes and let us know.

EDIT 2

Whenever we Deal with POJO's at that time we have to deal with Converter. Why Custom Converter is the question is what you want to ask now. Refer Custom Converter

These are the steps to create Custom Converter 1. Create a converter class by implementing javax.faces.convert.Converter interface. 2. Override both getAsObject() and getAsString() methods. 3. Assign an unique converter ID with @FacesConverter annotation present in javax.annotation.

  1. First of all I have created a POJOConverter class for your Specialization class

    package primefaces1; import java.util.ArrayList; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.convert.FacesConverter; @FacesConverter(forClass=Specialization.class) public class PojoConverter implements Converter{ public static List<Specialization> specilizationObject; static { specilizationObject = new ArrayList<Specialization>(); specilizationObject.add(new Specialization("Vinayak", 10)); specilizationObject.add(new Specialization("Pingale", 9)); } public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) { if (submittedValue.trim().equals("")) { return null; } else { try { for (Specialization p : specilizationObject) { if (p.getName().equals(submittedValue)) { return p; } } } catch(NumberFormatException exception) { throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Specialization")); } } return null; } public String getAsString(FacesContext facesContext, UIComponent component, Object value) { if (value == null || value.equals("")) { return ""; } else { return String.valueOf(((Specialization) value).getName()); } } }
  2. Following changes has been made to your managed Bean class. To overcome the NUll Pointer Exception

    package primefaces1; import java.util.ArrayList; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name = "appointentBean") @SessionScoped public class appointentBean { private ArrayList<Specialization> specializationResult; private Specialization selectedSpecialization ; @PostConstruct public void init() { selectedSpecialization = new Specialization(); selectedSpecialization.setName(new String()); selectedSpecialization.setSpecialization_id(0); } public appointentBean() { specializationResult= (ArrayList<Specialization>) PojoConverter.specilizationObject; } public ArrayList<Specialization> getSpecializationResult() { // Here retrievie objects list from database //and it works return specializationResult; } public void setSpecializationResult(ArrayList<Specialization> result) { this.specializationResult = result; } public Specialization getSelectedSpecialization() { if (this.selectedSpecialization != null) System.out.println("getSelectedSpecialization----" + this.selectedSpecialization.getName()); return this.selectedSpecialization; } public void setSelectedSpecialization(Specialization selectedSpecialization) { this.selectedSpecialization = selectedSpecialization; } }
  3. I have made some minute changes to your xhtml for showing values.

<h:body>

    <h:form id="me">
            <p:selectOneMenu value="#{appointentBean.selectedSpecialization}" >
                <f:selectItem itemLabel="Select One" itemValue=""></f:selectItem>
                <f:selectItems value="#{appointentBean.specializationResult}"
                    var="result" itemValue="#{result}" itemLabel="#{result.name}" />

            </p:selectOneMenu>

            <p:commandButton value="Szukaj" update="me:textid">
                </p:commandButton>
            <h:outputText value="NAME: "></h:outputText>
            <h:outputText  id="textid" value="#{appointentBean.selectedSpecialization.name}" rendered="#{not empty appointentBean.selectedSpecialization}"/>

    </h:form>

</h:body>


I find myself in the same situation that user2374573, SelectOneMenu, was populated correctly using a custom converter, but the selected item was null. The proposed solution is a variation of the custom converter, but it doesn't solve the problem (at least for me). The value selecting does not arrive as explained in the Primefaces documentation, this occurs because SelectOneMenu operates with String and not with Pojos. After studying In the end I have opted for an intermediate solution. Instead of having a variable of type pojo to store the value, I use just having a String that stores the id of the element as follows. This solution has been useful for the SelectOneMenu and also for loading the Targer in the DualList used in the Primefaces Picklist. It is not an ideal solution, but it saves the problem.

Java View

public class PickListView  implements Serializable { 
    private static final long serialVersionUID = 1L;
    private List<CviConcesione> listaConcesion;
    private CviConcesione concesionSeleccionada;    
    private String concesionSeleccionadaS;  

    @Autowired
    private ConcesionesBO concesionesBO;    

    @PostConstruct
    public void init() {
    }
     
    public List<CviConcesione> getListaConcesion() {
        if (null != listaConcesion && !listaConcesion.isEmpty()) {
            return listaConcesion;  
        } else {
            listaConcesion = new ArrayList<CviConcesione>();            
            listaConcesion = concesionesBO.consultaTodasConcesiones();
            return listaConcesion;
        }
    }

    public void setListaConcesion(List<CviConcesione> listaConcesion) {
        this.listaConcesion = listaConcesion;
    }

    public ConcesionesBO getConcesionesBO() {
        return concesionesBO;
    }

    public void setConcesionesBO(ConcesionesBO concesionesBO) {
        this.concesionesBO = concesionesBO;
    }

    public CviConcesione getConcesionSeleccionada() {
        return concesionSeleccionada;
    }

    public void setConcesionSeleccionada(CviConcesione concesionSeleccionada) {
        this.concesionSeleccionada = concesionSeleccionada;
    }

    public String getConcesionSeleccionadaS() {
        return concesionSeleccionadaS;
    }

    public void setConcesionSeleccionadaS(String concesionSeleccionadaS) {
        this.concesionSeleccionadaS = concesionSeleccionadaS;
    }
}

Html Code for select one menu

<p:selectOneMenu 
            id="concesionR" 
            value="#{pickListView.concesionSeleccionadaS}" 
            style="width:125px" 
            dynamic="true"
            converter="#{concesionConverter}">
                <f:selectItem itemLabel="Seleccione" itemValue="" />
                <f:selectItems value="#{pickListView.listaConcesion}" 
                    var="concesion" 
                    itemLabel="#{concesion.conCodigo} - #{concesion.conDescripcion}" 
                    itemValue="#{concesion.conCodigo}"
                    ajax = "true"
                 />
                <p:ajax update="lineaR" process="@form" />                           
    </p:selectOneMenu>

a Class converter

@FacesConverter("concesionConverter")
public class ConcesionesConverter implements Converter {

    public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
        if(value != null && value.trim().length() > 0) {
            try {
                PickListView service = (PickListView) fc.getExternalContext().getApplicationMap().get("pickListView");
                return service.getListaConcesion().get(Integer.parseInt(value));
            } catch(NumberFormatException e) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid theme."));
            }
        }
        else {
            return null;
        }
    }

    public String getAsString(FacesContext fc, UIComponent uic, Object object) {
        if(object != null) {
            return String.valueOf(((CviConcesione) object).getConId());
        }
        else {
            return null;
        }
    }   
}

This solution does not manage to bring the pojo, but lets you know that it has been selected, showing pojo values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM