Search code examples
javaxpages

xp:checkbox value differs in read and edit mode


on my xpage I have placed a checkbox:

<xp:checkBox id="cbOther" value="#{customerBean.customer.other}" disabled="#{!customerBean.customer.editable}" checkedValue="1" uncheckedValue="0">

In my back-end code I try to set the value for the checkbox based upon the value of another field:

 if(doc.hasItem("fldOtherVal")){
                    if(doc.getItemValueString("fldOtherVal").equals("")){
                        System.out.println("no relations");
                        customer.setOther("0");
                    }else{
                        System.out.println("relations");
                        customer.setOther("1");
                        customer.setOtherVal(doc.getItemValueString("fldOtherVal"));    
                    }                           
                }else{
                    customer.setOther("0");
                }

This works fine when I open the customer object in my xpage in read mode. but when I set the customer object to edit mode the value in the checkbox is set to the default value of 0.

Can someone explain me what I am doing incorrect?


Solution

  • I see inconsistency with your document/bean. Chceckbox binds to "other" value, but sometimes refers to "otherVal" field/property.

    In case your saved doc contains value "0" in "fldOtherVal" field, your code falls to

                System.out.println("relations");
                customer.setOther("1");
                customer.setOtherVal(doc.getItemValueString("fldOtherVal"));   
    

    branch in. In read mode it shows "1", but writes "0" to otherVal again.

    That was my comment about:

    if(doc.getItemValueString("fldOtherVal").equals("")){
    

    does not check for "0" value.

    Edit:

    Get back to aliased values of checkbox ("0" and "1").

    Update your script to this

     // no hasItem check needed
     var other = doc.getItemValue("fldOtherVal"); // must not be multivalue
     if ("".equals(other) || "0".equals(other)) {
          System.out.println("no relations");
          customer.setOther("0");
          customer.setOtherVal("0"); // update "otherVal" also
     } else {
          System.out.println("relations");
          customer.setOther("1");
          customer.setOtherVal("1"); // do not copy value, just set to "1"
     }