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!
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 = ”;
}
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
}
}
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.
List myList = new List();
for (Integer i = 0; i < 10; i++) {
if (i==5)
{
myList.add(i); // Doesn't get added to myList
}
}
// 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);
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
use a continue statement, not a break
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());
}
}
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!
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
“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
Awesome. Thanks, David!
it is a field update on rule criteria so why it is not possible with work flow?
thanks in advance
Hai David
Need a test class for if else condition…
Suresh.
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!
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.
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/
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;}
}
}
}
Great question – try posting this one on the forums!
https://www.sfdc99.com/forums/forum/beginning-apex/
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
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
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’;
}
}
}
}
It looks good to me! hahaha. Are you getting an error message?
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
Make sure you have it all under the same IF… ELSE IF… ELSE statement =)
if (abc) {
// hi
} else if (def) {
// <3
} else {
// wow!
}
Got that logic .Thanks it worked.
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
You sure can – nicely done!
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;
}
}
}
}
Sweet! Glad you’re enjoying the site!!
Here are my recommendations for debugging!
Your trigger logic looks sound to me so my guess is that it’s something else!
David
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…
Hahaha, no problem!
Be proud of yourself that you wrote a perfect trigger on your first try – that’s impressive!
David
Must… read… more… :D