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!

How to Read Code

May 16, 2013

The key is in the colors! I painted the code to help simplify your learning!

Pay close attention to these:

  • Green highlighted lines means it’s important! The deeper the green, the more useful the code. Skim the code without any highlights, that’s just boilerplate code.
  • Blue colored text are Salesforce reserved variables or sObjects. They have useful functionality that I will teach you to master!
  • Purple colored text are variables that we define. We can name them anything we want!

Subconsciously pay attention to these:

  • // Comments begin with a doubleslash, and they’re frequently used in code to help explain what you’re doing. Salesforce will ignore these lines when executing Apex.
  • ‘Strings’, also known as “text”, are wrapped in single quotes. Strings need to be differentiated from numbers, for example, because ‘3’ + ‘3’ = ’33’ and 3 + 3 = 6.
51 Comments
swetha
May 2, 2016 @ 6:40 am

David ,

you are an inspiration !..i wonder how much passion you have to write and explain everything in detail …even beginners like me could understand …thank you so much! you are website is the best sales force website….hope one day i can write code as you wrote !

Swetha

Reply
    David Liu
    May 2, 2016 @ 9:08 pm

    Thank you Swetha and good luck!

    Reply
su
February 1, 2016 @ 9:03 pm

I know I’m posting this a little late, but your website is the best I’ve come across! you da man David

Reply
    David Liu
    February 1, 2016 @ 9:06 pm

    Thanks Su!

    Reply
Anonymous
August 13, 2014 @ 10:35 am

smcnasdnmfsdnf

Reply
    David Liu
    August 13, 2014 @ 10:40 am

    I’m gonna approve this comment since I’m pretty sure you’re not a robot, just a funny person who felt like typing jibberish =)

    Reply
      Anonymous
      August 27, 2014 @ 6:33 am

      We all get that urge to type jibberish sometimes!

      Reply
sanjeev
July 25, 2014 @ 10:55 am

hii david,

i have an issue whenever i save my records then show this message please help me out.

Data Storage Limits Exceeded
Your company currently has exceeded its data storage limits including an extra overflow buffer. Per our terms and conditions, we cannot permit additional data creation within our system until your company first reduces its current data storage. Please contact your company’s salesforce.com administrator to resolve this. We apologize for any inconvenience this may cause.

Reply
    sanjeev
    July 27, 2014 @ 6:30 pm

    I am facing some problems while saving records in my developer enviroment.
    I have even cleared my Accounts, Contacts, Opps and Cases, but still I am unable to save records.

    Hope to get a solution from you.
    Waiting for a quick responce.

    Thanks…… :)
    Sanjeev

    Reply
      David Liu
      July 27, 2014 @ 9:30 pm

      Answer: Start a new dev org, ha ha ha. It’s free, why not!

      Reply
    David Liu
    July 27, 2014 @ 9:42 pm

    Setup >> Company Profile >> Company Information >> Used Data Space

    Mass delete records using Workbench:
    https://www.sfdc99.com/2013/06/08/where-to-write-soql-queries/

    If lazy, simply create a new dev org =)

    Reply
Karthick
July 10, 2014 @ 4:14 am

hey david,
can you give me the video tutorial for visualforce
Thanks in advance

Reply
    David Liu
    July 10, 2014 @ 10:39 pm

    I went with the standard Salesforce documentation to learn this!

    Reply
Chaithu
June 28, 2014 @ 1:20 pm

Just Found the Site ….About me Video gets confidence levels to me :) you r very energeticand talented man.Keep Helping..and motivate others :) Good Work Thanks :)

Reply
    David Liu
    June 28, 2014 @ 1:33 pm

    Thank you!!! So happy I could motivate you!!!

    Reply
Farheen
June 24, 2014 @ 9:10 pm

Hi David,
Is there any possibility to get the record type from an Sobject that a profile can create record.I dont want all the record types in the Sobject, only the record type that Profile can great.

Waiting for your reply.

Thanks
farheen

Reply
    David Liu
    June 24, 2014 @ 9:40 pm

    Just like this =)
    http://www.mindfiresolutions.com/Record-Types-In-Apex-According-To-The-Current-Users-Profile-Availability-2463.php

    Reply
Sathish
June 18, 2014 @ 8:01 am

Nice Post!!!

Reply
Catherine Johnson
May 16, 2014 @ 4:29 am

Hi David,
How do I get a trigger to fire on a date? For example, we have effective date and separation date. I would like the trigger to execute 2 days before the effective date. Currently, the “active” check box is fired when a separation date is entered but the effective date could be 30 days later. I want the “active” check box to stay checked until 2 days before the effective date is true.
Thanks

Reply
Daniel Mason
May 8, 2014 @ 7:59 am

David,
Is it possible if you can help me create an approval process on the campaign object?
Approval process would need to fire, when a custom button is selected. Let’s say custom button is called “D Mason”

Looking forward to your help

Reply
    David Liu
    May 8, 2014 @ 9:55 pm

    Check out these posts to do this!

    How to call Apex from a button:
    http://salesforcesource.blogspot.com/2009/06/triggering-apex-method-with-custom.html

    How to trigger an approval process using Apex (ignore that it’s in a trigger!):
    http://blog.jeffdouglas.com/2010/01/04/automating-salesforce-approval-processes-with-apex-triggers/

    Reply
      Daniel Mason
      May 9, 2014 @ 3:55 am

      Hi David, thanks for the response. Can you enable approval processes in your org so i can test this functionality ?

      Reply
        David Liu
        May 10, 2014 @ 11:23 pm

        I have to restrict some of the config permissions on the user otherwise the org would be broken sorry hahaha.

        I definitely recommend creating your own dev org as seen here!
        https://www.sfdc99.com/2013/05/13/where-to-write-code-in-salesforce/

        Reply
Daniel Mason
April 22, 2014 @ 8:25 am

Hi David Liu

I have the following Apex Class ( See below), However i have Zero 0% coverage. unfortunately i know longer have the test class. iIs there any possibility, you can get this class working for me ?

Looking forward to your response

Daniel

global class DeactivateUsers implements Schedulable
{
global void execute(SchedulableContext ctx)
{
// to run the job only in production. Amended by Daniel Mason on 22/04/2014
if (UserInfo.getOrganizationId() == ’00DR0000001tVYy’)

{
system.debug(‘*****orgid*****’+UserInfo.getOrganizationId());
Date myDate = Date.Today();
String sDate = String.valueOf(myDate);

List updUsers = new List();
String Usr = ”;
String[] AdminEmail = new String[]{};
AdminEmail.add(‘daniel.Mason@hotmail.com’);
AdminEmail.add(‘daniel.Mason@hotmail.com’);
AdminEmail.add(‘daniel.Mason@hotmail.com’);

String[] DeveloperEmail = new String[]{};
DeveloperEmail.add(‘daniel.Mason@hotmail.com’);

String eMailSub = ”;
String eMailbdy = ”;

List UserList = new List();

if(Test.isRunningTest())
{
// To increase the code coverage during running the test class
UserList = [
SELECT Id, Name,isactive,lastlogindate,createddate,Inactive_Date__c
FROM User
WHERE
isactive = False and Inactive_Date__c= null
LIMIT 2];
}
else
{

/*UserList = [
SELECT Id, Name,isactive,lastlogindate,createddate,Inactive_Date__c
FROM User
WHERE isactive = True
AND Management_User__c = False
AND
//((lastlogindate != null and lastlogindate < LAST_90_DAYS) OR (lastlogindate = null and CreatedDate < LAST_90_DAYS))
(
(lastlogindate != null and lastlogindate < LAST_90_DAYS and Inactive_Date__c= null)
OR (lastlogindate != null and lastlogindate < LAST_90_DAYS and Inactive_Date__c != null and Inactive_Date__c< LAST_N_DAYS:5)
OR (lastlogindate = null and CreatedDate < LAST_90_DAYS and Inactive_Date__c= null)
OR (lastlogindate = null and CreatedDate < LAST_90_DAYS and Inactive_Date__c != null and Inactive_Date__c < LAST_N_DAYS:5)
)
LIMIT 100];*/

UserList = [
SELECT Id, Name,isactive,lastlogindate,createddate, Inactive_Date__c
FROM User
WHERE isactive = True
AND Management_User__c = False
AND
((lastlogindate != null and lastlogindate < LAST_90_DAYS) OR (lastlogindate = null and CreatedDate < LAST_90_DAYS))
LIMIT 100 ];

}

Integer i =1;
for(user u: UserList)
{

if( (u.Inactive_Date__c== null) || (u.Inactive_Date__c != null && (u.Inactive_Date__c< (system.today()-5)) ))
{
Usr = Usr + i+'. '+u.name + '’;
i = i+1;
u.isactive = False;
updUsers.add(u);
}
}
if(updUsers.size()>0)
{
try
{
system.debug(‘Try Part — UpdUsersListSize–‘+updUsers.size());
update updUsers;
system.debug(‘Try Part after update’);
sndEmail(AdminEmail,’Deactivated User List for ‘+sDate,’Dear Administrator,The following Company users have been deactivated during today’s run.’+Usr);
}
catch(Exception e)
{
system.debug(‘Exception:’+e);
sndEmail(AdminEmail,’Exception in Deactivate Users ‘+sDate,’Dear Administrator,The following exception has stopped todays Deactivate Users Run.’+e+’ The below users will have to be manually deactivated.’+Usr);
}
}
else
{
sndEmail(DeveloperEmail,’No Deactivated Users ‘+sDate,’Dear Administrator,There are no deactived users today’);
}

}
}

Public void sndEmail(String[] ToAdr,String Sub, String bdy){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setUseSignature(false);
mail.setSenderDisplayName(‘Global CRM Team’);
mail.setToAddresses(ToAdr);
mail.setSubject(Sub);
mail.setHtmlBody(bdy);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}

}

Reply
    David Liu
    April 22, 2014 @ 9:06 pm

    hahaha, not gonna lie, that’s too much code for me to debug!!!

    The code is relatively advanced – if you can learn up to chapter 7 you’ll be able to tackle this one!

    David

    Reply
Jay
April 7, 2014 @ 8:40 pm

I have a question for you as well, I am trigger to write a trigger for the following situation and could use some guidance, I have a custom field on a case (service console), and a lookup field which looks up to a custom object, also on the case layout, my trigger needs to take the first custom field (text) and auto populate the lookup field with the same value. (So no matter which you type the value in, the other field populates as well) Thoughts?

Reply
    David Liu
    April 7, 2014 @ 9:07 pm

    Definitely possible with code =) Something like this!

    if (Field_1__c == null) {
      Field_1__c = Field_2__c;
    } else if (Field_2__c == null) {
      Field_2__c = Field_1__c;
    }

    Reply
      Jay
      April 9, 2014 @ 4:46 pm

      Thanks for your response David! I am building the class right now. I assume I need to only pull both fields and the id from the case object in the SOQL query, does that sound about right?

      Reply
        David Liu
        April 9, 2014 @ 10:05 pm

        No need to query either of the fields since they’re already on the trigger object (they are auto queried by default!)

        Reply
          Jay
          April 10, 2014 @ 4:02 am

          Thanks David. How does the object the trigger is firing upon know which fields field_1__c/field_2__c are? Am I supposed to define them in the class, as variables?

          Reply
            David Liu
            April 10, 2014 @ 11:38 pm

            If you need to access those values you can simply do this:

            myCase.Field_1__c
            myCase.Field_2__c

            Of course this needs to be done inside your loop of Trigger.new!

            Hope this helps!
            David

            Reply
Chandra Kanth Knduru
March 16, 2014 @ 8:12 pm

Hi David Liu,

Thanks for the material and Login details. Very useful stuff. If I get a chance to come to US i’ll definetely work with you (even if i dont get a pay);)…

Reply
    David Liu
    March 16, 2014 @ 9:26 pm

    hahaha awesome, I would love to teach in person!

    Reply
sreenivasulu
March 6, 2014 @ 11:33 am

Hi David
I have One Scenario : Send Email To System Admins When new Object in created .with link to the object.
please help me this is urgent requirement.

Reply
    David Liu
    March 6, 2014 @ 9:54 pm

    Perfect! Here’s a recent post on how to send emails using Apex:
    https://www.sfdc99.com/2014/03/01/sending-emails-using-apex/

    You’ll notice that all Salesforce links are simply naXX.salesforce.com/recordId

    Also note that you can probably do this without any code using a workflow.
    David

    Reply
      sreenivasulu
      March 6, 2014 @ 10:32 pm

      Hi David,
      using custom links how send email to system admins when record created.with link to the object give me full code

      Reply
        David Liu
        March 6, 2014 @ 10:34 pm

        Sreenivasulu I only guide =) I can teach you how to fish but I won’t catch the fish for you!

        Reply
Moh
March 3, 2014 @ 2:44 pm

Hey David, thanks for all of your work. I have seen a video of yours on creating and deploying triggers and since then I have written few triggers which works really well. However, now I am bit confused as I am unable to write one trigger.

The scenario is when we create an opportunity, we have to manually add the contact roles in that opportunity. Is there a way we can automatically set this up or we have to write a trigger for this ??

Scenario: When we create an opportunity it should automatically add all the contacts in the related account as contact roles in that opportunity, only if the opportunity type is “Membership”

Any help will be highly appreciated

Thanks
Moh

Reply
    David Liu
    March 3, 2014 @ 10:38 pm

    You can get halfway there without code!

    Just make sure people create opportunities from one of these two places:
    – Lead
    – Contact

    Creating an opp any other way won’t automatically create a Contact Role.

    If this doesn’t cut it, you can code it!
    David

    Reply
Sridhar K N
February 24, 2014 @ 10:10 am

Hi Dave,

I thank you for making me understand apex coding very easy. You are my APEX Guru now.

Cheers
Sridhar

Reply
    David Liu
    February 24, 2014 @ 6:51 pm

    And you my loyal student Sridhar! Let me know if you ever need advice!

    Reply
Brian
January 30, 2014 @ 4:08 pm

David, thanks for all the work you put into this site, it’s helpful to see some Apex documentation and tutorials that don’t start of with “Similar to Java…”

Reply
    David Liu
    January 30, 2014 @ 7:48 pm

    My pleasure Brian =)

    Reply
mounica
January 30, 2014 @ 12:57 am

Hi David,
I am poor in developing part can u please help me regarding that.

Reply
    David Liu
    January 30, 2014 @ 7:46 pm

    Hey Mounica,

    Is there anything in particular I can help you out with? Try going through the chapters one by one!
    https://www.sfdc99.com/beginner-tutorials/

    David

    Reply
Joe
January 29, 2014 @ 10:05 pm

Great site! thanks for making coding easy to learn!

Reply
    David Liu
    January 29, 2014 @ 10:06 pm

    Thank you Joe! I hope you have a great career as a developer – let me know how it goes!

    Reply
Robert B.
January 28, 2014 @ 6:17 pm

ALL CAPS COMMENTS!
But on the real, this is incredibly useful. Thanks for putting this together, David.

Reply
    David Liu
    January 28, 2014 @ 8:26 pm

    hahaha, my pleasure I enjoy it!

    Reply
Anonymous
January 3, 2014 @ 2:59 am

NICE HELP FULL

Reply
    David Liu
    January 3, 2014 @ 1:26 pm

    THANKS!!

    hahaha
    David

    Reply

Leave a Reply Cancel reply

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


*

*

Theme: Simple Style by Fimply