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!

Code from #Apex4Admins Webinar 2!

May 22, 2014

Basic

[SELECT Id, Name, Website, Sells_Chocolate__c FROM Account];

Cross-object

[SELECT Account.Owner.Manager.Needs_Chocolate__c FROM Contact];

WHERE

[SELECT Id, Name FROM Contact WHERE Eats_Chocolate__c = true];

Operators

[SELECT Id, Title FROM Lead WHERE Favorite_Chocolate__c != null];

AND

[SELECT Id, Name, Email, Birthdate, Account.Name FROM Contact 
  WHERE Eats_Chocolate__c   = true
AND Allergic_to_Nuts__c = false AND Chocolate_Rehab__c = false];

Mixing ANDs & ORs

[SELECT Id, Name, Email, Birthdate, Account.Name FROM Contact 
  WHERE Eats_Chocolate__c  = true
AND (Milk_Chocolate__c = true OR Dark_Chocolate__c = true)];

Text, Picklist, IDs

[SELECT Id, Name, Email, Birthdate, Account.Name FROM Contact 
  WHERE Eats_Chocolate__c     = true
AND Favorite_Chocolate__c = 'Snickers' AND OwnerId = '005i0000000OAOO'];

Numbers

[SELECT Id, Name, Email, Birthdate, Account.Name FROM Contact 
  WHERE Eats_Chocolate__c          = true
AND Chocolate_Bars_Consumed__c > 10 OR Broccoli_Consumed__c <= 1];

Dates

[SELECT Id, Name, Email, Birthdate, Account.Name FROM Contact 
  WHERE Eats_Chocolate__c  = true    
    AND Diet_Start_Date__c = null
OR Diet_Start_Date__c > TODAY];

Fuzzy Matching

[SELECT Id, Name, Email, Birthdate, Account.Name FROM Contact 
  WHERE Eats_Chocolate__c   = true
AND Preferred_Fillings__c LIKE '%Caramel%'];

Sorting

[SELECT Id, Name, Email, Birthdate, Account.Name FROM Contact 
  WHERE Eats_Chocolate__c = true    
    AND Last_Chocolate_Consumption__c < 2014-01-01
ORDER BY LastName ASC];

Limiting Results

[SELECT Id, Name, Email, Birthdate, Account.Name FROM Contact 
  WHERE Eats_Chocolate__c = true    
    AND Last_Chocolate_Consumption__c = YESTERDAY
LIMIT 10];

Apex FUNdamentals

Variables

// Text
String favoriteMovie = 'Frozen';

// Numbers
Integer timesWatched     = 8;
Decimal merchandiseSpend = 55.20;

// True or False
Boolean ownsTheSoundtrack = true;

// Dates
Date dateLastWatched  = Date.newInstance(2014, 5, 20);
DateTime nextShowtime = DateTime.now().addHours(7);

// SObjects
Movie__c frozen = [SELECT Id FROM Movie__c WHERE Name = 'Frozen'];

IF Statements and Comparison Operators

// How to compare values
Greater than:  >      Less than:     <
Equals:        ==     Not Equals:    !=
AND:           &&     OR:            ||

// IF Statements
if (david.Twtr_Follows__c < leeAnne.Twtr_Follows__c) {
david.Emotions__c = 'Crushed.';
} else if (david.Twtr_Follows__c == leeAnne.Twtr_Follows__c) {
david.Emotions__c = 'Showdown! Last man standing!';
} else if (david.Twtr_Follows__c < 1200 || david.Tweets__c < 500){
david.Emotions__c = 'A petty victory.';
} else {
david.Emotions__c = 'Life is good.'; }

Loops

// FOR EACH Loop: Eat every Reeses in our trigger!
for (Chocolate__c choco : Trigger.new) {
if (choco.Name == 'Reeses') { choco.Status__c = 'In my belly!'; update choco; } } // FOR Loop: Eat 100 Reeses!
for (Integer i = 0; i < 100; i++) {
Chocolate__c choco = new Chocolate__c(); choco.Name = 'Reeses'; choco.Status__c = 'In my belly!'; insert choco; }
// Eat 10 Reeses every time you watch Frozen!
trigger Snacks on Movie__c (after insert) {
    // Loop through all records in the trigger
for (Movie__c movie : Trigger.new) {
if (movie.Name == 'Frozen') { // Loop a specific number of times
for (Integer i = 0; i < 10; i++) {
Chocolate__c choco = new Chocolate__c(); choco.Name = 'Reeses'; choco.Status__c = 'In my belly!'; insert choco; } } } }

Final “Non-Profit” Trigger:

trigger AutoCreateOpp on Account (after insert) {
    // Every trigger has this loop!
for (Account a : Trigger.new) {
// Check if it's a 'Prospect' Account
if (a.Type == 'Prospect') {
// Create a new Opp (but don't save yet) Opportunity o = new Opportunity(); o.Name = 'Big Deal'; o.StageName = 'Prospecting'; o.CloseDate = Date.today().addDays(30); o.AccountId = a.Id; // Set the Opp amount based on the Industry
if (a.Industry == 'Technology') {
o.Amount = 5000000;
} else if (a.Industry == 'Non-Profit') {
o.Amount = 1000;
} else {
o.Amount = 5000; } // Double the Opp amount if there are many employees!
Integer bigCompanyMultiplier = 2; if (a.NumberOfEmployees > 1000) { o.Amount = o.Amount * bigCompanyMultiplier; }
// Don't forget to save! insert o; } } }

Try writing a test class for this trigger! Paste your class in the comments and I’ll tell you how you did!

Thanks to everyone who joined today – it was AWESOME!!!

19 Comments
Pam Melnick
May 28, 2014 @ 8:20 am

When is the recording going to be available for the second webinar, Beyond the Basics? The presentation is there but not the recording…on the SF Developer site.

Reply
    David Liu
    May 28, 2014 @ 6:39 pm

    Looks like it’s gonna be tomorrow – I’ll post an update the site the moment I find out!

    Reply
Pin
May 27, 2014 @ 7:27 pm

Got a quick question about this example:

Movie__c frozen = [SELECT Id FROM Movie__c WHERE Name = ‘Frozen’];

This is a variable to store the Movie__c object, why is the assignment to store the SFDC ID to the variable?

Reply
    David Liu
    May 27, 2014 @ 7:39 pm

    Great question!

    The result is always of the Movie__c type no matter which fields are queried. The fields listed simply specifies which fields are available on each Movie__c record.

    Hope this helps!
    David

    Reply
lakshminarayana
May 27, 2014 @ 3:13 am

Hi David,
i have a question on writing test class for nested if conditions like if(conditon){

if(condition){
//do something..
}else if(some condtion){

//do something

}else{
//do somthing..
}

}else{

//do something
}

that is my problem,.can you please explain how to write test class for nested if condtons..

Reply
    David Liu
    May 27, 2014 @ 12:55 pm

    One record or update for each condition!

    Reply
      lakshminarayana
      May 28, 2014 @ 11:26 pm

      Thanks David for your quick reply.
      if you don’t mind can you please explain with small example.so that it will be very clear to me.

      Reply
        David Liu
        May 29, 2014 @ 5:10 pm

        You usually use a different record for each if condition =)

        So if you have…
        if (#1) {

        } else if (#2) {

        } else if (#3) {

        } else {

        }

        You can have one record that’ll go through the first IF, another record that goes through the second, and so on and so forth =)

        Remember that you only need 75% coverage though – so you actually don’t need to test every single IF clause you have!

        David

        Reply
    David Liu
    May 27, 2014 @ 1:42 pm

    Also don’t forget that you only need 75% code coverage, so there’s no need to cover every possible IF condition. Just the ones with the most lines of code will usually do!

    Reply
Seshu
May 23, 2014 @ 11:38 pm

Hi, Please find the testclass for the above trigger.

static testMethod void accountCreator() {
Account acc = new Account();
acc.Name = ‘Tesla Motors’;
acc.Type=”Prospect”;
acc.Industry == “Technology”;
acc.NumberOfEmployees=999;
insert acc;

Account acc2 = new Account();
acc2.Name = ‘Tata Motors’;
acc2.Type=”Prospect”;
acc2.Industry == ‘Non-Profit’;
acc2.NumberOfEmployees=1001;
insert acc2;

Opportunity opp = new Opportunity();
opp.AccountId=acc.Id;
insert opp;

}

Reply
    David Liu
    May 24, 2014 @ 12:37 am

    Great job Seshu – looks awesome!!! That was fast!

    David

    Reply
Balaji S
May 22, 2014 @ 9:18 pm

David, your sessions are awesome !!! Keep it up.

Reply
    David Liu
    May 22, 2014 @ 10:12 pm

    Thank you =) We all work very hard to put them out!!

    Reply
Laci
May 22, 2014 @ 5:00 pm

Thanks David, I have a question about the looping examples. Would you actually do the inserts and updates individually as shown in the example code or would you add them to a list where the inserts and updates currently are and then do a single insert/update of the list after the loop has finished?

Reply
    David Liu
    May 22, 2014 @ 5:12 pm

    Great question!

    I would definitely do them outside the loop! But we won’t cover that until Chapter 5 =)

    My philosophy for beginners learning is that it’s better to quickly get some code written, even if it’s not 100% optimized! Otherwise the learning curve is a bit too intimidating for newbies =)

    David

    Reply
Anonymous
May 22, 2014 @ 3:08 pm

David–I’m working my way through the 5 step program. It’s gonna be great! I started playing with the workbench today as SQL is background. I’m having a problem understanding how to link multiple objects together. Specifically, I would like to go from contacts to the attachments. I would have thought that was a direct link, but I’m not getting it. Could you put some explanation behind the cross-object query you have shown us?

Thanks
Bob

Reply
    David Liu
    May 22, 2014 @ 5:14 pm

    Great question Bob!

    In SOQL you can’t explicitly do a JOIN as you would in SQL. You can only traverse upwards or downwards:
    https://www.sfdc99.com/2013/06/09/example-how-to-write-a-cross-object-soql-query/
    https://www.sfdc99.com/2013/06/24/example-how-to-write-a-cross-object-soql-query-part-2/

    For Contacts –> Attachments you’ll want the downwards query!

    David

    Reply
      Bob Lloyd
      May 23, 2014 @ 6:53 am

      Bueno! I actually said “AHAH” out loud when I looked at the post you provided.

      Thanks!

      Reply
Virginia
May 22, 2014 @ 9:57 am

Nice!

Reply

Leave a Reply Cancel reply

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


*

*

Theme: Simple Style by Fimply