If statement is the most basic requirement of any developer. This statement has exist in every High Level Language, as writing a code without using this condition seems next to impossible. However we do know that for languages like HTML if condition is not required, as HTML is nothing more than a markup language, yet the support is provided with the help of JavaScript to vary elements on the basis of conditions. Salesforce on the other hand, took a step forward and provided this conditional statement in Visualforce itself. We will discuss about the same today, using If condition in salesforce.


For this example I have written an APEX class to assign 5 accounts originally to a list. There is also a function which assigns all the records to that list.

public class iftest {
    public integer acclimit { get; set;}
    public integer total { get; set;}
    public list<account> acclist { get; set;}
    public iftest(){
        acclimit = 5;
        total = [select count() from account];
        acclist = [select id, name from account limit :acclimit];
    public void allacc(){
        acclist = [select id, name from account];

VisualForce Code

Before jumping onto the code itself, let’s discuss something. How to actually use the If condition? Using it is really simple and can be somewhat related to the usage of ternary operator. First of all, it must be in the formula expression. It must start with If, followed by parenthesis. The parenthesis will take 3 arguments, first the condition, in parenthesis again, second the value if true is returned, and the last argument, like you guessed, will be the value of condition is false.
The values can be any apex controller variable, or it can be strings written directly.

<apex:page controller="ifblog">
        <apex:commandButton action="{!allacc}" value="Show All Accounts" disabled="{!If((total<=acclimit),true,If((acclist.size>acclimit),true,false))}"/>
    	<apex:dataTable value="{!acclist}" var="acc">
        	<apex:column value="{!acc.id}" headerValue="Id"/>
            <apex:column value="{!acc.name}" headerValue="Name"/>

As you can see that the disabled attribute of the commandbutton is using the If condition, also the condition is nested. Now while nesting the if condition in Visualforce you need to be really careful of the parenthesis just like you need to be careful of scope normally.


The Output of my code will be something like this:


That’s all about creating a post on chatter through APEX, for any further queries feel free to contact us at:


Or let us know your views on how to make this code better, in comments section below.

Leave A Reply

Please verify that you are not a robot.

Tell us about Your Company

How can we help you with your business?

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home