Search code examples
listjsfprimefacesselectmanycheckbox

How to enable/disable item in selecManyCheckbox based on flag


I need your help in disabling and enabling an item from the selectManyCheckbox component in a jsf page. First of all, the selectManyCheckbox component is showing three chechboxes which are (Loan - Health - Transfer). The list will be populated from a bean which it has the code:

private List<hrCertificate> hrCertificatesList = new ArrayList<hrCertificate>(); 

//Getter and Setter

Private String loanFlag="";

@PostConstruct
public void init() {

    this.hrCertificatesList.add(new hrCertificate(("Loan"), "LC"));
    this.hrCertificatesList.add(new hrCertificate(("Health"), "HI"));
    this.hrCertificatesList.add(new hrCertificate(("Trasnfer"), "TE"));    
}

In the same bean, I will be running a SQL statement that will return either Yes or No and that value I am adding it to the loanFlag variable.So if the flag="Y", I need to enable the loan checkbox so the user can select it else I need to disable it from the selectManyCheckbox. The issue is that I am facing difficulties in applying the logic to disable and to enable the item selectManyCheckboxwhere in the above code I am listing and enabling them all the time.

The code for the selectManyChexkbox:

 <p:selectManyCheckbox id="hrCertificates" value="#{user.selectedHRCertificates}" layout="pageDirectio>
     <f:selectItems value="#{user.hrCertificatesList}" 
         var="hrCertificate" itemLabel="#{hrCertificate.hrCertificateName}"
         itemValue="#{hrCertificate.hrCertificateCode}"/>

 </p:selectManyCheckbox>

So how to apply the logic


Solution

  • Could you edit your hrCertificate class to add a disabled boolean field? If yes, then you can add itemDisabled="#{hrCerticate.disabled}" to your f:selectItems which should be the easiest solution.

    Another option would be to use a Map<hrCertificate, Boolean> instead of a List<hrCertificate>.

    private Map<hrCertificate, Boolean> hrCertificatesMap = new HashMap<hrCertificate, Boolean>();
    
    @PostConstruct
    public void init() {
         hrCertificatesMap.put(new hrCertificate(("Loan"), "LC"), null);
         hrCertificatesMap.put(new hrCertificate(("Health"), "HI"), null);
         hrCertificatesMap.put(new hrCertificate(("Trasnfer"), "TE"), null);
     }
    
     // Then when you're done with your SQL query, update your Map to add the corresponding boolean values...
    

    .xhtml

    <p:selectManyCheckbox id="hrCertificates" value="#{user.selectedHRCertificates}" layout="pageDirectio>
        <f:selectItems value="#{user.hrCertificatesMap.keySet().toArray()}" var="hrCertificate" itemLabel="#{hrCertificate.hrCertificateName}" itemValue="#{hrCertificate.hrCertificateCode}" itemDisabled="#{user.hrCertificatesMap.get(hrCertificate)}" />
    </p:selectManyCheckbox>