Search code examples
jsflabelselectmanycheckbox

How to get label of selected item in managed bean


I need your help in getting the values of a list into two variables. My list is having descriptions and codes. However, I need to place the descriptions in a variable and the codes in a different variable, so how can I achieve this.

My Code is

private String[] selectedCertificates;
private List<SelectItem> Certificates;

    public List<SelectItem> getCertificatesList(){
    Certificates = new ArrayList<SelectItem>();
    Certificates.add(new SelectItem("Certificate A","A"));
    Certificates.add(new SelectItem("Certificate B","B"));
    return bankCertificates;

}

public void setCertificates(List<SelectItem> Certificates) {
    this.Certificates = Certificates;
}
// Setters and Getters

Select Item Code:

                         <p:selectManyCheckbox id="Certificates" value="#{user.selectedCertificates}"
                                              layout="pageDirection" disabled="#{user.secondToggle}">
                            <f:selectItems value="#{user.Certificates}" var="bankCertificates"
                                           itemLabel="#{user.CertificatesString}" itemValue="#{user.CertificatesCode}"/>
                        </p:selectManyCheckbox>

where can I define that the description should be the first value and the code should be the second value in the list and I can use them in the page.

Thanks


Solution

  • Try

    class SelectItem {
        private String code;
        private String description;
    
        SelectItem (String code, String description) {
            this.code = code;
            this.description = description;
        }
    
        public String getCode () {
            return code;
        }
        public String getDescription () {
            return description;
        }
    }
    

    Here is your main class

    class MainClass {
        public static void main (String...arg) {
            //construct your list here using SelectItem class objects
            List<SelectItem> certificates =  = new ArrayList<SelectItem>();
            certificates.add(new SelectItem("Certificate A","A"));
            certificates.add(new SelectItem("Certificate B","B"));
    
            //now first read the SelectItem objects you have added to the list
            //or you can also iterate through the list, modify accordingly
            SelectItem si1 = certificates.get(0);
            //to read the code and description use the getters defined in SelectItem
            si1.getCode(); si1.getDescription();
        }
    }
    

    You can also choose to create a method to which you can pass the index which you wish to read from the list. Hope, this helps.