Apex4AdminsIntroduction to Coding for Admins and Non-CodersSamantha Ready
Senior Developer Evangelist
@samantha_ready
Safe Harbor
Safe harbor statement under the Private Securities Litigation Reform Act of 1995:
This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the
assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we
make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of product or service availability,
subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements
of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services.
The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, new
products and services, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays
in our Web hosting, breach of our security measures, the outcome of intellectual property and other litigation, risks associated with possible mergers and
acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and
manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization
and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our
annual report on Form 10-Q for the most recent fiscal quarter ended July 31, 2012. This documents and others containing important disclosures are available on
the SEC Filings section of the Investor Information section of our Web site.
Any unreleased services or features referenced in this or other presentations, press releases or public statements are not currently available and may not be
delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available.
Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.
Samantha Ready
Senior Developer Evangelist
@samantha_ready
Introduction to Apex & Visualforce
• Who is this workshop for?
• Clicks vs Code
• Beyond Declarative
• Apex 101
• How does Visualforce Work?
• SOQL for everyone
• Apex Triggers
• Apex Test Classes
#forcewebinar
Free Developer Environment
http://developer.salesforce.com/signup
bit.ly/apex4admins-df14
Two Approaches to Development
Visualforce Pages
Visualforce Components
Apex Controllers
Apex Triggers
Metadata API
REST API
Bulk API
Formula Fields
Validation Rules
Workflows and Approvals
Custom Objects
Custom Fields
Relationships
Page Layouts
Record Types
User
Interface
Business
Logic
Data
Model
Declarative Approach Programmatic Approach
Apex and Visualforce for Every Object, Every Field
Visualforce Pages
Visualforce Components
Apex Controllers
Apex Triggers
Custom UI
Custom Logic
Use to
introduce a
demo, video,
Q&A, etc. Let’s start with Apex…We’ll cover the basics of writing and reading Apex
What is Apex?
• Salesforce platform language
• Similar to Java
• Object-oriented
• Strongly typed
• Classes and Interfaces
• Cloud based compiling, debugging and unit testing
#forcewebinar
What Can You Do With Apex?
Visualforce Controllers
Inbound/Outbound
Email Services
Custom web services and
HTTP CalloutsDatabase Triggers
Scheduled and Batched Tasks
Data Types and Variables
• String favoriteBeer = ‘Lagunitas IPA’;
• Integer numberOfBeers = 6;
• Decimal bloodAlcoholLevel = 0.15
• Boolean isDrunk = true;
• Date courtDate = Date.today().addDays(30);
• DateTime timePulledOver = DateTime.now();
• Contact me = new Contact(FirstName = ‘Bud’, LastName = ‘Weiser’,
Email=‘[email protected]’);
Data Collections
Data Collections are groupings of any data type
• Lists – can be ordered and indexed
• List<Contact> peopleToSpam = [SELECT Email, Id FROM Contact];
• Contact firstContact = peopleToSpam[0];
• Contact lastContact = peopleToSpam[peopleToSpam.size() -1];
• Sets – unordered lists with no dupes
• Maps – key value pairs
Dot Notation
• Similar syntax to merge fields in formula fields or email templates to access field
values from instance variables
• Decimal companyRev = myContact.Account.Revenue;
• User relatedProjectOwner = myContact.Project__c.Owner;
• List<Opportunity> opps = myContact.Account.Opportunities;
• Can also be used to call instance methods
• Integer numOpps = opps.size();
• String iLoveCaps = myContact.FirstName.capitalize();
Loops
The FOREACH loop will repeatedly execute for every element in the list
List<Contact> allContacts = [SELECT Id FROM Contact];
for (Contact currentContact : allContacts) {
// This is my contact Id. People love me!
currentContact.Best_Friend__c = ‘003i000000Mnm1R’;
}
Comparison Operators
Any statement that evaluates to True or False
Try and guess which below are True or False
presenter.Age __c >= marcBenioff.Age__c;
presenter.numSessionsAttended < 10
presenter.Gender __c != ‘Male’;
presenter.Sleep_hours __c == 5;
IF Statement
Similar to IF statements in formula fields, but more powerful
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
}
Creating, updating, and deleting records
Commit action on a record or list of records to the database
• insert myLead;
• update myLead;
• delete myLead;
Use to
introduce a
demo, video,
Q&A, etc.
Now let’s talk about Apex in the context of Visualforce…
Visualforce
• Framework to build custom user interfaces
• Hosted natively on Force.com
• Build streamlined UX
• Extend Salesforce.com
• Customize for different devices
• Leverage other web technologies
Visualforce Controllers
• Provides access to data
• Logic for handling UI interaction
• Standard Controllers
• Same functionality as standard pages
• Save, delete, field access etc.
• Custom Controllers
• Written in Apex
• Override standard behavior
• Controller Extensions
#forcewebinar
MVC example
How do I connect a controller?
Standard or
custom objects
Defined at the
page level
Custom controller
logic to extend
standard controllers
Inherit standard CRUD
functionality.
If only using custom controllers,
use controller=“controllerName”
<apex:page standardController = “Restaurant__c” extensions=“ext1, ext2” />
Apex and Visualforce
Custom UIController
Demo 1 and 2 Visualforce with standard controllers and extensions
Pop Quiz
Where can Visualforce Pages be
used in your org?
Templates
Embedded in Page
LayoutsGenerate PDFs
Custom Tabs
Mobile
Interfaces
Page Overrides
Where can I use Visualforce?
You can create tabs or go to /apex/[Page Name]
Mashups and External Sites
Pop Quiz
What would we use to query for lists of data programmatically if
we didn’t use a StandardController?
SOQL(Salesforce Object Query Language)
What's SOQL?
• Salesforce Object Query language
• Similar to SQL
• Streamlined syntax to traverse object relationships
• Built into Apex
• Query results returned as nested objects
• You can’t reference fields on queried instance variables without querying for them
SELECT Id, Name, Phone
FROM Contact
SELECT Id, Name, Phone
FROM Contact
WHERE Phone != null
SELECT Id, Name, Phone
FROM Contact
WHERE Phone != null
AND Name LIKE '%rose%'
SELECT Id, Name, Phone
FROM Contact
WHERE Phone != null
AND Name LIKE '%rose%'
ORDER BY Name
SELECT Id, Name, Phone
FROM Contact
WHERE Phone != null
AND Name LIKE '%rose%'
ORDER BY Name
LIMIT 50
Details to Master
SELECT Id, Name, Phone, Account.Name
FROM Contact
WHERE Phone <> null
AND Name LIKE '%rose%'
ORDER BY Name
LIMIT 50
Master to Details
SELECT Name,
(SELECT FirstName, LastName, Phone
FROM Contacts)
FROM Account
Executing SOQL in the Developer Console
Pop Quiz
If I wanted to upload an image to use in a Visualforce
Page, where would I upload it in Setup?
Static
Resources
Hands-on Exercisebit.ly/apex4admins-df14Exercise: Visualforce Homepage Component
Use to
introduce a
demo, video,
Q&A, etc.
Now let’s talk about Apex in the context of Triggers…
What's a Trigger?
• Apex code executed on database events.
• Like a workflow, but with code and more flexibility
• Before or after:
• Insert
• Update
• Delete
• Undelete
• Best Practice: BULKIFY!
• Examples
• Modify the object being saved
• Create new objects
• Modify related objects
• Modify any object in the system
Before or After?
• Before
• Update or validate values before they are saved to the database
• Example: Prevent double-booking of a speaker
• After
• Need access to values set by the database (Id, lastUpdated, …)
• Example: Send speaker confirmation email
#forcewebinar
Anatomy of a Trigger
Chapter 1:
#forcewebinar
Glossary of Terms
•
• Salesforce Keyword
• Variable
• Free Text Important!
Pop Quiz
I want to create a Chatter post (FeedItem) on the related
account every time I create an Opportunity or change the stage.
Fill in the blanks:
Trigger postOpptyInfoToAccount on ??what?? (??when??)
Trigger postOpptyInfoToAccount on Opportunity (after insert,
after update)
Pop Quiz
I want to set a custom checkbox field (VIP__c) on Account if the
total Opportunities value exceeds $1M and the Account Rating
field is ‘Cold.’
Trigger setToVIP on ??what?? (??when??)
Trigger setToVIP on Account (before update)
Pop Quiz
When an Account is (or many Accounts are) inserted I want a
trigger that uses the Account Name and Billing State to set the
Description field to {!Account.Name} : {!Account.BillingState}
Trigger setDescription on ??what?? (??when??)
Trigger setDescription on Account (before insert, before update)
Hands-on Exercisebit.ly/apex4admins-df14Exercise: Visualforce Homepage Component
Use to
introduce a
demo, video,
Q&A, etc.
Now let’s talk about Apex in the context of Test Classes…
#forcewebinar
What is a Test Class?
• When do we use Test Classes?
• What are the requirements?
• Test Class vs. Trigger
• Why should I care?
Unit Testing
• Code to test code
• All data in a test class is transient
• Increases quality and predictability
• Unit test coverage is required to move code to production
• Must have at least 75% of code covered
• Coverage = lines of code exercised by tests / total line of code
#forcewebinar
Anatomy of a Test Class
@isTest
private class myClass {
static testMethod void myTest() {
// 1. Prepare temporary data
// 2. Start Test
// 3. Execute some code
// 4. Stop Test
// 5. Assert
}
}
#forcewebinar
Test and Assert
Test.startTest();
// Try to book speaker for session2
Session_Speaker__c booking2=
new Session_Speaker__c(Session__c=s2.Id, Speaker__c=sp.Id);
Database.SaveResult result = Database.insert(booking2, false);
Test.stopTest();
// Insert should fail: can't book same speaker for 2 sessions happening
// at same time
System.assert(!result.isSuccess());
Running Tests
Resources
• Developer Forums • http://developer.salesforce.com/forums
• SFDC99 – David’s Site• http://sfdc99.com
• Join the community
• #Apex4Admins #AskForce
www.SFDC99.com
Surveybit.ly/df-how-apex4admins
Samantha Ready
Senior Developer Evangelist
@samantha_ready
Show FlowDreamforce 2104 Breakout Session Show Flow Template
Notes
Session TitleIntroduction to Development on Force.com for Admins and Non-Coders
Presentation Device: Computer
Customer Speaker: You!
Salesforce Speakers: None at DF
Demo Device Computer
Demo Driver: You!
Deck Owner/Filename: Samantha Ready
0:00 Doors open
start 0:00 Start
takes 5 minutes 0:05 Welcome and Intros
3 min 0:08 Signup together for a DE
17 min 0:25 Intro Platform & Apex the Intro Platform Apex/Intro Visualforce timing is really based off of how you read the
20 min 0:45 Intro Visualforce audience… spend more time where is necessary, fundamentals are important
10 min 0:55 Visualforce Demo
5 min 1:00 SOQL
20 min 1:20 1st Hands-On
25 min 1:45 Triggers
20 min 2:05 2nd Hands-On
20 min 2:25 Unit Tests
5 min 2:30 Resources / Q&A