Post on 04-Jul-2015
description
transcript
Show FlowDreamforce 2104 Breakout Session Show Flow Template
Notes
Introduction to Development on Force.com
for Developers2hr 30min
Presentation Device:
Customer Speaker:
Demo Device
Deck Owner/Filename:
0:00 Doors open
0:00 Start
5 min 0:05 Welcome and Intros
3 min 0:08 Agenda and workbook
5 min 0:13 Platform Overview
5 min 0:18 Sign up for a DE
Please encourage all attendees to sign up for a new DE so they don’t run into any issues with disabled features or API naming issues
25 min 0:43 Writing an Apex ClassHere we only have slides, but feel free to show your own use case or demo if you have
one
17 min 1:00 Hands-On: Apex
15 min 1:15 SOQL and DML Demo using SOQL in the developer console. Build your own SOQL query and talk it out
15 min 1:30 Hands-On: SOQL/DML
20 min 1:50 Visualforce Demo Twitter bootstrap in VF/yelp demo or your own demo
15 min 2:05 Hands-On: Visualforce
10min 2:15 Controller Extensions
10 min 2:25 Hands-On: Controller Extensions
5 min 2:30 Q&A
There is a 30 minute turnaround time in the room, so the Q&A can extend this time if necessary. Also please encourage people to ask questions frequently throughout the day, and to utilize the helpers in the room.
Introduction to Development on Force.comFor Developers Samantha Ready, salesforce.com
Senior Developer Evangelist
@samantha_ready
Samantha ReadySenior 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.
Go Social!
@salesforcedevs
Salesforce Developers
+Salesforce Developers
Salesforce Developers
Salesforce Developers
Agenda
• Platform Overview
• Writing Apex Classes
• Accessing Data using SOQL
• Writing Triggers
• Writing Visualforce Pages
• Writing Controller Extensions
Extra Credit:
• Using the REST APIs
• Unit Testing
• Batching and Scheduling
bit.ly/df14-intro-force
Salesforce Platform is the Fastest Path from Idea to App
IdeaBuild App
Idea
buy &
setup
hardware
install
complex
software
define user
access
build & test
security
make it
mobile &
social
setup
reporting &
analytics
build
app
Traditional Platforms
6-12 Months?
App
App
Salesforce1 Platform Services
Salesforce1 Platform
Force.com Heroku Exact Target
Salesforce1 Platform APIs
Salesforce1 App
Sales
Cloud
Service
Cloud
Marketing
CloudAppExchange
Custom
Apps
Partner
Apps
Salesforce1 Mobile App
• Salesforce on your phone
• Customizable by
– Users
– Admins
– Developers
• Supports
– Objects
– Visualforce
– Canvas
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
The Conference AppWhat we’ll build…
• Manage sessions and speakers
• Automatically send confirmation emails
• Customized user interface with Visualforce Pages
• Upload speaker pictures
• Flickr integration (Apex) to show conference pictures
Free Developer Environment
http://developer.salesforce.com/signup
bit.ly/df14-intro-force
Lab 1: Install Your Developer Org
http://developer.salesforce.com/signup
Writing Apex Classes
What is Apex?
• Salesforce platform language
• Similar to Java
• Object-oriented
• Strongly typed
• Classes and Interfaces
• Cloud based compiling, debugging and unit testing
Apex and Java
Same
• Primitive data types
• Flow control (if, for, while, …)
• Exception handling
• Collections: Lists, Sets, …
Different
• Case insensitive
• Single quote strings: 'Joe'
• Id data type
• Built-in support for data access
Apex Class
public class MortgageCalculator {
}
public Double amount { get; set; }
public Double rate { get; set; }
public Integer years { get; set; }
public Double calculateMonthlyPayment() {
Integer months = years * 12;
Double monthlyRate = rate / (12 * 100);
return amount * (monthlyRate/
(1 - Math.pow(1 + monthlyRate, -months)));
}
Development Tools
• Developer Console
• Force.com IDE (Eclipse Plugin)
• Mavens Mate (Sublime Plugin)
• Force CLI
Developer Console
• Browser Based IDE
• Create Classes, Triggers, Pages
• Execute Apex Anonymously
• Execute SOQL Queries
• Run Unit Tests
• Review Debug Logs
Lab 4: Creating an Apex Class
• Create the EmailManager class
• Send emails from the developer console
Accessing Data with SOQL and DML
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
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
Demo: Executing SOQL in the Developer Console
Inlining SOQL in Apex
Integer i = [SELECT Count() FROM Session__c];
Inlining SOQL in Apex
String level = 'Advanced';
List<Session__c> sessions =
[SELECT Name, Level__c FROM Session__c
WHERE Level__c = :level];
Inlining SOQL in Apex
List<String> levels = new List<String>();
levels.add('Intermediate');
levels.add('Advanced');
List<Session__c> sessions =
[SELECT Name, Level__c FROM Session__c
WHERE Level__c IN :levels];
Inlining SOQL in Apex
for (Speaker__c s : [select email__c from Speaker__c])
{
System.debug(s.email__c);
}
What's DML?
• Data Manipulation Language
• Language used to create, update, delete records
insertSession__c session = new Session__c();
session.name = 'Apex 101';
session.level__c = 'Beginner';
insert session;
insertSession__c session = new Session__c(
name = 'Apex 201',
level__c = 'Intermediate'
);
insert session;
updateString oldName = 'Apex 101';
String newName = 'Apex for Beginners';
Session__c session =
[SELECT Id, Name FROM Session__c
WHERE Name=:oldName];
session.name = newName;
update session;
deleteString name = 'Testing 501';
Session__c session =
[SELECT Name FROM Session__c
WHERE Name=:name];
delete session;
Lab 5: Accessing Data using SOQL and DML
• Execute SOQL statements in the Query Editor
• Execute DML statements in the Anonymous Window
Writing Triggers
What's a Trigger?
• Apex code executed on database events
• Before or after:
– Insert
– Update
– Delete
– Undelete
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
Bulk Mode
• Trigger API is designed to support bulk operations
– Data Import, Bulk API, etc.
• Triggers work on bulk of records, not single records
• Context variables provide access to data:
– Trigger.old and Trigger.new (List)
– Trigger.oldMap and Trigger.newMap (Map)
Example 1trigger WelcomeKit on Account (after insert) {
List<Case> myCases = new List<Case>();
for (Account account : Trigger.new) {
Case welcomeCase = new Case();
welcomeCase.Subject = 'Mail Welcome Kit';
welcomeCase.AccountId = account.Id;
myCases.add(welcomeCase);
}
insert myCases;
}
Example 2
Trigger on Account (before update) {
for (Account acc: Trigger.New) {
// Compare new value with old value
if (acc.Rating != Trigger.oldMap.get(acc.Id).Rating) {
// Your Logic
}
}
}
Workflow vs Trigger
Workflow Trigger
Created with Clicks Code
What can it do • Update field
• Send email
• Create task
• Send outbound message
• Launch flow (flow trigger)
~ Anything (e.g.
create/delete records, REST
callout, etc.)
Cross-object field updates Limited (detail -> master) Any
Lab 6: Writing Triggers
• Write the SendConfirmationEmail trigger
• Write the RejectDoubleBooking trigger
Writing VisualforcePages
What's a Visualforce Page?
• HTML page with tags executed at the server-side to generate dynamic content
• Similar to JSP and ASP
• Can leverage JavaScript and CSS libraries
• The View in MVC architecture
Model-View-Controller
ModelData + Rules
ControllerView-Model
interactions
ViewUI code
Separation of concerns
– No data access code in view
– No view code in controller
Benefits
– Minimize impact of changes
– More reusable components
Model-View-Controller in Salesforce
View• Metadata
• Standard Pages
• Visualforce Pages
• External apps
Controller• Metadata
• Standard Controllers
• Controller Extensions
• Custom Controllers
Model• Metadata
• Objects
• Triggers (Apex)
• Classes (Apex)
Expression Language
• Anything inside of {! } is evaluated as an expression
– Dynamic variables: {!Contact.Phone} or {!myApexVariable}
– Logic: {! IF (Opportunity.Stage == ‘Closed/Won’, val_if_true, val_if_false)}
– Functions: {!JSENCODE(Account.BillingAddress)}
• Same expression language as Formulas
• $ provides access to global variables (User, Page, RemoteAction, Resource, …)
– {! $User.FirstName } {! $User.LastName }
Example 1<apex:page>
<h1>Hello, {!$User.FirstName}</h1>
</apex:page>
Example 2
<apex:page standardController="Contact">
<apex:form>
<apex:inputField value="{!contact.firstname}"/>
<apex:inputField value="{!contact.lastname}"/>
<apex:commandButton action="{!save}" value="Save"/>
</apex:form>
</apex:page> Function in
standard controller
Standard controller
object
Standard Controller
• A standard controller is available for all objects
– You don't have to write it!
– No test methods needed
– Can grab a single record or set of records
• Provides standard CRUD operations
– Create, Update, Delete, Field Access, etc.
• Can be extended with more capabilities (next module)
• Uses id query string parameter in URL to access object
Component Library
• Presentation tags
– <apex:pageBlock title="My Account Contacts">
• Fine grained data tags
– <apex:outputField value="{!contact.firstname}">
– <apex:inputField value="{!contact.firstname}">
• Coarse grained data tags
– <apex:detail>
– <apex:pageBlockTable>
• Action tags
– <apex:commandButton action="{!save}" >
Demo: Dissect a Visualforce Page & Build with Bootstrap
Templates
Embedded in Page
Layouts
Generate PDFs
Custom Tabs Mobile
Interfaces
Page Overrides
Where can I use Visualforce?
Lab 7: Writing Visualforce Pages
• Write the SpeakerForm Visualforce page
• Set it as default for creating and editing speakers
Writing Controller Extensions and Custom Controllers
What's a Controller Extension?
• Custom class written in Apex
• Works on the same object as the standard controller
• Can override standard controller behavior
• Can add new capabilities
Defining a Controller Extension
<apex:page standardController="Speaker__c"
extensions="SpeakerCtrlExt, ext2">
Provides basic
CRUD
Overrides standard
actions and/or provide
additional capabilities
Anatomy of a Controller Extensionpublic class SpeakerCtrlExt {
private final Speaker__c speaker;
private ApexPages.StandardController stdController;
public SpeakerCtrlExt (ApexPages.StandardController ctrl) {
this.stdController = ctrl;
this.speaker = (Speaker__c)ctrl.getRecord();
}
// method overrides
// custom methods
}
Demo: Dissect a Controller Extension
What's a Custom Controller?
• Custom class written in Apex
• Doesn't work on a specific object
• Provides custom data
• Provides custom behaviors
Defining a Custom Controller
<apex:page controller="FlickrController">
Custom Controller Example
public with sharing class FlickrController {
public FlickrList getPictures() {
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('http://api.flickr.com/services/feeds/');
HTTP http = new HTTP();
HTTPResponse res = http.send(req);
return (FlickrList) JSON.deserialize(res.getBody(),
FlickrList.class);
}
}
Lab 8: Writing a Controller Extension
• Write a Controller Extension that supports Picture Upload
Surveybit.ly/df-how-introforce
Samantha Ready
Senior Developer Evangelist
@samantha_ready
Certification Logos for “Speaker Intro Slides”
For salesforce.com
use only
Guides for logo placement
Column title Column title Column title Column title
0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00
Example of a TableTable subtitle
Column title Column title Column title Column title
0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00
Example of a TableTable style and coloring
Device Family Without Screens