Thursday, December 13, 2012

SelectBooleanCheckbox & boolean/Boolean.

I was just using SelectBooleanCheckbox component to store selected boolean value in a request scoped bean, as shown below:

<af:selectBooleanCheckbox id="sbc1" text="#{ethuiBundle.SEARCH}" autoSubmit="true" valueChangeListener="#{DetailsViewBean.searchValueChange}" value="#{DetailsViewBean.search}"/>

What I observed is that when I used primitive boolean type, then value change listener gets fired only when the value switches to true, or when its checked. When its unchecked, then value change listener is not called. Even the setter of the boolean attribute in the bean is not called when the checkbox is unchecked but setter is called when checkbox is checked.

    public void setSearch(boolean search) {
        this.search = search;
        System.out.println("LKAPOOR: SEARCH = " + search);
    }

    public boolean getSearch() {
        return search;
    }

    public void searchValueChange(ValueChangeEvent valueChangeEvent) {
        // Add event code here...
        System.out.println("LKAPOOR:: VALUE CHANGE EVENT, NEW VALUE = " + valueChangeEvent.getNewValue());
        System.out.println("LKAPOOR:: VALUE CHANGE EVENT, OLD VALUE = " + valueChangeEvent.getOldValue());
    }


When I googled for this, found the following forum post:
https://forums.oracle.com/forums/thread.jspa?threadID=944994

After reading this, modified the above code as below:

    public void setSearch(Boolean search) {
        this.search = search;
        System.out.println("LKAPOOR: SEARCH = " + search);
    }

    public Boolean getSearch() {
        return search;
    }

    public void searchValueChange(ValueChangeEvent valueChangeEvent) {
        // Add event code here...
        System.out.println("LKAPOOR:: VALUE CHANGE EVENT, NEW VALUE = " + valueChangeEvent.getNewValue());
        System.out.println("LKAPOOR:: VALUE CHANGE EVENT, OLD VALUE = " + valueChangeEvent.getOldValue());
    }


By using Boolean type instead of primitive boolean type, value change listener and setter is getting called for each event (checked and unchecked). I was not aware of this so thought of documenting and sharing this.

2 comments:

  1. Thanks for your help;
    It was very usefull;

    ReplyDelete
  2. Hi, It is really helpful.
    Can you guide how can we get the row where valueChangeEvent.getNewValue() = "true"
    ?

    ReplyDelete