+ Start a Discussion
TuxTux 

How to access state of a checkbox field in apex?

I want to knw whether a checkbox was ticked or not.

 

Something like Object.fieldName.isChecked().

 

How do I do that?

Best Answer chosen by Admin (Salesforce Developers) 
cashworthcashworth

If you are just looking to see if the checkbox has been checked on the object itself that could look like...

 

 

In a SOQL Statement:

Opportunity o = [select Id, name, Checkbox__c from Opportunity Checkbox__c = true];

 

As an if statement or iterative loop:

if(o.Checkbox__c  = true) {

 //Do something

}

 

All Answers

RajivRajiv

you can use wrapper class. By using wrapper class, you will get to know whether a checkbox is selected or not.

Here is the example :

http://wiki.developerforce.com/page/Wrapper_Class

 

cashworthcashworth

If you are just looking to see if the checkbox has been checked on the object itself that could look like...

 

 

In a SOQL Statement:

Opportunity o = [select Id, name, Checkbox__c from Opportunity Checkbox__c = true];

 

As an if statement or iterative loop:

if(o.Checkbox__c  = true) {

 //Do something

}

 

This was selected as the best answer
TuxTux

Sorry for not updating this in time. I found out that I only need to specify the field name. I wanted to use the value as a condition.

 

So it was as follows:

 

if(Object__c.Checkbox){
    //
}else{
    //
}

 

 

Kr SatyamKr Satyam
for me this worked (using equals operator)
 if(object.Checkbox_Field__c  == true){
     //coding
}

below code was working for uncheked condition also (using assignment )
if(Object_Name.Checkbox_Field__c  = true){      
     //coding
}
Waqas MahmoodWaqas Mahmood
The reason why the following code was also working for unchecked condition is because, you are assinging true value to that field, thus making the if statement true too.
if(Object_Name.Checkbox_Field__c  = true){      

     //coding

}

As in Apex, = is used for assigning values to variables and == is used for checking Boolean conditions (True or False).
Waqas MahmoodWaqas Mahmood

Actually it is not required to check if the field is true or not. As the values returned from a checkbox field is already a Boolean Value, so simply you can just use:

If(Object_Name.Checkbox_Field__c){
   //coding (if value is true)
} else {
  // coding (if value is false)
}

Hope it helps :)