SlideShare a Scribd company logo
Apex4Admins 
Introduction to Coding for Admins and 
Non-Coders 
Samantha 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
Free Developer Environment 
#forcewebinar 
http://developer.salesforce.com/signup 
bit.ly/apex4admins-df14
Two Approaches to Development 
Declarative Approach Programmatic Approach 
Visualforce Pages 
Visualforce Components 
Apex Controllers 
Apex Triggers 
Metadata API 
REST API 
Bulk API 
Page Layouts 
Record Types 
Formula Fields 
Validation Rules 
Workflows and Approvals 
Custom Objects 
Custom Fields 
Relationships 
User 
Interface 
Business 
Logic 
Data 
Model
Apex and Visualforce for Every Object, Every Field 
Visualforce Pages 
Visualforce Components 
Apex Controllers 
Apex Triggers 
Custom UI 
Custom Logic
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
What Can You Do With Apex? 
#forcewebinar 
Visualforce Controllers 
Inbound/Outbound 
Email Services 
Custom web services and 
HTTP Callouts 
Database 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=‘BWeiser@yahoo.com’);
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;
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
MVC example 
#forcewebinar
How do I connect a controller? 
Standard or 
custom objects 
Defined at the 
page level 
<apex:page standardController = “Restaurant__c” extensions=“ext1, ext2” /> 
Custom controller 
logic to extend 
standard controllers 
Inherit standard CRUD 
functionality. 
If only using custom controllers, 
use controller=“controllerName”
Apex and Visualforce 
Controller Custom UI
Demo 1 and 2 Visualforce with standard controllers and extensions
Pop Quiz 
Where can Visualforce Pages be 
used in your org?
Email 
Templates 
Embedded in Page 
Layouts 
Generate 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 Exercise 
bit.ly/apex4admins-df14 
Exercise: Visualforce Homepage Component
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
Anatomy of a Trigger 
Chapter 1: 
#forcewebinar
Glossary of Terms 
Important! • Free Text 
• 
• Salesforce Keyword 
• Variable 
#forcewebinar
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 Exercise 
bit.ly/apex4admins-df14 
Exercise: Visualforce Homepage Component
Now let’s talk about Apex in the 
context of Test Classes…
What is a Test Class? 
• When do we use Test Classes? 
• What are the requirements? 
• Test Class vs. Trigger 
• Why should I care? 
#forcewebinar
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
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()); 
#forcewebinar
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
Samantha Ready 
Senior Developer Evangelist 
@samantha_ready 
Survey 
bit.ly/df-how-apex4admins
Hands-On Workshop: Introduction to Coding for on Force.com for Admins and Non-Coders
Show Flow 
Dreamforce 2104 Breakout Session Show Flow Template 
Notes 
Session Title 
Introduction 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

More Related Content

PPTX
Introduction to Point-and-Click App Building
POTX
Hands-on Workshop: Intermediate Development with Heroku and Force.com
PPTX
Hands-On Workshop: Introduction to Development on Force.com for Developers
PPTX
Salesforce Lightning workshop
PPTX
Lightning Experience with Visualforce Best Practices
PPTX
Salesforce Lightning Design System
PPTX
Force.com Friday - Intro to Visualforce
PPTX
Force.com Friday - Intro to Force.com
Introduction to Point-and-Click App Building
Hands-on Workshop: Intermediate Development with Heroku and Force.com
Hands-On Workshop: Introduction to Development on Force.com for Developers
Salesforce Lightning workshop
Lightning Experience with Visualforce Best Practices
Salesforce Lightning Design System
Force.com Friday - Intro to Visualforce
Force.com Friday - Intro to Force.com

What's hot (20)

PPTX
Rits Brown Bag - Salesforce Lightning
PPTX
Salesforce Lightning Experience Overview by Brainiate
PPTX
Migrating to Salesforce Lightning - A Personal Experience Presented to EA For...
PPTX
Lightning Component - Components, Actions and Events
PDF
Apex tutorial
PDF
Visual Workflow Overview
PPTX
Aura Framework and Lightning (Nikolay Zenko and Alexey Filippov)
PPTX
Migrating to Salesforce Lightning
PPTX
Secure Development on the Salesforce Platform - Part I
PDF
Build Cloud & Mobile App on Salesforce Force.com Platform in 15 mins
PPTX
Lightning Developer Week - Bangalore Salesforce Developer Group
PPTX
Coding in the App Cloud
PPTX
Best Practices for Lightning Apps
PDF
Dreamwares_Salesforce Updated
PPTX
Integrating Salesforce with Microsoft Office through Add-ins
PDF
Local development with Open Source Base Components
PDF
Lightning Design System and Components for Visualforce Developers
PPTX
Introduction to the Wave Platform API
PPTX
Go Faster with Lightning - Overview
PPTX
Using Apex for REST Integration
Rits Brown Bag - Salesforce Lightning
Salesforce Lightning Experience Overview by Brainiate
Migrating to Salesforce Lightning - A Personal Experience Presented to EA For...
Lightning Component - Components, Actions and Events
Apex tutorial
Visual Workflow Overview
Aura Framework and Lightning (Nikolay Zenko and Alexey Filippov)
Migrating to Salesforce Lightning
Secure Development on the Salesforce Platform - Part I
Build Cloud & Mobile App on Salesforce Force.com Platform in 15 mins
Lightning Developer Week - Bangalore Salesforce Developer Group
Coding in the App Cloud
Best Practices for Lightning Apps
Dreamwares_Salesforce Updated
Integrating Salesforce with Microsoft Office through Add-ins
Local development with Open Source Base Components
Lightning Design System and Components for Visualforce Developers
Introduction to the Wave Platform API
Go Faster with Lightning - Overview
Using Apex for REST Integration
Ad

Viewers also liked (20)

PDF
Salesforce Lightning Components Workshop
PPTX
Salesforce Lightning Components
PDF
Introducing: The Lightning Experience
PPT
Salesforce Ideas Implementation Best Practices
PDF
Salesforce1 app getting started guide
PDF
Salesforce Spring '16 Release Overview
PDF
Diseñando para Apple Watch
PDF
Poquet a Poquet - Octubre 2015
PDF
Documento peh chdraam 06 febrero 12_versión resumida renovada
PDF
Motorola air defense configuring an ap650 running wing 5.x as a sensor only
PDF
Un 02 act 03 anexo 01
PPT
Digitale Nähe - Zukunft des digitalen Tourismusmarketings
PDF
3000 từ tiếng anh thông dụng
PPTX
Lightning Components Introduction
PDF
Lightning Components Explained
PPT
3 swpp ps for const sites tonning ksa apr 2010
PDF
Introducing the Salesforce Lightning Design System
PDF
Cybersecurity and Legal lessons after Apple v FBI
PDF
ACCIONA ENERGIA EN MÉXICO: UNA ESTRATEGIA EMPRESARIAL CON VALOR SOCIAL
PDF
Salesforce Adoption and Best Practices
Salesforce Lightning Components Workshop
Salesforce Lightning Components
Introducing: The Lightning Experience
Salesforce Ideas Implementation Best Practices
Salesforce1 app getting started guide
Salesforce Spring '16 Release Overview
Diseñando para Apple Watch
Poquet a Poquet - Octubre 2015
Documento peh chdraam 06 febrero 12_versión resumida renovada
Motorola air defense configuring an ap650 running wing 5.x as a sensor only
Un 02 act 03 anexo 01
Digitale Nähe - Zukunft des digitalen Tourismusmarketings
3000 từ tiếng anh thông dụng
Lightning Components Introduction
Lightning Components Explained
3 swpp ps for const sites tonning ksa apr 2010
Introducing the Salesforce Lightning Design System
Cybersecurity and Legal lessons after Apple v FBI
ACCIONA ENERGIA EN MÉXICO: UNA ESTRATEGIA EMPRESARIAL CON VALOR SOCIAL
Salesforce Adoption and Best Practices
Ad

Similar to Hands-On Workshop: Introduction to Coding for on Force.com for Admins and Non-Coders (20)

PPTX
Elevate Tel Aviv
PDF
Elevate london dec 2014.pptx
PPTX
Atl elevate programmatic developer slides
PPTX
Introduction to Apex for Developers
PPTX
Apex for Admins: Beyond the Basics (Part 2)
PDF
Intro to Apex Programmers
PPT
Salesforce1 Platform for programmers
DOCX
Salesforce couse in chennai
DOCX
Salesforce Certification in chennai
DOCX
Salesforce couse Training in chennai
DOCX
SALESFORCE TRAINING IN CHENNAI
DOCX
Salesforce couse content
PPTX
Salesforce Campus Tour - Developer Intro
PPTX
Force.com Friday : Intro to Apex
ODP
CRM Science - Dreamforce '14: From Admin to Developer: Learning to Code on F...
PPTX
Force.com Friday: Intro to Visualforce (May 8, 2015)
PPTX
Salesforce Campus Tour - Declarative
PPTX
Visualforce
PPTX
Coding Apps in the Cloud with Force.com - Part 2
PPTX
Coding Apps in the Cloud with Force.com - Part I
Elevate Tel Aviv
Elevate london dec 2014.pptx
Atl elevate programmatic developer slides
Introduction to Apex for Developers
Apex for Admins: Beyond the Basics (Part 2)
Intro to Apex Programmers
Salesforce1 Platform for programmers
Salesforce couse in chennai
Salesforce Certification in chennai
Salesforce couse Training in chennai
SALESFORCE TRAINING IN CHENNAI
Salesforce couse content
Salesforce Campus Tour - Developer Intro
Force.com Friday : Intro to Apex
CRM Science - Dreamforce '14: From Admin to Developer: Learning to Code on F...
Force.com Friday: Intro to Visualforce (May 8, 2015)
Salesforce Campus Tour - Declarative
Visualforce
Coding Apps in the Cloud with Force.com - Part 2
Coding Apps in the Cloud with Force.com - Part I

More from Salesforce Developers (20)

PDF
Sample Gallery: Reference Code and Best Practices for Salesforce Developers
PDF
Maximizing Salesforce Lightning Experience and Lightning Component Performance
PPTX
TrailheaDX India : Developer Highlights
PDF
Why developers shouldn’t miss TrailheaDX India
PPTX
CodeLive: Build Lightning Web Components faster with Local Development
PPTX
CodeLive: Converting Aura Components to Lightning Web Components
PPTX
Enterprise-grade UI with open source Lightning Web Components
PPTX
TrailheaDX and Summer '19: Developer Highlights
PDF
Live coding with LWC
PDF
Lightning web components - Episode 4 : Security and Testing
PDF
LWC Episode 3- Component Communication and Aura Interoperability
PDF
Lightning web components episode 2- work with salesforce data
PDF
Lightning web components - Episode 1 - An Introduction
PDF
Migrating CPQ to Advanced Calculator and JSQCP
PDF
Scale with Large Data Volumes and Big Objects in Salesforce
PDF
Replicate Salesforce Data in Real Time with Change Data Capture
PDF
Modern Development with Salesforce DX
PDF
Get Into Lightning Flow Development
PDF
Integrate CMS Content Into Lightning Communities with CMS Connect
PDF
Introduction to MuleSoft
Sample Gallery: Reference Code and Best Practices for Salesforce Developers
Maximizing Salesforce Lightning Experience and Lightning Component Performance
TrailheaDX India : Developer Highlights
Why developers shouldn’t miss TrailheaDX India
CodeLive: Build Lightning Web Components faster with Local Development
CodeLive: Converting Aura Components to Lightning Web Components
Enterprise-grade UI with open source Lightning Web Components
TrailheaDX and Summer '19: Developer Highlights
Live coding with LWC
Lightning web components - Episode 4 : Security and Testing
LWC Episode 3- Component Communication and Aura Interoperability
Lightning web components episode 2- work with salesforce data
Lightning web components - Episode 1 - An Introduction
Migrating CPQ to Advanced Calculator and JSQCP
Scale with Large Data Volumes and Big Objects in Salesforce
Replicate Salesforce Data in Real Time with Change Data Capture
Modern Development with Salesforce DX
Get Into Lightning Flow Development
Integrate CMS Content Into Lightning Communities with CMS Connect
Introduction to MuleSoft

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
A Presentation on Artificial Intelligence
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Cloud computing and distributed systems.
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Electronic commerce courselecture one. Pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Building Integrated photovoltaic BIPV_UPV.pdf
NewMind AI Monthly Chronicles - July 2025
Advanced methodologies resolving dimensionality complications for autism neur...
Understanding_Digital_Forensics_Presentation.pptx
A Presentation on Artificial Intelligence
Network Security Unit 5.pdf for BCA BBA.
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Spectral efficient network and resource selection model in 5G networks
Dropbox Q2 2025 Financial Results & Investor Presentation
Big Data Technologies - Introduction.pptx
Cloud computing and distributed systems.
Reach Out and Touch Someone: Haptics and Empathic Computing
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Digital-Transformation-Roadmap-for-Companies.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf

Hands-On Workshop: Introduction to Coding for on Force.com for Admins and Non-Coders

  • 1. Apex4Admins Introduction to Coding for Admins and Non-Coders Samantha Ready Senior Developer Evangelist @samantha_ready
  • 2. 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.
  • 3. Samantha Ready Senior Developer Evangelist @samantha_ready
  • 4. 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
  • 5. Free Developer Environment #forcewebinar http://developer.salesforce.com/signup bit.ly/apex4admins-df14
  • 6. Two Approaches to Development Declarative Approach Programmatic Approach Visualforce Pages Visualforce Components Apex Controllers Apex Triggers Metadata API REST API Bulk API Page Layouts Record Types Formula Fields Validation Rules Workflows and Approvals Custom Objects Custom Fields Relationships User Interface Business Logic Data Model
  • 7. Apex and Visualforce for Every Object, Every Field Visualforce Pages Visualforce Components Apex Controllers Apex Triggers Custom UI Custom Logic
  • 8. Let’s start with Apex… We’ll cover the basics of writing and reading Apex
  • 9. What is Apex? • Salesforce platform language • Similar to Java • Object-oriented • Strongly typed • Classes and Interfaces • Cloud based compiling, debugging and unit testing
  • 10. What Can You Do With Apex? #forcewebinar Visualforce Controllers Inbound/Outbound Email Services Custom web services and HTTP Callouts Database Triggers Scheduled and Batched Tasks
  • 11. 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=‘BWeiser@yahoo.com’);
  • 12. 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
  • 13. 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();
  • 14. 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’; }
  • 15. 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;
  • 16. 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 }
  • 17. Creating, updating, and deleting records Commit action on a record or list of records to the database • insert myLead; • update myLead; • delete myLead;
  • 18. Now let’s talk about Apex in the context of Visualforce…
  • 19. 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
  • 20. 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
  • 22. How do I connect a controller? Standard or custom objects Defined at the page level <apex:page standardController = “Restaurant__c” extensions=“ext1, ext2” /> Custom controller logic to extend standard controllers Inherit standard CRUD functionality. If only using custom controllers, use controller=“controllerName”
  • 23. Apex and Visualforce Controller Custom UI
  • 24. Demo 1 and 2 Visualforce with standard controllers and extensions
  • 25. Pop Quiz Where can Visualforce Pages be used in your org?
  • 26. Email Templates Embedded in Page Layouts Generate PDFs Custom Tabs Mobile Interfaces Page Overrides Where can I use Visualforce?
  • 27. You can create tabs or go to /apex/[Page Name]
  • 29. 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)
  • 30. 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
  • 31. SELECT Id, Name, Phone FROM Contact
  • 32. SELECT Id, Name, Phone FROM Contact WHERE Phone != null
  • 33. SELECT Id, Name, Phone FROM Contact WHERE Phone != null AND Name LIKE '%rose%'
  • 34. SELECT Id, Name, Phone FROM Contact WHERE Phone != null AND Name LIKE '%rose%' ORDER BY Name
  • 35. SELECT Id, Name, Phone FROM Contact WHERE Phone != null AND Name LIKE '%rose%' ORDER BY Name LIMIT 50
  • 36. Details to Master SELECT Id, Name, Phone, Account.Name FROM Contact WHERE Phone <> null AND Name LIKE '%rose%' ORDER BY Name LIMIT 50
  • 37. Master to Details SELECT Name, (SELECT FirstName, LastName, Phone FROM Contacts) FROM Account
  • 38. Executing SOQL in the Developer Console
  • 39. Pop Quiz If I wanted to upload an image to use in a Visualforce Page, where would I upload it in Setup? Static Resources
  • 40. Hands-on Exercise bit.ly/apex4admins-df14 Exercise: Visualforce Homepage Component
  • 41. Now let’s talk about Apex in the context of Triggers…
  • 42. 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
  • 43. 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
  • 44. Anatomy of a Trigger Chapter 1: #forcewebinar
  • 45. Glossary of Terms Important! • Free Text • • Salesforce Keyword • Variable #forcewebinar
  • 46. 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)
  • 47. 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)
  • 48. 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)
  • 49. Hands-on Exercise bit.ly/apex4admins-df14 Exercise: Visualforce Homepage Component
  • 50. Now let’s talk about Apex in the context of Test Classes…
  • 51. What is a Test Class? • When do we use Test Classes? • What are the requirements? • Test Class vs. Trigger • Why should I care? #forcewebinar
  • 52. 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
  • 53. 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 }
  • 54. 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()); #forcewebinar
  • 56. Resources • Developer Forums • http://developer.salesforce.com/forums • SFDC99 – David’s Site • http://sfdc99.com • Join the community • #Apex4Admins #AskForce
  • 58. Samantha Ready Senior Developer Evangelist @samantha_ready Survey bit.ly/df-how-apex4admins
  • 60. Show Flow Dreamforce 2104 Breakout Session Show Flow Template Notes Session Title Introduction 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

Editor's Notes

  • #8: When building custom apps, its important to know how all of the components work together. Apex and Visualforce are inherently designed to undestand the Salesforce Object Model in your custom schema. It can read the metadata of an object or field, and automatically checks against profiles and permissions when programmatically accessing them. The platform handles things like visbility and edit rights, so even if you tried to display a field on a Visualforce page, if the end user didn’t have the perms to see it, it wouldn’t appear on the page. The same thing goes with inserting or any other commit to the database—without the perms, a platform won’t allow it.
  • #9: Now lets go through some of the basics of Apex programming and syntax, and then we can get to building and modifying.
  • #10: Natively build back end logic on Force.com Looks like Java and very human readable You can build classes, which represent a set of custom actions or methods that you can execute, and triggers which are like the code version of workflow In order to be able to push any code into production, you need to build test classes for them to ensure they won’t break in production and create a bad user experience for your end users
  • #11: These are the most common use cases for using Apex in an org. We’re going to be introducing Database Triggers and Visualforce controllers today. (feel free to elaborate on any of these with personal examples of things you’ve built)
  • #12: First lets talk about some basic data types. These are definitely not all of them, but these are a few of the data types that you’ll see most often. In order to use variables in your Apex code, you need to declare a variable with a data type and optionally assign it a value right away or assign it later in your code These data types define the type of data your using in code. Some are the same as their twin-named field types, but let me explain the ones you might not have heard of before…. String – a line of text, read by the compiler as pure text Integer – a whole number with no decimal places Decimal – a number with decimal places Boolean – a variable that can either be true or false Contact  this one is different because its called an sObject. The programmatic representation of an instance of an object. In this example it’s a representation of an instance of a contact, aka a potential record, but it’s the same syntax for any standard or custom object.
  • #13: You can use these three collection types to store different sets of data Lists store ordered lists of records, and can be indexed and organized Sets are just like lists, but it cannot be ordered or indexed and does not allow for duplicates Maps store key and value pairs, where the key is a unique identifier for being able to reference a related value.
  • #14: An instance variable is a value of an sObject field or related set of records and can be assigned to a static variable to store the value and use in your code The various examples are ways to assign instance variables You can access fields on an object and assign it to a variable You can access fields on a related object and assign it to a variable You can also access a list of related records and assign it to a variable Instance variables also have instance methods which are methods that can provide information, evaluate, or manipulate the instance variable in some way. For example, the size() instance method evaluates the opps instance variable and returns an integer of the number of records in that list. The capitalize() instance method will store the myContact instance variables First Name as a text string in all capital letters
  • #15: Walk through this for each loop and explain the SOQL query, for each loop, and assigning the field value on that individual element in the list repeatedly
  • #16: Talk about what different logical operators there are, and read these examples as an english sentence “The age of the presenter is greater than or equal to Marc Benioff’s age. ” etc
  • #17: Walk through this if statement
  • #20: Visualforce is the fastest way to build custom user interfaces on Force.com because it does a lot of heavy lifting for you…. Mention how visualforce components are a compilation of HTML, CSS, and JS which you can view by viewing the source on a page. What this means is, it has automatic styling, structure, and built in functionality so that you don’t have to recreate UI components similar to what you’re already using in your Salesforce org from scratch Please use as many personal and past experience examples as possible
  • #21: In order to build a Visualforce page, you need to have a basic understanding of how dynamic data gets on the page. Visualforce uses the MVC Design pattern, the most commonly used design paradigm in all of enterprise computing Visualforce needs to use a controller in order to grab data from the database and put it onto the screen. It also needs a controller to handle any actions like saving a record or doing a calculation on the backend before updating a record There are two types of controllers you can implement: a standard or custom controller Standard controllers give you basic CRUD into any standard or custom object, and also give you out of the box actions on a given record or set of records. You don’t have to write any Apex, and in turn also don’t have to write any test classes either. A custom controller is written in Apex and can do whatever you code up! It can be a standalone controller, or extend a standard or other custom controller
  • #22: Heres a simple example of the MVC design pattern at work…. On your page you have a Visualforce component referencing an Account.Name field. The component is able to read the metadata of the field to properly render the right type of input. Here it shows text, but if this field were a picklist it would know to automatically display a picklist with all of the options. The value for this instance variable is being sourced from the custom apex controller. There is a public account variable that is declared in the class. You’ll notice this getter and setter method here too—a getter is what allows the page to get this variable value, and the setter method allows you to also set the value from your page form. Finally, after the end user clicks save, a controller action will commit the value of this account name value back to the database.
  • #23: How do you associate a controller with a page you ask? Right at the page tag! You can assign one to many different controllers, and if you have multiple primary controller extensions you can simply use commas to separate the different controllers.
  • #24: Relates to: Tutorial 7 When developing a page, you have a bunch of different ways to build it. You can use the setup menu, developer console, a 3rd party development environment…This image shows development mode which is a split screen view of your code and the Visualforce page itself so you can edit and view your page at the same time time. You can see the simple standard VF markup there within the page tag, and an associated apex controller to grab the data.
  • #25: Now let me show you two examples of a custom page. The first page only uses a standard controller with standard styling to output custom object data, but the second example has basically the same code with some custom CSS added in to change the look and feel, some jQuery for drag and drop funcitonality, and a custom button within the form so that you can invoke an action in your custom apex controller extension.
  • #26: Ask the audience to name a few…the answers are on the next slide
  • #27: I’ve showed you a couple different use cases of Visualforce, but you can also use visualforce to Build an email template off of several sets of data rather than 1 target object When you associate a standard controller with a page, you then have the option to drag that page onto the page layout using the standard page layout editor on that object You can generate pdfs using the renderAs=“pdf” attribute in the page tag You can create custom VF tabs and put it into your Force.com apps You can create mobile interfaces as stand alone HTML5 pages, in Hybrid mobile apps, or in Salesofrce1 You can override standard buttons (like the new button) to create a custom UI for standard and custom object record details
  • #28: Lets not also forget you can create VF pages to just navigate to via a url. Simply type /apex/the name of your page at the end of your na.salesforce.com URL to go to your page
  • #29: And while most Visualforce pages are internally facing where the end user had to login to Salesforce, you can also overlay pages onto Force.com sites.
  • #30: Ask this question and wait for someone to say the right answer… People might say ‘Apex’ and then you can say something like “that’s almost right, but Apex actually uses this to query for records within the database”
  • #32: Let’s walk through the anatomy of a SOQL query… Here you can see we’re grabbing a list of Contacts. Each of the contacts that we grab in this query will store a unique instance of each contact and the field values associated with the explicit fields queried for. In this case, those fields are Id, Name, and Phone
  • #33: But if we don’t want ALL the contacts in our org (Salesforce has limits afterall and if we have 100k contacts, this will cause an error) we can create a where clause to limit the number of records returned. In this case, we want all contacts that have a phone number stored to it (or conversely, where they don’t have a null or blank phone field)
  • #34: You can concatenate multiple delimiters to pair down your result set even further. In this case we’re using a logical AND operator to say grab all contacts with a phone number and whose names are like the string ‘rose.’ The percent symbols are like a wild card symbol so if for example a contact had the name ‘Melrose’ or ‘Rosetta’ they would fit this criteria
  • #35: The order by clause allows you to sort your list. In this case it will order in alphabetical order, but it would work with numbers and dates as well.
  • #36: Finally you can also limit the set with the LIMIT clause. This will take the first 50 contacts, but if any others fit the criteria after those 50 are stored, it will disregard them.
  • #37: You can also query for fields off of related records. In this case traversing through the master account record using the lookup field and grabbing the Name off the account
  • #38: You can also go the other direction from the parent to the children and grab a list of related records. In this case, if you were referencing the first account record from this returned list of accounts in your code and wanted to loop through the related contacts, you would reference that list with the syntax account[0].contacts
  • #39: Copy and paste the full Contact soql query from 2 slides ago into your dev console and explain how you execute it and why You would do this to see what results are returned and can use this to validate your soql queries and the results your’e seeing
  • #40: This is a reference back to the VF demo since you showed static resources there….
  • #41: This link will go directly to the VF exercise. It skips a lot of chapters/modules in the workbook, but they can go back and read those later as they are a detailed writeup of things we’ve already been talking about today.
  • #43: Triggers are like workflows written with code. They allow you to build custom logic off of any database operation It is like executing any action on a save or delete of a record. You can create records, update fields on the record that fired the trigger, modify related objects… But triggers do have limits, and one word you’ll probably hear a lot is BULKIFY What bulkify means is write your trigger with best practice coding techniques as if your trigger might run on a bulk set of records (like for example a bulk data load) Your trigger executes in a certain execution context, and so when you bulkify you are ensuring that you are making the least amount of API calls as possible when your trigger runs. This means doing things like a DML operation or a SOQL query outside of for loops. We’ll get to that in a minute…
  • #44: One final thing you need to wrap your head around with triggers is whether or not the trigger should run before or after whatever DML you want it to execute with (so either insert/update/delete) You should use a before trigger if you want to modify any values on the record that fired the trigger. You would use a before trigger because if you did an after, it would set the trigger into an infinite loop continuously firing itself. This would also be good for validation in things like duplicate records and preventing the duplicate from being inserted. Another use case for the before trigger would be to compare a field value with a previous field value on update to see if the value changed… You would use an after trigger when you need the Id. For example, if you want to create a record related to the record that fired the trigger, you would need that record’s Id in order to set the lookup field on the child object.
  • #45: Talk through this simple trigger and how it works. Mention the name, the object its associated with, the after insert Talk about the for loop Talk about creating the case
  • #46: Talk through glossary of terms. Mention how this trigger is NOT best practice bulkified because you are doing an insert in the for loop, and if there were even 50 accounts this trigger would break and fail. A good exercise (if you have time) would be to build this trigger in developer console and show how you would bulkify it (create a Case list outside of the for loop and add all cases to the list. Do the insert outside of the for loop)
  • #47: Ask this question and pose it to the audience. If they get it wrong, give them hints towards the right answer. I want to create a chatter post on account both when an opportunity is created AND when a field changes so this would be a trigger off of insert and update. Because I need the opportunity Id and the field it is an after insert, and then either a before or after update would work (but not both).
  • #48: Ask this question and pose it to the audience. If they get it wrong, give them hints towards the right answer. In this case, I want to set the field on Account. Because The opportunity values need to exceed $1M we know you cannot be creating the account, because opportunities are children of an account and would need to be created after an account is created so this has to be an update only. Also we want to do a before trigger because you are updating a field on the object that fired the trigger…. If this were an after trigger it would go into an infinite loop.
  • #49: Ask this question and pose it to the audience. If they get it wrong, give them hints towards the right answer. This would be on Account, and being that you want to modify a field on Account it would be a before trigger. You want to modify the account field when it is inserted, but also when either the name or billing state changes to keep the description up to date…so this would be a before insert and before update
  • #52: Test classes test triggers and apex classes to make sure they don’t break in production A test class essentially runs and executes code in either a trigger or apex class with transient (temporary) data Salesforce has 3 release cycles a year, so this also gives salesforce something to test against to make sure their updates to the platform doesn’t break your code. You should care because it ensures quality moving forward
  • #53: In more general terms, you write test class code to test code You need to create all data to use in a test class. It has no access to existing data in your database. None of the data created/committed in a test class is actually committed to the database. All data used in test classes is test data In order to test your code, you basically want to create transient (temporary) data and emulate however your class or trigger would be invoked. The test data should run through at lest 75% of the total lines of code by calling methods, providing multiple instance variables to run through if/else statements, loops, etc. You need 75% of your code covered to be able to push the trigger or class into production
  • #54: This is a sample test class for a trigger which is a little different than writing a test class for a class First you need to instantiate your test class. Notice how there is no direct association in the name or declaration to your actual trigger or class you’re testing. You just need the @isTest and static testMethod Then you need to create temporary data that will fire your trigger Then when you start the test (literally a method to start testing) You insert/update/delete (ie whatever should fire your trigger) and the test class will check how many lines of code your temporary data runs through without breaking Stop the test after doing all the necessary logic to run through the trigger appropriately And finally, at any point before, during, or after the start/stop test you can use an assert method to check what values are for instance variables at any instance It is best practice to run asserts where you think errors and to validate at the end of a test
  • #55: Here is a direct sample following that previous anatomy formula It works off of a conference management app, and basically checks against a trigger on the Session_Speaker__c object In this example it should fail because you shouldn’t be able to double book speakers
  • #56: You can run tests from the run tab in developer console… I like to show the test class for the workbook that they walk though. You can add arbitrary dummy functions to the OpportunityPageController like Public void dummyMethod(){ Integer x = 0; } Run test class again… go back to to the OpportunityPageController and show it no longer has 100% test coverage and explain why. Simple and easy to understand.