Salesforce coding lessons for the 99%
Finally, Apex tutorials for point-and-click admins! Written by a self-taught Google engineer.
  • Beginner Tutorials
    • Apex
    • Certifications
    • Career Info
    • Technical Architect
    • Visualforce
    • Videos
  • Apex Academy
  • Success Stories
  • About Me
  • Misc
    • Mailbag
    • Challenges
    • Links
    • Login to my Org
Follow @dvdkliuor SUBSCRIBE!

IF statements

October 12, 2013

Preface – This post is part of the Core Apex Tools series.

IF statements in Apex are like IF statements in formula fields, but much better!

Now that you know how to do comparison operators, this will be a piece of cake.

When I first started coding, the company’s best engineer told me that most code written in large companies is simply a bunch of IF statements. He said as long as I understood these, I’d have a job. Looking back, he was pretty much right! The rest will be covered in Sfdc99 of course!

Here’s your standard IF statement template:

if (insert comparison operator) {
// Code that runs if the above is true!
} else if (another comparison operator) {
// Code that runs if only the above line is true!
} else {
// Code that runs if everything is false!
}

Pretty easy, right? Now let’s do an IF statement with real comparison operators. Notice how we can use as many “else if” statements as we like!

if (myWallet.Cash__c > 20) {
david.Status__c = 'Shopping at Whole Foods, baby!';
} else if (myWallet.Cash__c > 10) {
david.Status__c = 'Perhaps Safeway instead';
} else if (myWallet.Cash__c > 5) {
david.Status__c = 'Where is the nearest Dollar Store..';
} else {
david.Status__c = 'I should call mom';
}


Next post: Creating, updating, and deleting records!

33 Comments
Carly Probasco
February 13, 2020 @ 1:45 pm

I am trying to return either a string or a date field using the following apex, but i’m getting an error ‘illegal assignment from date to string’.

//Returns the Rating Release date or the ‘rating pending’
IF (Today currentQRpCase.Rating_Externally_Visible_Date__c){
RatingRelease = currentQRpCase.Rating_Externally_Visible_Date__c;
} else {
RatingRelease = ”;
}

Reply
Dale Weaver
March 16, 2018 @ 6:23 am

Why can’t I add to a List from inside an if statement?

List myList = new List();
for (Integer i = 0; i < 10; i++) {
if (i==5) {
myList.add('5'); // Doesn't get added to myList
}
}

Reply
    Dale Weaver
    March 16, 2018 @ 6:29 am

    Ok weird. It does actually get added to the list if I use System.debug(myList). But when I’m viewing myList in the debugger while stepping through the code, there is no value.

    Reply
    payal
    September 6, 2018 @ 2:39 am

    List myList = new List();
    for (Integer i = 0; i < 10; i++) {
    if (i==5)
    {
    myList.add(i); // Doesn't get added to myList
    }
    }

    Reply
      GregWax
      April 6, 2021 @ 11:50 am

      // create a list of type Integer

      List myList = new List();

      for (Integer i = 0; i < 10; i++) {
      if (i==5)
      {
      myList.add(i); // Doesn't get added to myList
      }
      }
      system.debug(myList);

      Reply
Anonymous
March 17, 2015 @ 3:16 am

Hi….i hav a for loop in which i have 3 ifs. if first if is executed i want to exit to my second iteration. i mean i want to get exit from that if statement and next iteration of my for loop should execute. Please guide. i Tried with break but that is exiting for loop,i just want to exit from if

Reply
    Anonymous
    July 8, 2015 @ 12:43 pm

    use a continue statement, not a break

    Reply
Chad Moutes
January 22, 2015 @ 10:33 am

Hey David,

I’m very new to Apex Triggers, but i have been coding HTML for years. So i decided I should try and learn some Java and some Apex. I wrote this trigger listed below, which counts the number of “Products” that are associated with an “Account” in Salesforce. What i would like to do is add an If statement to it that makes it so it only counts the “Projects” that have the check box field “Active Project” checked. Can you help me?

trigger RollupProjectCountToAccountTrigger on Project__c (after insert, after delete, after undelete) {

List AccountIds = new List();

If(Trigger.isInsert || Trigger.isUndelete) {
for(Project__c p: Trigger.new) {
AccountIds.add(p.Company_Name__c);
}
}

If(Trigger.isDelete){
for(Project__c p: Trigger.old) {
AccountIds.add(p.Company_Name__c);
}
}

AggregateResult[] groupedResults = [SELECT count(id)projectCount, Company_Name__c FROM Project__c WHERE Company_Name__c in :AccountIds GROUP BY Company_Name__C];

Map accountMap = new Map([SELECT Id, Total_Projects__c FROM Account WHERE Id in :AccountIds]);

for(AggregateResult ar: groupedResults) {
accountMap.get((Id)ar.get(‘Company_Name__c’)).Total_Projects__c = (decimal) ar.get(‘projectcount’);
}

try {
update accountMap.values();
} catch(DmlException e) {
System.debug(e.getMessage());
}

}

Reply
    David Liu
    January 22, 2015 @ 7:13 pm

    Welcome =)

    No need for the second SOQL query – you don’t need a field queried if you’re updating (and not reading) the value.

    Also you can have another WHERE clause that filters out inactive projects.

    Good luck!

    Reply
Chris
January 21, 2015 @ 6:55 pm

Hi David- Thanks so much for doing this site. I’m learning a ton and it’s done very well! I’m trying to write a trigger that will update the Activity_Type__c custom field to the picklist value of Email on Tasks when the task Subject starts with “Email:” (don’t ask why…long story!). This isn’t possible via a workflow so I’m trying to use a trigger with an IF statement that is generating the following error: Error: Compile Error: unexpected token: ‘LIKE’ at line 3 column 25

Any ideas?

trigger emailTask on Task (before insert) {
for (Task allTasks : Trigger.new) {
if (allTasks.Subject LIKE ‘Email:%’) {
allTasks.Activity_Type__c = ‘Email’;
}
}
}

Thanks again for all of your work.
Chris

Reply
    David Liu
    January 21, 2015 @ 7:07 pm

    “This isn’t possible via a workflow”

    Smart man for checking first =)

    Anyway, you probably want to use the “startsWith” method here!
    https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_string.htm#apex_System_String_startsWith

    Reply
      Chris
      January 26, 2015 @ 12:00 pm

      Awesome. Thanks, David!

      Reply
      radha
      February 15, 2015 @ 7:41 pm

      it is a field update on rule criteria so why it is not possible with work flow?
      thanks in advance

      Reply
Suresh Kumar Vempally
November 10, 2014 @ 1:55 am

Hai David

Need a test class for if else condition…

Suresh.

Reply
    David Liu
    November 10, 2014 @ 7:54 pm

    If/else is one of the reasons you only need 75% code coverage. If 100% was required you’d have to test literally every single possible if/else condition in all your code, and that’s a pain!

    Basically, create enough varying records such that most if/else statements are run as a result =) The more the better, but 75% total is only necessary!

    Reply
Diana
September 22, 2014 @ 1:53 pm

How would I write an apex trigger to display an error message for an Opportunity when the user attempts to change the stage to “Closed,” but still has open activities (Status Completed) and prevent the user from saving the record.

Reply
    David Liu
    September 25, 2014 @ 7:26 pm

    Use addError like it’s used here =)
    https://www.sfdc99.com/2013/10/19/example-how-to-write-a-deduping-trigger-for-leads-and-contacts/

    Reply
Salaad Nur
September 8, 2014 @ 12:06 pm

Hi David,
I have wrote the below and it doesn’t work. I am trying to do an if statement that doesn’t only look at values on opportunity, but also value on the related account. Please let me know what I am doing wrong. If I take off the if statement for account type, it works.

trigger UpdateAccount on Opportunity (after insert,after update)
{
for (Opportunity OppChange: Trigger.new){
if (OppChange.StageName==’Prospecting’){
if(OppChange.Account.Type==’Prospect’){
Account currentAcc = new Account();
currentAcc.Id=OppChange.AccountId;
currentAcc.Ownership=’Public’;

update currentAcc;}
}
}
}

Reply
    David Liu
    September 8, 2014 @ 8:46 pm

    Great question – try posting this one on the forums!
    https://www.sfdc99.com/forums/forum/beginning-apex/

    Reply
    Reshmi
    December 2, 2014 @ 9:35 pm

    Hi
    I am Reshmi , just new to Salesforce. Done my 401 Exam. Was preparing for the Apex. while Searching in google i got your Site. I Should Say, That was one of my luckiest moment . having a great Teacher is much pleasure. I donno how to describe that :) Thanks David For this site.

    I just tried the above code. In this code, the incorrect single codes are used. Instead of ’Prospecting’ use ‘Prospecting’. and the same with Prospect also.
    trigger UpdateAccount on Opportunity (after insert,after update)
    {
    for (Opportunity Opp: Trigger.new){
    if (Opp.StageName == ‘Prospecting’)
    {
    if(Opp.Account.Type== ‘Prospect’)
    {
    Account currentAcc = new Account();
    currentAcc.Id=Opp.AccountId;
    currentAcc.Ownership = ‘Public’;
    update currentAcc;}
    }
    }
    }
    Let me know , if i am wrong.
    Thanks
    Reshmi

    Reply
      David Liu
      December 4, 2014 @ 9:50 pm

      Close!

      I think the thing is that Opp.Account.Type isn’t available in the trigger unless you query it using SOQL. This is because technically that field isn’t on the Opp record!

      To fix this, you can simply create a formula field on the Opp for that data, OR the better solution is to query it using SOQL.

      Hope this helps!
      David

      Reply
Anonymous
June 28, 2014 @ 2:47 am

Hi David,

Please correct me what mistake i did in below trigger

trigger updateRating on Account (before insert, before update) {

for(Account acc:Trigger.new){
if(acc.Industry!=null){
if(acc.Industry==’Agriculture’){
acc.Rating=’Warm’;
}
else if(acc.Industry==’Entertainment’){

acc.Rating=’Hot’;
}

else {
acc.Rating=’cold’;
}
}

}

}

Reply
    David Liu
    June 28, 2014 @ 11:31 am

    It looks good to me! hahaha. Are you getting an error message?

    Reply
Vaishali Singh
April 29, 2014 @ 5:36 am

Hi David,
I tried to do something like this where i wanted to update the rating based on the industry type.
If my industry= agriculture then rating = Warm
If my industry= entertainment then rating = Hot
If my industry= (is anything else from the top industries) then rating = Cold

But every time it is setting the value as cold. I dont understand where i am missing on. Please help

trigger updateRating on Account (before insert,before update) {

for(Account acc:trigger.new)
{
if(acc.Industry!=null)
{
IF(acc.Industry==’Agriculture’)
{
acc.Rating=’Warm’;
}
IF(acc.Industry==’Entertainment’)
{
acc.Rating=’Hot’;
}
else
acc.Rating=’cold’;

}
else
acc.Rating=”;

}

}

Cheers
Vaishali Singh

Reply
    David Liu
    April 29, 2014 @ 8:20 pm

    Make sure you have it all under the same IF… ELSE IF… ELSE statement =)

    if (abc) {
    // hi
    } else if (def) {
    // <3
    } else {
    // wow!
    }

    Reply
      Vaishali Singh
      April 30, 2014 @ 4:49 am

      Got that logic .Thanks it worked.

      Reply
Madhu
March 12, 2014 @ 6:31 am

Hi David,

In the above trigger can we use ” else if { ” statement.

if(NewCase.Origin==’E-mail’){

if(NewCase.Description.contains(‘TYPE A’)) {
NewCase.Type=‘TYPE ‘A;
}
else if (NewCase.Description.contains(‘TYPE B)) {
NewCase.Type=’T’YPE B;
}
else {
NewCase.Type=‘TYPE’ C;

Thanks,
Madhu

Reply
    David Liu
    March 12, 2014 @ 8:05 pm

    You sure can – nicely done!

    Reply
Q
January 11, 2014 @ 10:45 am

Hi David!

You tutorials are great, I started thanks to them! Thank you!

I’m trying to write a trigger for the Case object that updates the ‘Type’ field based on a value in the ‘Description’ field. However it should fire only if the ‘Origin’ is equal to E-mail (I don’t want to override Salesforce user’s choice, I only want to trigger this APEX if it’s coming form email-to-case).

Problem is : it seems that the E-mail Origin condition is totally ignored, no matter what I choose, it sets the Type defined in the trigger. Any idea??

Thanks a lot!

============================================================

trigger TypesForEmailToCase on Case (before insert) {

for (Case NewCase : Trigger.new) {

if(NewCase.Origin==’E-mail’){

if(NewCase.Description.contains(‘TYPE A’)) {
NewCase.Type=‘TYPE ‘A;
}
if (NewCase.Description.contains(‘TYPE B)) {
NewCase.Type=’T’YPE B;
}
if (NewCase.Description.contains(‘TYPE C’)) {
NewCase.Type=‘TYPE’ C;
}
}
}
}

Reply
    David Liu
    January 11, 2014 @ 11:36 am

    Sweet! Glad you’re enjoying the site!!

    Here are my recommendations for debugging!

    • Check to see how the Type is updating when creating a case manually on Salesforce.com – with different values of Case Origin!
    • Does your Type field have a default value?
    • Are there any other Origin fields that might be confusing this?
    • Deactivate your trigger and see if the Type is still updating! (perhaps from a workflow or other trigger)

    Your trigger logic looks sound to me so my guess is that it’s something else!
    David

    Reply
      Q
      January 11, 2014 @ 3:39 pm

      Hey David you were right, it was actually a workflow updating the Type field… Doh! ;-)
      I tested it in another dev org and it works…

      Reply
        David Liu
        January 11, 2014 @ 3:51 pm

        Hahaha, no problem!

        Be proud of yourself that you wrote a perfect trigger on your first try – that’s impressive!

        David

        Reply
Chris
October 13, 2013 @ 11:52 am

Must… read… more… :D

Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *


*

*

Theme: Simple Style by Fimply