[SalesForce] Bind checkbox value with controller boolean variable

I have checkboxes on my vf page

<apex:inputCheckbox id="checkboxShowP" value="{!P}" onchange="show(this);"/>

In the controller class

public boolean P{get;set;}

I want to bind this checkbox value to a boolean variable. But when I display the P value of apex class it is showing up as null. Is it possible to bind variable values in this way?

Best Answer

Looks like you have not initialised the value for "P". Initialise the value in the constructor.

VF Page:

<apex:page controller="CheckboxController">
    <apex:form >
        <apex:inputCheckbox id="checkboxShowP" value="{!P}" onchange="show(this);"/>
    </apex:form>
</apex:page>

Apex Class:

public with sharing class CheckboxController {

    public Boolean P{ get; set; }

    public CheckboxController(){
        this.P = true;
    }
}

Checkbox

Do check the Apex and VF trailhead for an understanding of dynamic bindings.

Custom Controllers : https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_custom.htm