Salesforce App Developer Guide: Version 15, Spring '19
Salesforce App Developer Guide: Version 15, Spring '19
Written by
Dianne Siebold
Samantha Ready
Michelle Chapman-Thurber
With contributions by
Michael Alderete
Cliff Armstrong
Jay Hurst
Dean Moses
Tammy Rahn
Samantha Reynard
Jim Sinai
Quinton Wall
Emily Wilska
  Discover both the declarative (point-and-click) and the programmatic (code-based)
  features of Salesforce. Learn how you can optimize existing features such as
  Visualforce pages and quick actions for the Salesforce mobile experience, as we
  walk you through the process of making an existing organization mobile-ready.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or
by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent
of the publisher.
CONTENTS
Chapter 1: Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Introducing the Salesforce Platform . .                             .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   2
Salesforce Platform Features . . . . . . .                          .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   2
Introducing the Salesforce App . . . . .                            .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   4
Getting Around in the Salesforce App .                              .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   4
What about the Other Mobile Apps? .                                 .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   9
   INDEX      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
CHAPTER 1                   Introduction
In this chapter ...          Mobile has become the new normal for staying connected in both our
                             personal and professional lives. More and more, we’re living our lives
•   Introducing the          connected to the Internet, but instead of sitting at a desk, we’re connecting
    Salesforce Platform      on planes, in cabs, in between meetings, in hotels, or even in line for coffee.
•   Salesforce Platform      We follow friends, update status feeds, research local businesses,
    Features                 collaborate with colleagues, email suppliers, and much more—all tasks
•   Introducing the          increasingly performed on the go.
    Salesforce App           And at the same time, every company is working harder and faster to
•   Getting Around in the    innovate and stay ahead of the competition. The successful businesses of
    Salesforce App           the future must embrace this mobile-first world and the freedom this
•   What about the           mobility provides to get things done, regardless of where you are and
    Other Mobile Apps?       what you’re doing.
                             Salesforce solves the problems of lagging innovation and a lack of mobile
                             specialists with a revolutionary approach to app development for the social
                             and mobile-first world. Salesforce delivers breakthrough productivity for
                             all users because it puts the customer—employees, partners, consumers,
                             and devices—at the center of everything.
                             The result is a fast, connected mobile solution with the potential to be as
                             disruptive as Software as a Service. It’s time to build the future today!
                                                1
Chapter 1 Introduction
    Social Data
    The ability to share, follow, collaborate, and take business actions directly on data within Salesforce is at
    the core of the platform. Users can follow records and data with a single tap. They can be notified of
    changes in real time, and collaborate directly within the record feed. This feed-based approach to working
    lets users focus on what’s most important to them.
    By treating data as social and as an important participant in business, Salesforce allows data to share
    updates, trigger workflows, and be part of the collaboration process with workers, teams, partners, and
                                                             2
                                                                                      Chapter 1 Introduction
customers. The result is an unparalleled opportunity to create new business apps and processes for business
productivity.
                                                   3
Chapter 1 Introduction
    The Feed
    The Chatter feed shows users their updates, updates to records and people they follow, and updates in
    groups they follow. Tapping a feed item displays all of the item’s details. Pulling down on the feed reveals
    the search bar (1), sort and filter options (2), the feeds drop-down menu (3), and feed items (4).
                                                            4
                                                                                     Chapter 1 Introduction
From the feed, record pages, and from elsewhere in Salesforce, users access actions from the action bar.
                                                  5
Chapter 1 Introduction
We’ll go over creating and customizing actions in Using Actions in the Salesforce App on page 45.
                                                            6
                                                                                     Chapter 1 Introduction
  1. Search box
  2. Menu items—any items you place above the Smart Search Items element when you customize
     the navigation menu
  3. Smart Search Items—includes a set of recently-searched objects in the Recent section and a larger
     set of supported objects under the More link
  4. Apps section—contains any items you place below the Smart Search Items element
From the navigation menu, users can access the feed, objects, apps, tasks, notes, and any other item you’ve
added to the menu. We’ll go over the components of the navigation menu in more detail in About the
Salesforce Navigation Menu on page 24. But for now, let’s take a look at records.
    At the top of each record page is the record highlights area. The icon for standard objects is predefined in
    Salesforce, and you can select the icon for a custom object using the custom object’s tab style.
    You can customize the fields displayed in the record highlights section by using compact layouts, which
    we’ll look at in About Compact Layouts on page 39.
                                                           8
                                                                                     Chapter 1 Introduction
                                                  9
CHAPTER 2                 About This Book
In this chapter ...        This book introduces you to both the declarative (point-and-click) and the
                           programmatic (code-based) features of Salesforce.
•   Who Is This Book
    For?
                           To help you get familiar with the different pieces that make up the
                           Salesforce Platform, and to show you how you can optimize existing
•   How Do I Begin?
                           features—such as Visualforce pages and actions—for the Salesforce mobile
•   About the Sample       experience, this book walks you through the process of enhancing an
    Scenario               existing organization to make it mobile-ready and mobile-friendly.
•   About Acme Wireless
                                            11
Chapter 2 About This Book
         Tip: Point-and-click admins, don’t let this deter you! We include code samples in most places, so
         even if you're not an experienced developer, you can still try the steps in each chapter and get a
         feeling for what can be done with Salesforce.
   How Do I Begin?
   It’s up to you! You could begin by pointing-and-clicking your way through Configuring the Salesforce App
   and working all the way through Using Actions in the Salesforce App. Then, put your developer hat on
   and create custom actions or add canvas apps to further enhance your users’ Salesforce experience.
   If you’re a seasoned developer, you could jump into the deep end first with the Welcome to Salesforce
   Platform Development chapter.
                                                              12
                                                                                 Chapter 2 About This Book
Acme Wireless is a large company that repairs devices such as mobile phones, tablets, and gaming consoles.
The company has a number of brick-and-mortar locations where customers can drop off devices for repair.
In addition, these storefronts sell device accessories like tablet covers, mobile phone covers, power cords,
rechargers, and so on.
Acme Wireless maintains a central warehouse where all the repair parts and accessories are stored. The
storefront locations order parts from the warehouse so that they can keep some inventory on hand. When
they need a special part that’s not in stock, storefronts can special order it from the warehouse.
Acme Wireless is also expanding its repair services by doing on-site service. Mobile technicians will go to
various customer locations to provide on-site service, including personal residences, hotels, small business
offices, and conference centers.
                                                  13
CHAPTER 3                  Setting Up Your Work Environment
In this chapter ...         To follow along with the exercises in this book, you’ll need a Salesforce
                            account and a Developer Edition organization. If you don’t have a Developer
•   Install the Enhanced    Edition organization, go to http://sforce.co/1om1gHf and sign
    Warehouse Data          up for a free Developer Edition account. Developer Edition is a fully
    Model                   functional version of Salesforce that you can use to develop Salesforce
•   Download Salesforce     apps. Since it’s free, there are limits on the amount of users, bandwidth,
                            and storage you’re allowed, but it includes all the features in Salesforce.
                            After that, you’ll need to install the enhanced Warehouse data model into
                            your organization, and then download Salesforce, if you haven’t already.
                                             15
Chapter 3    Setting Up Your Work Environment
     5. Click Install.
     6. Wait for the installation to finish.
     7. From the Lightning Platform app menu, select Warehouse.
     8. Click the Data tab.
     9. Click Create Data.
   All right! The last step is to download Salesforce, then we’ll be ready to roll.
   Download Salesforce
   If you’ve already downloaded Salesforce, you can skip this step.
     1. Go to www.salesforce.com/mobile/, and download Salesforce for your device.
         You may be prompted to create a security PIN.
     2. Open Salesforce.
     3. Log in using your developer organization credentials.
                                                            16
SALESFORCE APP ADMINISTRATION
                                              17
Chapter 4 Configuring the Salesforce App
    Downloadable Apps
    Salesforce for Android and Salesforce for iOS are connected apps. As a result, you can control the users
    who have access to the apps, as well as other security policies. By default, all users in your organization
    can log in to Salesforce for Android and iOS.
    You can control security and access policies for Salesforce for Android and Salesforce for iOS using settings
    components that are installed from the managed Salesforce connected apps package. These components
    need to be installed in Salesforce:
    • Salesforce for Android
    • Salesforce for iOS
    These components are automatically installed when one of your users installs Salesforce from the App
    Store or Google Play on a mobile device and authenticates with your organization by logging in to the
    mobile app.
    Alternatively, you can manually install the Salesforce and Chatter Apps connected apps package so you
    can review and modify the default security and access settings before rolling out Salesforce for Android
    and Salesforce for iOS to your users.
    When the Salesforce connected apps components are installed, they’re added to the Connected Apps
    page. (From Setup, enter Connected Apps in the Quick Find box, then select the option for
    managing connected apps.) Here, you can view and edit the settings for each of the apps, including
    controlling user access with profiles, permissions, and IP range restrictions. An error message is displayed
    if a restricted user attempts to log in to Salesforce for Android or Salesforce for iOS.
                                                           18
                                                                Chapter 4 Configuring the Salesforce App
When this option is turned on, users who log in to Salesforce from a supported mobile browser are
automatically directed to the Salesforce mobile web experience. Logging in from an unsupported mobile
browser loads the Salesforce Classic full site, even when this option is selected.
      Important: Use of the Salesforce Classic full site in a mobile browser isn’t supported. While you can
      disable Salesforce mobile web for your organization, and individual users can turn off mobile web
      for themselves, regular use of the full site in a mobile browser isn’t recommended. Your users may
      experience problems that Salesforce Customer Support won’t investigate.
      It’s not possible to access the Lightning Experience full site from any mobile browser.
About Notifications
Notifications let your users know when certain events occur in Salesforce. For example, notifications let
users know when they receive approval requests or when someone mentions them in Chatter.
These types of notifications can appear to Salesforce app users.
In-app notifications
    In-app notifications keep users aware of relevant activity while they’re using the Salesforce app. By
    tapping the notification bell, a user can view the 20 most recent notifications received within the last
    90 days.
    If Salesforce Communities is enabled for your organization, users see notifications from all of the
    communities they’re members of. To help users easily identify which community a notification came
    from, the community name is listed after the time stamp.
Push notifications
   Push notifications are alerts that appear on a mobile device when a user has installed the Salesforce
   for Android and Salesforce for iOS but isn’t using it. These alerts can consist of text, icons, and sounds,
   depending on the device type. If an administrator enables push notifications for your organization,
   users can choose individually whether to receive push notifications on their devices.
As the first task in our fresh new development organization, let’s set up notifications for all the Acme
Wireless mobile users.
                                                   19
Chapter 4 Configuring the Salesforce App
      1. From Setup, enter Connected Apps in the Quick Find box, then select Manage
         Connected Apps.
      2. If they’re not already selected, select both Enable in-app notifications and Enable push
         notifications.
      3. If you’re authorized to do so for your company, select Display full content push
          notifications.
      4. Click Save.
          Note: Enabling in-app notifications is an all-or-nothing process. Either they’re on for everyone, or
          off for everyone. Mobile users can’t customize, enable, or disable in-app notifications for themselves.
    Now that we’ve addressed notifications, let’s look at offline access in the app.
     Salesforce Data / Salesforce Available for Offline Viewing Available to Create, Edit, or
     App Element                                                Delete Offline (Beta)
     Navigation Menu                      Yes                                  n/a
                                                            20
                                                            Chapter 4 Configuring the Salesforce App
Salesforce Data / Salesforce Available for Offline Viewing Available to Create, Edit, or
App Element                                                Delete Offline (Beta)
Records for Recent Objects       Yes, recently accessed records for    Yes, recently accessed records for
                                 the first five objects (excluding     the first five objects (excluding
                                 Files) in the Recent section of the   Files) in the Recent section of the
                                 Salesforce app navigation menu        Salesforce app navigation menu
Records for Other Objects If viewed in current session If viewed in current session
Tasks                            Most recently accessed tasks from Most recently accessed tasks from
                                 the first page of My Tasks list only the first page of My Tasks list only
                                                                       (The simplified New Task form
                                                                       must be disabled)
Visualforce pages No No
                                              21
Chapter 4 Configuring the Salesforce App
     Salesforce Data / Salesforce Available for Offline Viewing Available to Create, Edit, or
     App Element                                                Delete Offline (Beta)
     Canvas Apps                        No                                  No
Lightning pages No No
    A Salesforce app session is the time between logging in and logging out of the app. Switching away from
    Salesforce app doesn’t end the session as long as the user doesn’t log out.
    All right! We’ve addressed notifications and offline access, now let’s look at the navigation menu.
                                                          22
CHAPTER 5                  Customizing the Salesforce App
                           Navigation Menu
In this chapter ...         Before you can send your users out on their mobile adventure, they need
                            a map to point the way to their destination.
•   About the Salesforce
    Navigation Menu
                            The Salesforce app navigation menu is that map. And it’s up to you to draw
                            it for them.
•   How the Navigation
    Menu Works              Help your mobile users get work done faster and more easily by configuring
                            which items appear in the navigation menu and in which order.
                                            23
Chapter 5 Customizing the Salesforce App Navigation Menu
    Canvas apps               Appears for organizations that have enabled a canvas app to appear in the
                              navigation menu.
Chatter The user’s main feed. Appears for organizations that have Chatter enabled.
    Dashboards                Availability depends on edition and user permissions. If you don’t add this
                              item to the navigation menu, dashboards are automatically included in the
                              set of Smart Search Items instead and the Dashboards item is available from
                              the Recent section.
    Events                    Lists events owned by the user, that the user created for him- or herself, and
                              that the user or a user’s groups are invited to. If you don’t add this item to the
                              navigation menu, events are automatically included in the set of Smart Search
                              Items instead and the Events item is available from the Recent section.
    Forecasts                 Displays the Forecasts app, a helpful tool for every member of a sales team to
                              keep track of forecast data and monitor progress towards quota. Available in
                              Salesforce for iOS only.
                                    Note: Your org must have Collaborative Forecasts enabled. If your org
                                    uses Customizable Forecasts, the Forecasts item isn’t available to add
                                    to the navigation menu.
    Groups                    Appears for organizations that have Chatter enabled. If you don’t add this
                              item to the navigation menu, groups are automatically included in the set of
                                                          24
                                         Chapter 5 Customizing the Salesforce App Navigation Menu
Lightning component       Only custom Lightning components that have a Lightning component tab
tabs                      associated with them can appear in the navigation menu.
News                      Displays the News app, a one-stop place for news and other insights about
                          the user’s accounts, contacts, leads, and opportunities.
Notes                     Displays the Notes app. If you don’t add this item to the navigation menu,
                          notes are automatically included in the set of Smart Search Items instead and
                          the Notes item is available from the Recent section.
Paused Flow Interviews Displays a list of flow interviews that the user paused. An interview is a running
                       instance of a flow. Users can tap an interview and resume or delete it. Available
                       in Salesforce mobile web only.
People                    Appears for organizations that have Chatter enabled. If you don’t add this
                          item to the navigation menu, profiles are automatically included in the set of
                          Smart Search Items instead and the People item is available from the Recent
                          section.
Reports                   Availability depends on edition and user permissions. If you don’t add this
                          item to the navigation menu, reports are automatically included in the set of
                          Smart Search Items instead and the Reports item is available from the Recent
                          section.
Smart Search Items        Adds standard and custom Salesforce objects to the Recent section in the
                          menu. This item also adds a set of the user’s recently accessed objects to the
                          Recent section and adds the More item so users can access all the objects
                          they have permission to use and that are supported. If you don’t include this
                          item in the navigation menu, users can’t access any objects on the navigation
                          menu.
                                 Note: Smart Search Items is required for users to get search results in
                                 Salesforce for Android. Users of Salesforce for iOS and the Salesforce
                                 mobile web are able to search for records if this option is omitted from
                                 the navigation menu.
                                                25
Chapter 5 Customizing the Salesforce App Navigation Menu
    Tasks                      Lists of a user’s open and closed tasks and tasks that have been delegated. If
                               you don’t add this item to the navigation menu, tasks are automatically
                               included in the set of Smart Search Items instead and the Tasks item is available
                               from the Recent section.
    Today                      An app that helps users plan for and manage their day by integrating mobile
                               calendar events with associated Salesforce tasks, accounts, and contacts. The
                               app also allows users to instantly join conference calls, quickly log notes about
                               events, and more. Available in Salesforce for Android and iOS only.
    Visualforce page tabs      Only Visualforce pages with the Available for Lightning
                               Experience, the Salesforce app, and Lightning
                               Communities checkbox selected will display in the Salesforce app.
    We won’t get into Visualforce pages in these exercises, but to learn more about them and how they work
    in Salesforce, see Extending the Salesforce App with Visualforce Pages on page 79.
                                                          26
                                         Chapter 5 Customizing the Salesforce App Navigation Menu
  2. Using the Up or Down arrows, arrange the top items in the Selected list like so:
      • Chatter
      • Today
      • Tasks
      • Smart Search Items
      • Dashboards
      Now whenever a mobile technician logs in to Salesforce, the Today page will be the first thing
      they see.
  3. Click Save.
Let’s go look at our changes.
                                                27
Chapter 5 Customizing the Salesforce App Navigation Menu
Now that we’ve addressed the navigation menu, let’s look at configuring our data for mobile.
                                                         28
                                           Chapter 5 Customizing the Salesforce App Navigation Menu
    elements below the scroll point if you put it near the top of the menu. Anything you put below the
    Smart Search Items element appears in the Apps section of the navigation menu.
• Before you can include Visualforce pages, Lightning pages, or Lightning components in the Salesforce
  app navigation menu, create tabs for them. From Setup, enter Tabs in the Quick Find box,
  then select Tabs.
• Anything represented by a tab in Salesforce—such as standard and custom objects, Visualforce pages,
  the Chatter feed, People, or Groups—is visible for a user in the Salesforce app menu, based on the
  user’s profile settings. For example, if a user is assigned to a profile that has the Groups tab set to Tab
  Hidden, the user won’t see the Groups menu item in the Salesforce app, even though an administrator
  has included it in the menu.
Some objects are excluded from the Recent section in the navigation menu, even if you accessed them
recently.
• People, groups, notes, dashboards, reports, tasks, and events, if these items were added directly to the
  navigation menu
• List views, which are shown only on object home pages, not in the navigation menu
• Objects that aren’t available in the Salesforce app, including any objects that don’t have a tab in the
  full Salesforce site
                                                   29
CHAPTER 6              Customizing How Your Data Shows
                       Up in the Salesforce App
In this chapter ...    We’ve done the basic configuration for the Salesforce app; now it’s time
                       to consider how we can optimize things in the full Salesforce site to give
•   How Page Layouts   our users the best possible mobile experience. First, we’ll customize how
    Work in the        our Salesforce data shows up when presented in a mobile context.
    Salesforce App
                       Two factors affect how information is displayed in the Salesforce app. One
•   About Compact
                       has been around for a while: page layouts. The other is newer: compact
    Layouts
                       layouts. You’ll learn about both in this chapter.
                                        31
Chapter 6 Customizing How Your Data Shows Up in the Salesforce App
              Note: In organizations that are created after Spring ’14, the Twitter component is added by
              default to the Mobile Cards section of page layouts for objects that support it.
    Actions
       Actions in the Salesforce Mobile and Lightning Experience Actions section of a page layout appear in
       the action bar and action menu on the object’s record pages.
    Here are the record detail page, related information page, and action menu for a sample account, Edge
    Communications:
                                                           32
                              Chapter 6 Customizing How Your Data Shows Up in the Salesforce App
We’ll cover actions in a later chapter. For now, let’s focus on record pages and mobile cards.
                                                  33
Chapter 6 Customizing How Your Data Shows Up in the Salesforce App
In the Salesforce app, the same account detail page looks like this:
    We only show three here, but there were five pages of scrolling, and that’s from a page layout with only
    32 fields! If you were a mobile user trying to find specific fields in a record detail with dozens of fields on
                                                             34
                                Chapter 6 Customizing How Your Data Shows Up in the Salesforce App
your phone, you’d have to scroll... and scroll... and scroll. It’s not the best user experience and it’s definitely
not good for your users’ productivity.
You have two options for handling page layouts for your mobile users: re-engineer your existing page
layouts, or create new page layouts that are mobile-friendly from the outset.
We’ll look at both options. First, we’ll walk through creating a fresh mobile-friendly page layout, then we’ll
discuss tips and tricks for optimizing existing long layouts for a mobile audience.
Try It Out: Create a Custom Page Layout for the Mobile Technicians
Profile
Users like the mobile technicians at Acme Wireless will spend the majority of their time accessing Salesforce
from a mobile device. We can create a streamlined, mobile-optimized page layout assigned to the Mobile
Technician profile, with only the items they need when on-site, and, voilà! Instant productivity boost.
In addition, using the specialized Mobile Cards section of the page layout, we can enhance the record’s
related information page by adding Visualforce pages and lookup cards.
  1. From the object management settings for accounts, go to Page Layouts.
  2. Click New.
  3. Leave the Existing Page Layout drop-down list set to –None–.
      We want to start with a clean slate for this page layout, so we’re choosing not to clone an existing
      page layout.
  4. Enter Account Mobile Technician Layout in the Page Layout Name field.
  5. Click Save.
      Required fields and “Always on Layout” fields are pre-populated onto the page layout. We just
      need to add a few more that are pertinent to the mobile technicians.
  6. Drag these fields from the palette into the Account Detail portion of the page, below the existing
     fields.
      • Shipping Address
      • Business Hours
      • Phone
  7. Click the Visualforce Pages category in the palette and drag Account Location into the Mobile
     Cards section.
                                                     35
Chapter 6 Customizing How Your Data Shows Up in the Salesforce App
         Account Location is a preconfigured Visualforce page that shows the user the location of the
         selected account on a Google map. In Salesforce, this will show up as a mobile card on the account
         record related information page.
     8. Click the Expanded Lookups category and drag Parent Account into the Mobile Cards
        section, above the Account Location mobile card.
         Parent Account is a lookup field, and putting it into the Mobile Cards section makes it display
         as a related lookup card on the account’s related information page.
     9. Click the Related Lists category and drag the Cases and Contacts related lists to the Related Lists
        section.
         Related lists show up on the record related information page in the Salesforce mobile app. When
         the mobile technicians navigate to an account’s related information page, they’ll see preview cards
         for the related lists that they can tap to get more information about the cases and contacts for
         that location.
                                               37
Chapter 6 Customizing How Your Data Shows Up in the Salesforce App
          Scroll down and you should also see the related lists that we added to the page layout. Tap a
          related list to see its details.
    Now that we’ve created this specialized page layout and added the fields our mobile technicians will need,
    their jobs will be much easier when they go on site. When they visit an account record’s related information
    page, they won’t have to shuffle through a long list of unnecessary fields to find the ones they really want.
    And, since we added the Visualforce page as a mobile card, they’ll be able to see the location of an account
    on a Google map.
    In the Actions chapter, we’ll enhance this page layout with special actions we’ve created just for our mobile
    technicians. But for now, let’s go over some recommendations for paring down existing page layouts to
    make them more mobile friendly.
                                                           38
                              Chapter 6 Customizing How Your Data Shows Up in the Salesforce App
• What are the important moments for your users when they’re working in the Salesforce mobile app?
• What actions or processes can you automate so that your users don’t have to manually do them?
                                                 39
Chapter 6 Customizing How Your Data Shows Up in the Salesforce App
    In the Salesforce mobile app, the first four fields that you assign to a compact layout appear in:
    • An object record’s highlights area
    • Expanded lookup cards on a record’s related information page
    If a user doesn’t have access to one of the fields that you assign to a compact layout, the next field on the
    layout is used.
    The first four fields you assign to your compact layout populate the record highlights section at the top
    of each record view in the Salesforce app, so we’ll put the fields we think our mobile technicians most
    want to see into the list.
    Creating and customizing compact layouts for objects isn't required for the Salesforce app, because system
    defaults are provided out of the box. However, we recommend using compact layouts to put important
    fields into object record headers—and elsewhere—to help your mobile users get the information they
    need quickly. Let’s give it a try.
                                                           40
                            Chapter 6 Customizing How Your Data Shows Up in the Salesforce App
Currently, the Merchandise object uses its system default compact layout, which only has the
Merchandise Name field assigned. Here’s what our iPhone 6 record looks like:
Let’s add more fields alongside that “iPhone6” so our mobile users can see more pertinent information
right at the top of the Merchandise record pages.
 1. Navigate to the Merchandise custom object in Setup. From the Compact Layouts related list, click
    New.
 2. In the Label field, enter Customized Compact Layout.
 3. Select these fields for the compact layout, and then click Add.
     When on site, these are the most important fields for our mobile technicians to see. You can select
     and add them individually or select them as a group using CTRL-click.
     • Condition
     • Merchandise Name
     • Price
     • Quantity
                                                41
Chapter 6 Customizing How Your Data Shows Up in the Salesforce App
      4. Using the Up or Down buttons, adjust the list so that the fields are in this order: Merchandise
         Name, Quantity, Condition, Price.
      5. Click Save.
         Now we need to set our compact layout as the primary.
      6. Click Compact Layout Assignment.
         You can see that the primary compact layout is set to the System Default here. We need to change
         that.
      7. Click Edit Assignment.
      8. Select the compact layout you just created to use as the primary compact layout.
      9. Click Save.
    We’ve customized a compact layout for the Merchandise object. Now let’s see what its related information
    page looks like.
                                                          42
                              Chapter 6 Customizing How Your Data Shows Up in the Salesforce App
As you can see, the record highlights area has the fields from our newly-created custom compact layout.
Instead of seeing just the merchandise name, as on the system default layout, the Acme Wireless mobile
technicians can now see much more: that there are ten refurbished iPhone 6s in stock at the warehouse,
and they cost $599.00 each.
                                                  43
Chapter 6 Customizing How Your Data Shows Up in the Salesforce App
    Removing a field from a page layout doesn’t remove it from the object’s compact layout. The two layout
    types are independent.
    Fields that aren’t available in the SOAP API don’t show up on compact layouts in the Salesforce app.
                                                         44
CHAPTER 7                  Using Actions in the Salesforce App
In this chapter ...         As an administrator, you can enable valuable micro-moments for all of
                            your users by creating unique actions. When thinking about what actions
•   Quick Actions           you might want to create specifically for the Salesforce app, ask your users
•   Point and Click Your    what they wish they could do in the mobile context.
    Way to Actions
                            For example, an administrator at a food service company could create an
•   About Action Layouts    "Emergency Order" action that allows their delivery drivers to immediately
•   About Predefined        order extra or missing food items using their mobile phone while still at a
    Values in Actions       customer site. Creating actions for the Salesforce app can drive adoption
•   About Custom            in your organization and make you a hero to your users!
    Actions                 In this chapter, we’ll learn about types and categories of actions, how to
                            create and customize them in Salesforce using point-and-click tools, and
                            how they can help mobile users get essential work done while away from
                            the office.
                                             45
Chapter 7 Using Actions in the Salesforce App
    Quick Actions
    Create quick actions, and add them to your Salesforce Classic home page, to the Chatter tab, to Chatter
    groups, and to record detail pages. Choose from standard quick actions, such as create and update actions,
    or create custom actions based on your company’s needs. In addition, actions have their own action
    layouts, which let you specify which fields are included in the action, and in which order.
    Actions also appear in an action bar on list items such as task lists and related record lists. This gives your
    mobile users the ability to work with records directly from lists and update records without having to open
    them. To access list item actions, navigate to the task list or open a related list from an object’s related
    information page. Then swipe left on the desired record.
                                                            46
                                                           Chapter 7 Using Actions in the Salesforce App
new contact is associated with Acme. You can only add an object-specific action to page layouts for that
object.
      Note: Actions to create records for an object that is the detail object in a master-detail relationship
      must be object-specific, not global.
                                                  47
Chapter 7 Using Actions in the Salesforce App
    For create, log-a-call, and custom actions—which we’ll go over at the end of this chapter—you can create
    either object-specific quick actions or global quick actions. Update actions must be object-specific.
    For a list of supported objects for object-specific and global actions, see "Object-Specific Actions" and
    "Global Quick Actions" in Salesforce Help.
    Action Categories
    Actions fall into several different categories. What you see depends on the age and configuration of your
    org.
    Standard Chatter actions
       Standard Chatter actions are actions that are included automatically when Chatter is enabled: Post,
       File, Link, Poll, and, in orgs that use work.com, Thanks. Standard actions can also include any actions
       that you created for your org using point-and-click methods, such as create or Log A Call actions.
    Default actions
       Default actions are sets of predefined actions to get you and your users started using actions in your
       org. Add default actions to publisher layouts to make them available to your users in the full Salesforce
       site and the action bar in the Salesforce mobile app. Default actions are sets of predefined actions to
       get you and your users started using actions in your org.
        Because our Development org is new, it contains a set of default actions. You can check out the default
        global actions: From Setup, enter Global Actions in the Quick Find box, then select Global
        Actions.
        For a list of which default actions appear on which object, see “Default Actions” in the Salesforce Help.
    Mobile smart actions
      Mobile smart actions are a set of preconfigured actions and are supported on the same list of objects
      as default actions. However, they appear in orgs created before Winter ’14 and are displayed only in
      the Salesforce app.
        Mobile smart actions appear as a single action element in the page layout editor. In the Salesforce
        mobile app, the Mobile Smart Actions element expands to distinct create actions that enable users to
        create records directly from the action bar.
                                                           48
                                                             Chapter 7 Using Actions in the Salesforce App
    Mobile smart actions are populated with all your org’s required fields on the relevant object, regardless
    of how many fields there are. For example, the New Case action in the mobile smart action bundle
    includes all required case fields. You can’t edit the fields on mobile smart actions. The fields that appear
    change only if you change which fields on an object are required.
    Mobile smart actions don’t appear in the full Salesforce site, regardless of which page layouts you add
    them to. They appear only to users in the Salesforce mobile app.
    For a list of what the mobile smart action element on each supported object expands to include, see
    “Mobile Smart Actions” in the Salesforce Help.
Custom quick actions
   Custom quick actions are actions that you create and customize, such as Create a Record, Send Email,
   or Log a Call actions. Quick actions can also invoke Lightning components, flows, Visualforce pages,
   or canvas apps with functionality that you define. For example, you can create an action so that users
   can write comments that are longer than 5,000 characters. Or, you can create an action that integrates
   a video-conferencing application so that support agents can communicate visually with customers.
    We’ll touch briefly on custom actions later in About Custom Actions, but you can find out much more
    about them in the Adding Functionality with Visualforce Custom Actions chapter.
Productivity Actions
   Productivity actions are predefined and attached to a limited set of objects. Productivity actions include
   Send Email, Call, Map, View Website, and Read News. Except for the Call action, you can’t edit or delete
   productivity actions.
                                                    49
Chapter 7 Using Actions in the Salesforce App
      3. In the Salesforce Mobile and Lightning Experience Actions section, click override the predefined
         actions.
                Tip: If you haven’t customized the Salesforce Mobile and Lightning Experience Actions
                section of a page layout, the actions for that object default to a set of predefined actions.
                If you have customized actions in the Quick Actions in the Salesforce Classic Publisher
                section, and have saved the layout, the Salesforce Mobile and Lightning Experience Actions
                section inherits the actions from the Quick Actions in the Salesforce Classic Publisher
                section, plus any standard or custom buttons present on the layout, when you click to
                override.
                                                           50
                                                           Chapter 7 Using Actions in the Salesforce App
  4. Click the Mobile & Lightning Actions category in the palette and then adjust the actions in the
     Salesforce Mobile and Lightning Experience Actions section to match this list.
      • Create a Case
      • Log a Call
      • New Contact
      • New Opportunity
      • New Task
      • Post
      • File
      Because the Create a Case action is important to the mobile technicians, we put it first in the list
      so that they can access it directly from the action bar.
      Notice there’s also a New Case item in the palette. The New Case item is a global default action
      associated with the Account object. We’re going to customize our object-oriented Create a Case
      action, so we don’t need the redundant global action.
            Tip: On object page layouts, the Mobile & Lightning Actions category contains all available
            types of actions for the object, including quick actions, productivity actions, Lightning
            component actions, and standard and custom buttons.
  5. Click Save.
Our new Create a Case action appears in the action bar on account records in the Salesforce mobile app
for all the mobile technicians.
Now that’s all done, let’s go over global actions. Then we’ll revisit action layouts and customize our Create
a Case action.
                                                  51
Chapter 7 Using Actions in the Salesforce App
    • You can remove a required field from the action layout, but make sure that the field has a predefined
      value. Otherwise, users can’t create records.
    For more tips, see Action Guidelines and Best Practices on page 64.
When you create an action, Salesforce populates its layout with a default set of fields. You can add, remove,
or reorder fields on the action layout to present only the essential items your users need when they’re
taking the action.
The upper part of the action layout editor is the palette, and below the palette is the action layout. The
palette contains fields from the action’s target object that you can add to the action layout, except for the
following unsupported field types:
• Record type fields
• Read-only field types such as roll-up summary, formula, and auto-number fields
• Read-only system fields such as Created By or Last Modified By
Inactive Fields
   Fields that are already on the action layout still appear on the palette but are inactive. When you select
   an inactive field on the palette, Salesforce highlights the field on the action layout.
Field Type Conversion
    If you convert a field’s type from one that is supported for actions to a type that isn’t supported,
    Salesforce removes the field from the action layout. If you convert the field back to a supported type
                                                  53
Chapter 7 Using Actions in the Salesforce App
        without changing the action layout, Salesforce automatically adds the field back to the layout. If you
        edit the layout, and then convert the field back to a supported type, add the field back to the layout
        manually.
    Layouts Used for Log a Call Actions
       A Log a Call action takes the active task page layout except under the following conditions:
        • Suppose that your organization has a custom Log a Call action for an object. The custom action
          takes the custom action layout defined for it.
        • Now suppose that your organization has a custom Log a Call global action. That action takes the
          custom layout defined for it, unless you also have a custom Log a Call action for an object. (A
          custom action on an object overrides a custom global action.)
        To display the simpler New Task form to Salesforce mobile app users, enable the form in Activity
        Settings and ensure that the layout used includes a subject field.
    Layout Auditing
       Salesforce tracks action layout customization in the setup audit trail history.
                                                            54
                                                          Chapter 7 Using Actions in the Salesforce App
  5. Click Save.
Now when the Acme Wireless mobile technicians view an account in the Salesforce app, they can create
a case from any account record page. Let’s give it a try.
                                                 55
Chapter 7 Using Actions in the Salesforce App
                                                          56
                                                           Chapter 7 Using Actions in the Salesforce App
Nice work!
                                                  57
Chapter 7 Using Actions in the Salesforce App
    create through that action are automatically assigned to the prospecting stage. You can remove the Stage
    field from the action’s layout, because the field is going to be assigned a value automatically.
    You can set predefined values for any field available in the action layout editor, with these exceptions.
    • Multi-select picklists
    • Read-only field types like auto-number, formula, and roll-up summary fields
    Predefined values for fields on actions are different from default values that you can set for fields on records.
    If a field is included in an action, it can have both a predefined value set for the action and a default value
    set. If a field on an action has both a predefined value and a default value set, the action uses the predefined
    value, not the default value.
    Let’s set a predefined value for one of the fields on our Create a Case action.
                 Tip: You can remove a required field from the action layout, but make sure that the field
                 has a predefined value. Otherwise, users can’t create records.
      9. Click Save.
    OK, now let’s see it in action.
                                                             58
                                                           Chapter 7 Using Actions in the Salesforce App
                                                 59
Chapter 7 Using Actions in the Salesforce App
    All right! We’re almost done with actions. There’s one more type, custom actions, that we’ll go over briefly
    for now.
                                                           60
                                                         Chapter 7 Using Actions in the Salesforce App
We can’t create custom actions with point-and-click, so we won’t be working with them in our administrator
exercises. If you want to find out more about custom actions, see Adding Functionality with Visualforce
Custom Actions on page 93.
                                                 61
CHAPTER 8                 Guidelines and Best Practices for
                          Administrators
In this chapter ...        We’ve covered the primary places you can use point-and-click tools to
                           optimize your organization for your mobile users. We enabled notifications,
•   Action Guidelines      created page layouts and compact layouts, set up quick actions, and
    and Best Practices     customized the navigation menu.
•   Custom Icon
                           In this chapter, we’ll cover some suggestions and best practices for actions
    Guidelines and Best
                           and custom icons that can make your mobile users’ experience that much
    Practices
                           better. And in case you missed it, don’t forget to review the page layout
                           guidelines in Tips for Optimizing Page Layouts for Mobile on page 38.
                                            63
Chapter 8 Guidelines and Best Practices for Administrators
    • Create a global action if you're contemplating something that your users need to do that isn't tied to
      a specific object and that you want to be accessible from anywhere.
    • Use the Description field to create notes for yourself about each action. Notes are especially
      useful if you’re creating several similar actions for different record types, for example. The description
      appears in the list of buttons, links, and actions for object-specific actions, or in the list of global actions,
      as well as on the detail page for the action. Your notes aren’t visible to users.
    • There is no hard limit to the number of fields you can add to an action layout. However, for optimum
      usability, we recommend a maximum of 8 fields. Adding more than 20 fields can severely impact user
      efficiency. To reduce the number of fields in your layout, you can create predefined values for the
      required fields, and then remove those fields from your layout. You can set predefined field values
      from the action detail page.
                                                              64
                                               Chapter 8 Guidelines and Best Practices for Administrators
                                                   65
DEVELOPING FOR THE SALESFORCE APP
                                             67
Chapter 9 Welcome to Salesforce Platform Development
    Our Scenario
    We’ll continue the business scenario of Acme Wireless and build functionality to meet the needs of their
    mobile technicians and warehouse workers.
    You’ll learn how to:
    • Optimize the mobile experience for users by employing mobile-first user interface design.
    • Implement Visualforce pages so that mobile users can access them from the navigation menu or action
      bar, from a record, or from the publisher in the full Salesforce site.
    • Create a Visualforce custom action to make a Visualforce page available from the action bar or from
      the publisher in the full Salesforce site.
    • Implement development best practices when extending the Salesforce app.
                                                          68
                                                Chapter 9 Welcome to Salesforce Platform Development
Salesforce Platform
• Defined user interface.
• Full access to Salesforce data.
• Possible integrated experience in the Salesforce app.
• Inclusion of your own apps and functionality with quick actions.
• Customized with point-and-click or programmatic tools.
                                                  69
Chapter 9 Welcome to Salesforce Platform Development
    • Programmatic functionality through Visualforce pages, Canvas apps, and the Lightning Component
      framework.
    • Defined navigation points, since customizations or apps adhere to the navigation menu. For example,
      a Visualforce page can be called from the navigation menu or from a custom action in the action bar.
    • Enables you to leverage existing Salesforce development experience, both point-and-click and
      programmatic.
    • Included in all Salesforce editions and supported by Salesforce.
    Custom Apps
    Custom apps can be either free-standing apps you create with Salesforce Mobile SDK or browser apps
    using plain HTML5, CSS, and your choice of mobile-friendly JavaScript frameworks. With custom apps, you
    can have:
    • A custom user experience.
    • Access to Salesforce data using REST APIs in native and hybrid local apps, or with Visualforce in hybrid
      apps using JavaScript Remoting. In HTML5 apps, do the same using standard JavaScript APIs.
    • A branded user interface, including a custom app icon, for increased exposure in customer-facing
      apps.
    • Standalone mobile app, either with native APIs using Java for Android or Objective-C for iOS, or through
      a hybrid container using JavaScript and HTML5 (Mobile SDK only).
    • App distribution through mobile industry channels, such as the Apple App Store or Google Play (Mobile
      SDK only).
    • Control of complex offline behavior (Mobile SDK only).
    • Push notifications (available for Mobile SDK native apps only).
    • A custom security container using your own OAuth module (Mobile SDK only).
    Other important Mobile SDK considerations:
    • Access to open-source SDK, downloadable for free through npm installers and GitHub. No licensing
      required.
    • Requires you to develop and compile your apps in an external development environment (Xcode for
      iOS, Eclipse or similar for Android).
    There’s no right or wrong answer when choosing between the Salesforce platform and the Mobile SDK.
    Base your choice on which features are most important for your app.
                                                          70
                                               Chapter 9 Welcome to Salesforce Platform Development
      Important: Running the Salesforce app in an emulator isn’t supported for normal use, and it’s not
      a substitute for full testing of your custom apps and pages on your organization’s supported mobile
      devices. During development you should regularly test your app on every device and platform on
      which you intend to deploy.
To view your custom mobile pages and apps on a device emulator, download and install the appropriate
SDK for your supported devices.
• Apple iOS Simulator for iPhone and iPad
    developer.apple.com/library/ios/documentation/IDEs/
    Conceptual/iOS_Simulator_Guide/
Development Prerequisites
You’ll need to have these before you can start these exercises.
• Access to a Developer Edition organization.
    If you aren’t already a member of the Lightning Platform developer community, go to
    http://sforce.co/1om1gHf and follow the instructions for signing up for a Developer Edition
    organization. Even if you already have Enterprise Edition, Unlimited Edition, or Performance Edition,
    use Developer Edition for developing, staging, and testing your solutions against sample data to protect
    your organization’s live data.
• The “API Enabled” permission must be enabled for your Developer Edition organization. This permission
  is enabled by default, but might have been changed by an administrator.
                                                  71
Chapter 9 Welcome to Salesforce Platform Development
    • The Warehouse data model must be installed in your Developer Edition organization and the Salesforce
      app installed on a mobile device. If you haven’t already set up these items, see Setting Up Your Work
      Environment on page 15.
                                                         72
CHAPTER 10 Designing Mobile-First User Interfaces
In this chapter ...      In this chapter, we’ll learn about user interface design considerations to
                         keep in mind when developing functionality for Salesforce mobile users.
•   Design for Mobile
                         Designing your user interface with mobile in mind is critical to the success
•   Keep Navigation
                         of your app. If users find your functionality easy to use and in alignment
    Simple
                         with the experience they have with other mobile apps, they’ll be much
•   Put Important        happier with the app. The user interface guidelines in this chapter address
    Information at the   key differences in the mobile platform and the way users work in it:
    Top
                         • Mobile devices have smaller screens.
•   Minimize the
    Number of Fields     • Navigation is done with gestures like tapping and swiping.
•   Use Field Defaults   • Users typically perform focused tasks from mobile devices like adding
•   Minimize User          a new record.
    Interface Text       Throughout the examples in this book, we demonstrate these best
•   Tap Target Size      practices. As you develop and create your own customizations and apps
                         using the Salesforce Platform, keep these guidelines in mind.
                                          73
Chapter 10 Designing Mobile-First User Interfaces
                                                           74
                                                       Chapter 10 Designing Mobile-First User Interfaces
                                                  75
Chapter 10 Designing Mobile-First User Interfaces
    To reduce the number of fields on a screen, consider using default values for new records instead of having
    the user enter the data.
                                                           76
                                                         Chapter 10 Designing Mobile-First User Interfaces
your user interface. The goal with user interface text is to provide enough information so that users can
understand what they need to do while at the same time keeping the user interface clean and simple.
A common best practice is to place labels above fields and to show only one column of fields instead of
displaying fields side by side.
Any blocks of text should also be concise and to the point. For example, if you’re automatically creating a
feed item to be viewed, keep the text short and include only the necessary information.
In our warehouse scenario, when an order is fulfilled in the warehouse, a feed item appears in the customer
account feed that shows the key information such as invoice number and order number, along with a
short message and a link to the invoice.
                                                   77
Chapter 10 Designing Mobile-First User Interfaces
    Screen controls should be large enough for users to tap easily and take into account that every user’s hands
    are sized differently. Controls that are too small means users will need to tap multiple times, a frustrating
    experience. But you don’t want controls so large that users can accidentally tap one when they meant to
    tap another.
    We recommend a minimum tap target size of 44 pixels wide by 44 pixels high. For more information about
    custom icons, see Custom Icon Guidelines and Best Practices on page 64.
                                                           78
CHAPTER 11 Extending the Salesforce App with
           Visualforce Pages
In this chapter ...        You can use Visualforce to extend the Salesforce app and give your mobile
                           users the functionality they need.
•   Try It Out: Create a
    Visualforce Page
                           In this chapter, we’ll extend the Acme Wireless organization and give
                           mobile technicians a way to find nearby warehouses. For example, if the
•   Tell Me More: Where
                           technician is out on a call and needs a part, they can use this page to look
    Visualforce Pages
                           for warehouses within a 20–mile radius.
    Can Appear in the
    Salesforce App         While you could take an existing Visualforce page and surface it in the
•   Tell Me More: About    Salesforce app, you should consider how that page will look and function
    the Code               on a mobile device. Most likely, you’ll want to create a new page designed
                           especially for a mobile experience.
                           For more information about where Visualforce pages can appear in the
                           user interface, see Tell Me More: Where Visualforce Pages Can Appear in
                           the Salesforce App on page 86.
                           Now, let’s get started!
                                            79
Chapter 11 Extending the Salesforce App with Visualforce Pages
      5. Copy and paste this code into the Visualforce Markup tab.
          <apex:page sidebar="false" showheader="false"
              standardController="Warehouse__c"
              recordSetVar="warehouses" extensions="FindNearby">
                                                         80
                Chapter 11 Extending the Salesforce App with Visualforce Pages
</script>
<!-- Set up the map to take up the whole window -->
<style>
    html, body { height: 100%; }
    .page-map, .ui-content, #map-canvas
        { width: 100%; height:100%; padding: 0; }
    #map-canvas { height: min-height: 100%; }
</style>
<script>
    function initialize() {
        var lat, lon;
                     lat, lon,
                     function(result, event){
                         if (event.status) {
                             console.log(result);
                             createMap(lat, lon, result);
                         } else if (event.type ===
                             'exception') {
                             //exception case code
                         } else {
                         }
                      },
                      {escape: true}
                 );
             });
         } else {
         //Set default values for map if the device
                         81
Chapter 11 Extending the Salesforce App with Visualforce Pages
                         function setupMarker(){
                             var content='<a href src="/'+ warehouse.Id +
                                 '" >'+
                                 warehouse.Name + '</a><br/>'+
                                 warehouse.Street_Address__c +
                                 '<br/>' + warehouse.City__c +
                                 '<br/>' + warehouse.Phone__c;
                                                  82
                                       Chapter 11 Extending the Salesforce App with Visualforce Pages
});
</script>
  6. Click Save.
Now that we’ve created the Visualforce page for finding warehouses, the next step is to create a tab for it.
We’ll then add the page to the navigation menu.
                                                   83
Chapter 11 Extending the Salesforce App with Visualforce Pages
      5. Click into the Tab Style field, and select the Globe style.
          The icon for this style appears as the icon for the page in the navigation menu.
      6. Click Next.
      7. Click Next to accept the visibility defaults.
      8. Deselect the Include Tab checkbox so that the tab isn’t included in any of the apps in the
         organization. We only want this tab to appear when users are viewing it on their mobile device.
      9. Click Save.
    Now that you’ve created the Visualforce page and the tab, you’re ready to add the new tab to the navigation
    menu.
                                                           84
                                     Chapter 11 Extending the Salesforce App with Visualforce Pages
3. Move the Find Warehouses item to just below the Smart Search Items menu item.
           Note: Menu items that you put below Smart Search Items appear in the Apps section of
           the Salesforce navigation menu.
 4. Click Save.
When your users log in, they’ll see the Find Warehouses menu item in the navigation menu. Now let’s test
it out.
                                                85
Chapter 11 Extending the Salesforce App with Visualforce Pages
          The warehouses in our package sample data are all located in the San Francisco area. If you’re
          testing this from another location, be sure to add a warehouse located within 20 miles. To add a
          new warehouse, choose Warehouse from the Lightning Platform app menu, click the Warehouses
          tab, and then click New in the Recent Warehouses section.
    That’s it! You can see how easy it is to make standard pages and tabs available to your mobile users.
    For more information about development guidelines for Visualforce pages, see Guidelines and Best Practices
    on page 108.
                                                           86
                                   Chapter 11 Extending the Salesforce App with Visualforce Pages
• Action bar and action menu—available from the bottom of any page that supports actions
                                            87
Chapter 11 Extending the Salesforce App with Visualforce Pages
• Record related information page (as a mobile card)—available when you navigate to a record
    You can also reference, and link to, another Visualforce page in your Visualforce markup using the supported
    navigation calls listed at Navigation with the sforce.one Object. Be sure to select Available
    for Lightning Experience, Lightning Communities, and the mobile app
    for all pages in a multi-page process.
    If a referenced page doesn’t have Available for Lightning Experience, Lightning
     Communities, and the mobile app selected, it doesn’t prevent the referencing, or parent,
    page from appearing. However, when a user tries to access the nonmobile enabled page, they receive an
    “Unsupported Page” error message.
                                                           88
                                       Chapter 11 Extending the Salesforce App with Visualforce Pages
                                                  89
Chapter 11 Extending the Salesforce App with Visualforce Pages
                              function(result, event){
                                  if (event.status) {
                                      console.log(result);
                                      createMap(lat, lon, result);
                                  } else if (event.type === 'exception') {
                                      //exception case code
                                  } else {
                                  }
                              },
                              {escape: true}
                   );
               });
           } else {
           //Set default values for map if the device doesn't
           //have geolocation capabilities
                /** San Francisco **/
                lat = 37.77493;
                lon = -122.419416;
                                                            90
                        Chapter 11 Extending the Salesforce App with Visualforce Pages
    console.log(err);
    warehouseNavUrl = '\\' + warehouse.Id;
}
    var warehouseDetails =
        '<a href="' + warehouseNavUrl + '">' +
        warehouse.Name + '</a><br/>' +
        warehouse.Street_Address__c + '<br/>' +
        warehouse.City__c + '<br/>' +
        warehouse.Phone__c;
                                 91
CHAPTER 12 Adding Functionality with Visualforce
           Custom Actions
In this chapter ...        Actions appear in the action bar and action menu in the Salesforce mobile
                           app, and are a quick way for mobile users to access commonly used tasks
•   Custom Actions         or functionality.
    Scenario
                           We learned about standard actions that can be configured with
•   Try It Out: Create a
                           point-and-click tools in Using Actions in the Salesforce App on page 45.
    Visualforce Custom
                           In this chapter we’ll look at custom actions, which are actions that you
    Action
                           define. There are two types of custom actions:
•   Tell Me More: About
    the Code               • Visualforce—specifies a Visualforce page that’s called from the Chatter
                             publisher or the Salesforce app action bar.
                           • Canvas—specifies a canvas app that’s called from the Chatter publisher
                             or the Salesforce app action bar.
                           Custom actions aren’t specific to mobile users, and appear in both the
                           Salesforce app and in the full Salesforce site. In the Salesforce mobile app,
                           custom actions appear in the action bar. In the full Salesforce site, custom
                           actions appear in the Chatter publisher.
                                            93
Chapter 12 Adding Functionality with Visualforce Custom Actions
                                                            94
                                      Chapter 12 Adding Functionality with Visualforce Custom Actions
  6. Click Save.
Now that we’ve created the custom action, we’ll add the action to the Account page layout. This ensures
that the custom action appears in the publisher when you go to the page for a customer account.
  6. If it’s present, drag the Mobile Smart Actions element out of the section and back to the palette.
  7. Click Save.
Now that we’ve created the custom action and added it to the page layout, we’re ready to see it in action.
                                                  95
Chapter 12 Adding Functionality with Visualforce Custom Actions
      6. In the Merchandise Name field, enter the name of an item, such as iPhone 5.
      7. In the Max Delivery Distance (miles) field, enter 10.
      8. Tap Submit.
                                                         96
                                     Chapter 12 Adding Functionality with Visualforce Custom Actions
 9. In the Search Results section at the bottom, you’ll see a list of merchandise that matches what you
    searched for. The list shows parts contained in warehouses within 10 miles of the current account.
    Tap iPhone 5S Gold.
 10. In the Quantity field, enter 1.
     After identifying nearby warehouses that contain the part you’re looking for, this screen lets you
     enter a quantity and creates an order for the part. The order is associated with the current account.
           Tip: If you want to return to the search screen, be sure to use the Back button. If you tap
           Cancel, an invoice with no line items is created.
Success! You’ve gone through the entire process of enabling a mobile technician to quickly search for a
part in a warehouse and create an order.
                                                 97
Chapter 12 Adding Functionality with Visualforce Custom Actions
    For more information about development guidelines for Visualforce pages, see Guidelines and Best Practices
    on page 108.
           public QuickOrderController(ApexPages.
               StandardController controller){
           }
           @RemoteAction
           global static List<Merchandise__c> findWarehouses(String accId,
               String merchName, String warehouseDist){
                merchandise = new List<Merchandise__c>();
                String queryString = '';
                                                           98
               Chapter 12 Adding Functionality with Visualforce Custom Actions
        Warehouse__r.Name, Warehouse__r.Id,
        Warehouse__r.Street_Address__c,
        Warehouse__r.City__c '+
        'FROM Merchandise__r WHERE Name
        like :queryName) '
        +'FROM Warehouse__c WHERE '
        +'DISTANCE(Location__c, GEOLOCATION('
        +acc.Location__Latitude__s+','
        +acc.Location__Longitude__s+'), \'mi\')';
    if(warehouseDist != null){
        queryString += ' <'+ warehouseDist;
    }
}
//If no location defined on the Account, this will run
//query against the merchandise name only
else {
    queryString = 'SELECT Id, Name,
        Location__Longitude__s,
        Location__Latitude__s, '
        +'(SELECT Id, Name, Warehouse__r.Name,
        Quantity__c
        FROM Merchandise__r WHERE Name
        like :queryName) '
        +'FROM Warehouse__c limit 25';
                        99
Chapter 12 Adding Functionality with Visualforce Custom Actions
                     Merchandise__c[] merch =
                         warehouse.getSObjects('Merchandise__r');
                         if (merch != null) {
                            for (Merchandise__c m : merch){
                                merchandise.add(m);
                            }
                         }
                }
                return merchandise;
          //This remote action creates the invoice for the quick order
          @RemoteAction
          global static Line_Item__c createQuickOrder(
              String accId, String merchandiseId){
              Invoice__c newInvoice = new Invoice__c();
              newInvoice.Account__c = accId;
              insert newInvoice;
               return quickOrder;
          }
                                                  100
                                   Chapter 12 Adding Functionality with Visualforce Custom Actions
          order.Quantity__c = quantity;
          insert order;
        post.type = 'LinkPost';
        post.LinkUrl = '/' + li.Invoice__c;
        post.Title = li.Merchandise__r.Name + ': ' + li.quantity__c;
        insert post;
    } catch(System.Exception ex) {
        system.debug(ex.getMessage());
    }
        return true;
    }
          return true;
    }
    Note: Use static queries and binding variables to prevent a SOQL injection attack. For example, use
    :queryName instead of \'%'+merchName+'%\'. For more information, see “Security
    Guidelines for Apex and Visualforce Development“ in the Salesforce Help.
                                              101
Chapter 12 Adding Functionality with Visualforce Custom Actions
    The Apex controller also has an insertQuickOrder method that creates a feed item about the new
    order in the account feed as shown in this code snippet. The feed item is a link post that links to the invoice.
           FeedItem post = new FeedItem();
           post.ParentId = aId;
           post.Body = UserInfo.getName() + ' just created a quick order';
           post.type = 'LinkPost';
           post.LinkUrl = '/' + li.Invoice__c;
           post.Title = li.Merchandise__r.Name + ': ' + li.quantity__c;
           insert post;
              <style>
                  /* Default S1 color styles */
                                                            102
                                       Chapter 12 Adding Functionality with Visualforce Custom Actions
                 .list-view-header, .data-capture-buttons a {
                       background: -webkit-linear-gradient(
                           #2a93d5,#107abb);
                       background: linear-gradient(#2a93d5,#107abb);
                       box-shadow: 0 1px 3px rgba(0,0,0,.2),
                           inset 0 1px 0 rgba(255,255,255,.21);
                       color: white;
                       font-weight: bold;
                 }
              #resultPage, #searchPage {
                  padding-bottom: 50px;
              }
          </style>
The QuickOrderPage also calls the Canvas SDK to enable the publisher Submit button and close
the publisher window.
First, it includes a reference to the SDK:
<!-- This needs to be included so the publisher can be used
    to submit the action -->
<script type='text/javascript'
src='/canvas/sdk/js/publisher.js'></script>
Then it calls the setValidForSubmit method to enable the publisher Submit button:
//This method will activate the publish button
//so the form can be submitted
Sfdc.canvas.publisher.publish({
    name: "publisher.setValidForSubmit",
    payload:"true"});
After the setValidForSubmit is called and the user clicks Submit, this subscribe method fires.
This method invokes the final JavaScript function which uses JavaScript remoting to insert the line item
(thus completing the quick order) and then post a feed item to the account:
<script type='text/javascript'>
    Sfdc.canvas.publisher.subscribe({name: "publisher.post",
        onData:function(e) {
    //This subscribe fires when the user hits
    //Submit in the publisher
    insertQuickOrder();
    }});
</script>
                                                103
Chapter 12 Adding Functionality with Visualforce Custom Actions
    Finally, after the callback from the remoting method returns successfully, this method closes the publisher
    window:
     // Success - close the publisher and refresh the feed
     Sfdc.canvas.publisher.publish({name: "publisher.close",
         payload:{ refresh:"true"}});
                                                          104
CHAPTER 13 Development Guidelines and Best
           Practices
In this chapter ...       You’ve had a chance to learn the major concepts of developing for the
                          Salesforce app, and to see how you can easily add customized functionality
•   When to Use the       for your mobile users. This chapter focuses on some conceptual guidelines
    Navigation Menu or    and specific best practices for developing advanced custom actions and
    the Action Bar        pages using the programmatic tools available to all Salesforce Platform
•   Guidelines and Best   developers.
    Practices
                          Whether you’re creating Visualforce pages to add as custom actions or
•   Canvas Guidelines     mobile cards, or creating or integrating canvas apps into the Salesforce
    and Best Practices
                          app, these principles and practices will help you provide the best
                          experience for your mobile users.
                                          105
Chapter 13 Development Guidelines and Best Practices
       The navigation menu appears when you tap            . This menu is available in the global context. For
       example, if users log in and are viewing items in the feed, they can tap and open the navigation menu,
       and it displays menu items. Typically, these menu items lead to more complex business processes that
       don’t take place in the context of any particular object.
       Menu items in the navigation menu should bring users to a fully functional page or app. So if you have
       a page or app that contains many fields through which the user would need to scroll and perform a
       more complex process, you’ll want to make your page or app available from the navigation menu.
       An example from this book is the Find Warehouses Visualforce page that we made available from the
       navigation menu in Extending the Salesforce App with Visualforce Pages on page 79. When the mobile
       technician taps the menu item, a page appears that contains a Google map and displays any nearby
       warehouses. The functionality of this page is global—not in the context of any particular object in our
       schema.
                                                         106
                                                Chapter 13 Development Guidelines and Best Practices
Action Bar
   The action bar and its action menu appear on all pages that support actions The action bar is for
   accessing custom functionality that displays small amounts of data and allows users to perform short,
   quick actions. If you have functionality that occurs in the context of an object, you’ll want to add it as
   an action in the action bar.
   An example from this book is the Create Quick Order action, available from the action bar within a
   customer account. While the mobile technicians are servicing a customer account, they can tap the
   action and then enter in just the merchandise name and distance to find warehouses with a part in
   stock. Then the technicians enter the quantity and a customer order is created. The functionality of
   this Visualforce page occurs within the context of a customer account. The user interaction with the
   page is quick, and it’s a simple process to search and create an order because the action contains only
   a few fields.
                                                 107
Chapter 13 Development Guidelines and Best Practices
                                                               108
                                                 Chapter 13 Development Guidelines and Best Practices
          Note: Standard buttons that are overridden with a Visualforce page disappear from record
          detail pages and record lists in the app if Available for Lightning Experience,
          Lightning Communities, and the mobile app isn’t selected for the Visualforce
          page that overrides the corresponding button.
                                                 109
Chapter 13 Development Guidelines and Best Practices
    Limitations
    Limitations to the user experience include:
    • Tap targets—buttons, links, form fields, and so on—are optimized for mouse cursors, and can be
      difficult to hit accurately with a fingertip.
    • The visual design is unchanged, and may not fit with the mobile-optimized, modern visual design of
      the Salesforce app.
    If your development timeline is aggressive, you might find these limitations acceptable.
<apex:form>
                 <apex:pageBlockButtons location="bottom">
                   <apex:commandButton action="{! quickSave }" value="Save"/>
                 </apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
          This page can be used in both the Salesforce app and the full Salesforce site. It displays as a standard
          desktop Visualforce page in both contexts.
                                                           110
                                                Chapter 13 Development Guidelines and Best Practices
                                                 111
Chapter 13 Development Guidelines and Best Practices
          <style>
              html, body, p { font-family: sans-serif; }
          </style>
<apex:form >
<h1>{!Warehouse__c.Name}</h1>
<h2>Warehouse Details</h2>
                <div id="theForm">
                    <div>
                      <apex:outputLabel for="address" value="Street Address"/>
                          <apex:inputField id="address"
                              value="{! warehouse__c.Street_Address__c}"/>
                      </div>
                      <div>
                          <apex:outputLabel for="city" value="City"/>
                          <apex:inputField id="city"
                              value="{! warehouse__c.City__c}"/>
                      </div>
                                                          112
                                                 Chapter 13 Development Guidelines and Best Practices
                 <div>
                     <apex:outputLabel for="phone" value="Phone"/>
                     <apex:inputField id="phone"
                         value="{! warehouse__c.Phone__c}"/>
                 </div>
             </div>
             <div id="formControls">
                 <apex:commandButton action="{!quickSave}" value="Save"/>
             </div>
</apex:form>
</apex:page>
      This page can be used in both the Salesforce app and the full Salesforce site. It displays as a standard
      page on the full Salesforce site, but without the full Salesforce styling for the form. In the Salesforce
      app, it displays roughly matching the Salesforce app’s visual style. With additional styles, the page
      can approximate the visual style for both versions.
                                                  113
Chapter 13 Development Guidelines and Best Practices
      3. Add scripts and styles from your chosen mobile toolkit to the page using Visualforce resource tags.
         For example:
          <apex:includeScript
              value="{!URLFOR(
                  $Resource.Mobile_Design_Templates,
                  'Mobile-Design-Templates-master/common/js/
                      jQuery2.0.2.min.js'
              )}"/>
      4. Use HTML5 and your mobile toolkit’s tags and attributes to create a page skeleton.
      5. Add JavaScript functions to the page as handlers to respond to user interaction. Use JavaScript
         remoting to call Apex @RemoteAction methods that retrieve records, perform DML, and so
         on.
      6. Add additional JavaScript functions to handle user actions and page updates. Perform page updates
         by constructing HTML elements in JavaScript, and then adding or appending them to the page
         skeleton.
                                                          114
                             Chapter 13 Development Guidelines and Best Practices
    <apex:includeScript
      value="{!URLFOR($Resource.Mobile_Design_Templates,
'Mobile-Design-Templates-master/common/js/jQuery2.0.2.min.js')}"/>
    <apex:includeScript
      value="{!URLFOR($Resource.Mobile_Design_Templates,
'Mobile-Design-Templates-master/common/js/jquery.touchwipe.min.js')}"/>
    <apex:includeScript
      value="{!URLFOR($Resource.Mobile_Design_Templates,
      'Mobile-Design-Templates-master/common/js/main.min.js')}"/>
<head>
<style>
    html, body, p { font-family: sans-serif; }
    input { display: block; }
</style>
<script>
    $(document).ready(function(){
        // Load the record
        loadWarehouse();
    });
    $.urlParam = function(name){
        var results = new RegExp('[\\?&]' + name + '=([^&#]*)')
            .exec(window.location.href);
        return results[1] || 0;
    }
    function loadWarehouse() {
        // Get the record Id from the GET query string
        warehouseId = $.urlParam('id');
                              115
Chapter 13 Development Guidelines and Best Practices
              function updateWarehouse() {
                  // Get the record Id from the GET query string
                  warehouseId = $.urlParam('id');
                                                116
                           Chapter 13 Development Guidelines and Best Practices
</script>
</head>
<body>
<div id="detailPage">
    <div class="list-view-header" id="warehouse_name"></div>
    <div id="action_status"></div>
   <section>
       <div class="content">
           <h3>Warehouse Details</h3>
           <div class="form-control-group">
               <div class="form-control form-control-text">
                   <label for="warehouse_address">
                       Street Address</label>
                   <input type="text" id="warehouse_address" />
               </div>
               <div class="form-control form-control-text">
                   <label for="warehouse_city">City</label>
                   <input type="text" id="warehouse_city" />
               </div>
               <div class="form-control form-control-text">
                   <label for="warehouse_phone">Phone</label>
                   <input type="text" id="warehouse_phone" />
               </div>
           </div>
       </div>
   </section>
</body>
                           117
Chapter 13 Development Guidelines and Best Practices
</apex:page>
         The static HTML provides the shell of the page, including empty form fields. JavaScript functions
         load the record, fill in the form fields, and send updated form data back to Salesforce.
         Although this page can be used in the full Salesforce site, it’s designed as a Salesforce app page and
         looks very different than a normal Visualforce page.
                // Stub controller
                // We're only using RemoteActions, so this never runs
                public WarehouseEditor(ApexPages.StandardController ctl){ }
               @RemoteAction
               global static Warehouse__c getWarehouse(String warehouseId) {
                            FROM Warehouse__c
                            WHERE Id = :warehouseId];
                      return(wh);
                }
                @RemoteAction
                global static Boolean setWarehouse(
                    String whId, String street, String city, String phone) {
                                                         118
                                                Chapter 13 Development Guidelines and Best Practices
Warehouse__c wh = WarehouseEditor.getWarehouse(whId);
              // Update fields
              // Note that we're not validating / sanitizing, for
      simplicity
              wh.Street_Address__c = street.trim();
              wh.City__c = city.trim();
              wh.Phone__c = phone.trim();
                   return true;
             }
      }
                                                 119
Chapter 13 Development Guidelines and Best Practices
    PDF rendering, by setting renderAs="PDF" on <apex:page>, isn’t supported for pages in the
    Salesforce app.
          Warning: Embedded Visualforce pages—that is, those added to a page layout—that contain an
          <apex:enhancedList> component may cause the Salesforce app to crash on iOS.
    Standard components outside the apex namespace, for example, <liveagent:*>, <chatter:*>,
    and so on, aren’t supported in the app.
    Custom components can be used in Visualforce in the app, as long as they themselves don’t use
    unsupported components.
                                                         120
                                                   Chapter 13 Development Guidelines and Best Practices
In general, Visualforce added to page layouts works best if it’s read-only, at-a-glance information. Put
features that require user interaction, like multi-field forms, on full screen pages by adding them as tabs
in the main navigation, or as custom actions from the action bar.
  1. The record header displays when an record is loaded, but can be scrolled up and off the screen
     by the user. When on screen, it’s 158 pixels high on all devices, and takes the full width of the
     screen. You can’t control the display of the record header.
  2. Mobile cards display above all of the related items on the record.
  3. Set the width to 100%; the element sizes automatically, minus some padding on either side. The
     content of mobile cards can’t be scrolled, so make sure it fits in the space you provide to it.
  4. Control the height of the mobile card by setting the height in pixels in the page layout editor. The
     mobile card area uses exactly that height, even if the mobile card’s content is shorter. In that case,
     the extra area is blank. If the card’s content is taller, the content is clipped. As a best practice, don’t
     create mobile cards taller than the smallest device screen you intend to support. Be sure to set the
     height of screen elements relevant to your environment.
  5. The record’s related items are displayed after all mobile cards.
                                                    121
Chapter 13 Development Guidelines and Best Practices
    While you can add multiple mobile cards, it quickly becomes a user experience challenge to scroll past
    them to the related lists. It’s a best practice to add only one or two. If you need a full screen to display your
    page, consider moving it to a custom action on the object instead.
    The normal Salesforce header and sidebar are automatically removed from Visualforce pages added as
    mobile cards. You may find it useful to explicitly turn them and the full Salesforce site stylesheets off while
    you’re developing the page. Additionally, if your page uses the Google Maps API, Google recommends
    using an HTML5 doctype. Here’s an <apex:page> tag that does all of these things:
    <apex:page standardController="Warehouse__c"
       docType="html-5.0" showHeader="false" standardStylesheets="false">
      1. The record header displays when an record is loaded, but can be scrolled up and off the screen
         by the user. When on screen, it’s 158 pixels high on all devices, and takes the full width of the
         screen. You can’t control the display of the record header.
      2. Record controls and details, automatically generated by the Salesforce app.
                                                             122
                                                  Chapter 13 Development Guidelines and Best Practices
                                                   123
Chapter 13 Development Guidelines and Best Practices
      1. The Salesforce header, which provides access to the main navigation menu, is 42 pixels high. The
         contents of the header can’t be changed.
      2. The rest of the device screen is dedicated to your Visualforce page.
    When displayed in the Salesforce app, the standard Salesforce header and sidebar are automatically
    removed, like Visualforce pages used as mobile cards or added to page layouts. However, Visualforce pages
    used as custom actions in the action bar are shared with the full Salesforce site, and pages added to the
    navigation may or may not be shared. Pages shared with the full Salesforce site shouldn’t have the standard
    Salesforce header and sidebar explicitly removed unless removing the header and sidebar is the standard
    practice for all Visualforce on your site.
                                                          124
                                                Chapter 13 Development Guidelines and Best Practices
</apex:form>
                                                 125
Chapter 13 Development Guidelines and Best Practices
    As the user moves through the form fields, either by tapping into them or tapping the Next button, the
    keyboard changes to match the expected data for the field.
    These type-specific keyboards make filling in forms much easier for people using their mobile devices.
    <apex:input> allows the following explicit type values to be set:
    • date
    • datetime
    • datetime-local
    • month
    • week
    • time
    • email
    • number
    • range
    • search
    • tel
    • text
    • url
    You can also set type to auto, and the data type of the associated controller property or method is used.
    The HTML type attribute, including new HTML5 features, is a standard part of HTML. For additional
    details about the type attribute, what you can use it for, and how it relates to mobile development, see
                                                         126
                                                   Chapter 13 Development Guidelines and Best Practices
WHATWG’s list of input type attribute values and descriptions. Not all values are supported on Visualforce
input components. If you want to use a value not supported by Visualforce, use static HTML instead of a
Visualforce tag.
      Note: Client-side validation requires that the Visualforce page be set to API version 29.0 or later,
      and the page docType be set to html-5.0.
Validation patterns are regular expressions. Form input is checked against the expression, and if it matches,
the field input is considered valid. If it doesn’t match, the input is considered invalid; an error message is
displayed, and the form won’t be submitted to the server. Here’s an example of a field that requires an
email address from a specific domain:
<apex:input id="email" value="{!fText}" type="email"
    html-placeholder="you@example.com"
    html-pattern="^[a-zA-Z0-9._-]+@example.com$"
    title="Please enter an example.com email address"/>
Other useful HTML5 attributes that can be set as pass-through attributes include:
• placeholder (set using the html-placeholder attribute)—adds ghost text to the field to
  show sample input to the user.
• title (set using the title attribute on <apex:input>, and the html-title attribute
  on components without a title attribute)—adds an error message to use if the field fails client-side
  validation.
For inspiration for how you can use attributes to enhance the usability of HTML <input> elements,
HTML5 Forms Introduction and New Attributes is a good survey of the new features in HTML5. For further
details, especially for mobile users, and details of client-side forms validation, see Client-side form validation
and Improving the user experience on mobile devices in WHATWG’s HTML: The Living Standard.
                                                    127
Chapter 13 Development Guidelines and Best Practices
    Managing Navigation
    The Salesforce app manages navigation using events. The navigation event framework is made available
    as a JavaScript object that provides a number of utility functions that make creating programmatic navigation
    that “just works” a breeze. The advantage is a navigation experience that’s more natural for a mobile
    context. It also makes creating post-completion navigation, such as redirecting to an order page after the
    order is successfully submitted, easier for Salesforce developers.
    In the Salesforce app, programmatic navigation for Visualforce pages generally works something like this:
      1. A user invokes a Visualforce page, usually from the navigation menu, or from an action in the action
         bar.
      2. The Visualforce page loads and runs, including any custom controller or extension code called by
         the page.
      3. The user interacts with the page in some way: for example, to fill in some form values.
      4. The user submits the form, or performs some other action on the page that commits a change.
      5. Controller or extension code runs, saving the changes to Salesforce, and returning the results of
         the action.
      6. The Visualforce page, using JavaScript response handlers, receives the results of the action, and
         when successful, responds by redirecting the user to a new page that shows the results of their
         action.
    This scenario is easily handled by the app’s navigation framework.
    Another common use case is simply adding links or other user interface controls to a page, which move
    from that Visualforce page to another page in the app. This navigation is also easily managed by the app’s
    navigation framework.
    In these cases, navigation is handled by a special utility JavaScript object, sforce.one. The
     sforce.one object is automatically added to all Visualforce pages when they run inside the Salesforce
    app. This object provides a number of functions that trigger navigation events when they run. To use these
    functions, you can call them directly from your page’s JavaScript code, or you can attach calls as click
    handlers to elements on the page.
    Here’s a JavaScript function that creates markers to add to a Google map.
    function setupMarker(){
                                                           128
                                                Chapter 13 Development Guidelines and Best Practices
       // ...
}
The very first line builds a string, warehouseNavUrl, that, when used as a JavaScript URL, navigates
to the detail page for the warehouse. The link is created around the warehouse name, and appears in the
information panel (put together in the warehouseDetails string) that appears when you click a
marker. Clicking the warehouse name takes you to the detail page for that warehouse (the omitted part
of the function code deals with the Google Maps API calls to create a marker and add it to the map).
If you have JavaScript code or HTML markup that runs inside of the Salesforce app, keep these considerations
in mind:
• Don’t directly manipulate the browser URL using window.location.href. This doesn’t work
  well with the app’s navigation management system.
• Don’t use target="_blank" in navigation URLs; you can’t open new windows inside the app.
                                                 129
Chapter 13 Development Guidelines and Best Practices
    For more information about using the new methods, see Salesforce App Navigation Methods for Use with
    Canvas Apps in the Canvas Developer Guide.
     Function                        Description
     back([refresh])                 Navigates to the previous state that’s saved in the sforce.one
                                     history. It’s equivalent to clicking a browser’s Back button.
                                     refresh is optional. By default, the page doesn’t refresh. Pass true
                                     to refresh the page if possible.
                                                         130
                         Chapter 13 Development Guidelines and Best Practices
Function   Description
           is, URLs that are outside the Lightning domain—open in a separate
           browser window.
                         131
Chapter 13 Development Guidelines and Best Practices
    Function                    Description
    navigateToFeed(             Navigates to the feed of the specified type, scoped to the
    subjectId, type)            subjectId. For some feed types, the subjectId is required
                                but ignored. For those feed types, pass the current user’s ID as the
                                subjectId.
                                type is the feed type. The possible values are as follows.
                                • BOOKMARKS: Contains all feed items saved as bookmarks by the
                                  context user. Pass the current user’s ID as the subjectId.
                                • COMPANY: Contains all feed items except feed items of type
                                  TrackedChange. To see the feed item, the user must have
                                  sharing access to its parent. Pass the current user’s ID as the
                                  subjectId.
                                • FILES: Contains all feed items that contain files posted by people
                                  or groups that the context user follows. Pass the current user’s ID
                                  as the subjectId.
                                • GROUPS: Contains all feed items from all groups the context user
                                  either owns or is a member of. Pass the current user’s ID as the
                                  subjectId.
                                • NEWS: Contains all updates for people the context user follows,
                                  groups the user is a member of, and files and records the user is
                                  following. Contains all updates for records whose parent is the
                                  context user. Contains every feed item and comment that mentions
                                  the context user or that mentions a group the context user is a
                                  member of. Pass the current user’s ID as the subjectId.
                                • PEOPLE: Contains all feed items posted by all people the context
                                  user follows. Pass the current user’s ID as the subjectId.
                                • RECORD: Contains all feed items whose parent is a specified record,
                                  which could be a group, user, object, file, or any other standard or
                                  custom object. When the record is a group, the feed also contains
                                  feed items that mention the group. When the record is a user, the
                                  feed contains only feed items on that user. You can get another
                                  user’s record feed. Pass the record’s ID as the subjectId.
                                • TO: Contains all feed items with mentions of the context user.
                                  Contains feed items the context user commented on and feed items
                                  created by the context user that are commented on. Pass the current
                                  user’s ID as the subjectId.
                                                   132
                                           Chapter 13 Development Guidelines and Best Practices
Function                     Description
                             • TOPICS: Contains all feed items that include the specified topic.
                               Pass the topic’s ID as the subjectId. This value is supported in
                               Salesforce for mobile web only. Topics aren’t available in Salesforce
                               for iOS or Salesforce for Android.
navigateToFeedItemDetail( Navigates to the specific feed item, feedItemId, and any associated
feedItemId)               comments.
navigateToList(      Navigates to the list view that’s specified by the listViewId, which
listViewId,          is the ID of the list view to be displayed.
listViewName, scope) listViewName sets the title for the list view. It doesn’t need to
                             match the actual name that’s saved for the list view. To use the saved
                             name, set listViewName to null.
                             Set scope to the name of the sObject in the view, for example,
                             “Account” or “MyObject__c”.
createRecord(                Opens the page to create a record for the specified entityName,
entityName[,                 for example, “Account” or “MyObject__c”.
recordTypeId][,              recordTypeId is optional and specifies the record type for the
defaultFieldValues])         created object. Calling createRecord without providing a
                             recordTypeId may result in an error.
                             defaultFieldValues is optional and, if provided, prepopulates
                             fields on a record create panel, including fields not displayed on the
                             panel. Users must have create access to fields with prepopulated values.
                             Errors during saving that are caused by field access limitations don’t
                             display error messages.
showToast({toastParams}) Shows a toast. A toast displays a message below the header at the top
                         of a view. The toastParams object sets the attributes for the toast.
                                           133
Chapter 13 Development Guidelines and Best Practices
    Function                         Description
                                     Use any attribute available for the force:showToast Aura event.
                                     For example:
                                      sforce.one.showToast({
                                          "title": "Success!",
                                          "message": "The record was updated
                                      successfully."
                                      });
                                                         134
                                                    Chapter 13 Development Guidelines and Best Practices
• Update the code for the page’s features to fix the problem. This solution is best, but it might require
  some debugging, and it will definitely require code changes.
• Use a specific version of sforce.one. This solution often requires minimal code changes.
      Note: sforce.one was added in Winter ’14 (API version 29.0) and wasn’t versioned until Summer
      ’14 (API version 31.0). All versions of sforce.one earlier than version 31.0 are identical to version
      31.0. You can specify a version of sforce.one for any version that’s valid for Visualforce, that is,
      from version 15.0 to the current API version.
sforce.one.getVersion(versionString, callbackFunction);
versionString is the API version that your application requires. It’s always two digits, a period, and
one digit, such as “30.0”. Calls with invalid version strings fail silently.
callbackFunction is a JavaScript function that uses a specific version of sforce.one.
 sforce.one.getVersion() operates asynchronously, and your callback function is called when
it finishes loading the requested version of sforce.one. Your callback function receives a single
parameter, an sforce.one object for the specified API version. Use the object passed in instead of the
global sforce.one to make calls to sforce.one that conform to the API version that your app
requires.
                                                     135
Chapter 13 Development Guidelines and Best Practices
                 this.createAccount = function() {
                     sforce.one.navigateToURL("/001/e");
                 };
           }
        function btnCreateAccount() {
            app.createAccount();
        }
    </script>
    App functionality is created in a MyApp object, and then an event handling function calls the app function
    when that event, a button click, occurs. Separating application functionality from application event handling
    is a best practice, and it sets you up for using version-specific versions of sforce.one.
    Using a Specific sforce.one API Version (Simple)
    To use a specific version of sforce.one, get and save a reference to a versioned instance of the object.
    Then use this object to make sforce.one calls. The simplest way is to save it in the MyApp object.
    In the next sample, references to the versioned instance of sforce.one are in bold.
    <script>
        function MyApp(sfone) {
            this.createAccount = function() {
                sfone.navigateToURL("/001/e");
            };
        }
        function btnCreateAccount() {
            // Create our app object if not already defined
            if(!app30) {
                // Create app object with versioned sforce.one
                sforce.one.getVersion("30.0", function(sfoneV30) {
                    app30 = new MyApp(sfoneV30);
                    app30.createAccount();
                });
                return;
            }
            app30.createAccount();
        }
    </script>
                                                           136
                                               Chapter 13 Development Guidelines and Best Practices
In the preceding example, the event-handling function is expanded from the first example to include the
creation of a version-specific instance of sforce.one. If your app needs to mix multiple versions, you
can create multiple MyApp instances with appropriate versions and names. More than one or two, though,
are cumbersome to manage. We recommend the next approach instead.
Using a Specific sforce.one API Version (Best)
A better way to organize your app code is to create version-specific instances of sforce.one in an
app initialization block of code so you can keep the event handling separate.
<script>
    function MyApp(sfone) {
        this.createAccount = function() {
            sfone.navigateToURL("/001/e");
        };
    }
In this sample the app initialization is separated only by white space and comments, but you can separate
it into functions for better encapsulation.
Using a Specific sforce.one API Version (Synchronous)
                                                137
Chapter 13 Development Guidelines and Best Practices
    You can trigger a synchronous mode for sforce.one by manually including the specific version of
     sforce.one’s JavaScript on your page. The format for the URL to the library
    is:/sforce/one/sforceOneVersion/api.js. Here’s an example:
    <script src="/sforce/one/30.0/api.js"></script>
    <script>
        function MyApp(sfone) {
            this.createAccount = function() {
                sfone.navigateToURL("/001/e");
            };
        }
          sforce.one.getVersion("30.0", function(sfoneV30) {
              app = new MyApp(sfoneV30);
          });
    Although some situations require synchronous mode, the asynchronous version is preferred. If you forget
    to manually include the correct versions of the sforce.one library, your code will contain bugs that
    are difficult to diagnose.
                                                         138
                                                 Chapter 13 Development Guidelines and Best Practices
Visualforce pages used as custom actions on an object must use the standard controller for that object.
Use controller extensions to add custom code, including @RemoteAction methods you can call using
JavaScript remoting.
Your custom code could do more than make updates to the originating record. For example, the Create
Quick Order custom action searches for matching merchandise. It then creates an invoice and line item,
all as part of creating an order for a part. That logic occurs in the context of the originating account
record—the invoice is associated to the account record where the quick order action was invoked.
When you redirect to a URL internal to your org, the action dialog closes upon completion or
programmatically navigating away. If you set up the redirect to point to an external URL, the behavior can
vary because an external URL opens in a new browser tab.
                                                 139
Chapter 13 Development Guidelines and Best Practices
    menu in the full Salesforce site. It needs to work in both places. The intent of the code is to navigate to
    the detail page for the account for whom the order was placed:
    // Go back to the Account detail page
    if( (typeof sforce != 'undefined') && sforce && (!!sforce.one) ) {
        // Salesforce app navigation
        sforce.one.navigateToSObject(aId);
    }
    else {
        // Set the window's URL using a Visualforce expression
        window.location.href =
            '{!URLFOR($Action.Account.View, account.Id)}';
    }
    The if statement checks to see if the sforce object is available and usable. This is only true if the page
    is running inside the app. If sforce is available, the mobile navigation management system is used to
    go to the account’s detail page.
    If the sforce object isn’t available, trying to use it to navigate anywhere results in a JavaScript error,
    and no navigation. So, instead, the code sets the window’s URL using a Visualforce expression that returns
    the URL for the account’s detail page. You don’t want to do this in the app because the navigation event
    will be lost by the framework, but it’s required in normal Visualforce.
          Note: It’s a best practice to factor out common tests like this one into their own helper function.
          You could add something like the following to a JavaScript static resource, and then just call
          ForceUI.isSalesforce1() in your if conditions. Then, if the detection logic changes, you
          only have to update it in one place.
           (function(myContext){
               myContext.ForceUI = myContext.ForceUI || {};
               myContext.ForceUI.isSalesforce1 = function() {
                   return((typeof sforce != 'undefined') && sforce &&
           (!!sforce.one));
               }
           })(this);
                                                           140
                                                Chapter 13 Development Guidelines and Best Practices
 Attribute                                     Description
 cache                                         Boolean value that specifies whether the browser should
                                               cache the page. If not specified, defaults to false.
More Resources
Here are some more resources to help you tune the performance of your Salesforce apps:
• Inside the Force.com Query Optimizer (webinar)
• Maximizing the Performance of Force.com SOQL, Reports, and List Views (blog post)
• Force.com SOQL Best Practices: Nulls and Formula Fields (blog post)
                                                 141
Chapter 13 Development Guidelines and Best Practices
    • When you access a canvas app from the publisher in the full Salesforce site, the user interface is different
      than when you access a canvas app from the action bar or action menu in the Salesforce app. For
      example, in the feed in the full Salesforce site, the Share button is at the bottom of the feed item.
In the Salesforce app, the Share button is at the top of the screen.
                                                           142
                                                Chapter 13 Development Guidelines and Best Practices
• When creating a canvas custom action, the height available for that action in the full Salesforce site is
  much greater than the height for that action in the app. Use the Dimensions object in the Canvas SDK
  to render your canvas app in the correct size.
• Keep the labels for canvas custom actions concise. Longer labels may not fully display in the publisher.
• When you access a canvas app from the publisher, the What are you working on? pane
  appears above the canvas app. This pane remains fixed, even if your canvas app scrolls.
• When the request comes into your Web application that’s exposed as a canvas app, you can determine
  the type of device that’s making the request. Use this information to render your app based on the
  requesting device for a better user experience. For example, you can add logic so that if the request
  comes from a mobile phone, only four lines of text are displayed; if the request comes from a tablet,
  ten lines of text are displayed.
• In most cases, you’ll want to specify 100% for the canvas app height and width in your CSS. This ensures
  that the canvas app takes up the maximum available screen space.
• Canvas apps appear in an iFrame, so you can format the app appearance as you would any standard
  iFrame.
                                                 143
Chapter 13 Development Guidelines and Best Practices
                                                         144
                                                  Chapter 13 Development Guidelines and Best Practices
    – Set the height attribute to the clientHeight value delivered in the signed request. For
      example:
         //Where sr is a parsed signed request object
         var h = parseInt(sr.context.environment.
             dimensions.clientHeight, 10);
         Sfdc.canvas.byId('divElementId').style.height = h;
    – The clientHeight value can be very small, particularly in a phone’s landscape mode, and
      users may not be able to see any content. Use min-height set to the desired height in pixels
      to ensure a good user experience.
                                                  145
CHAPTER 14 Learning More
In addition to this guide, there are many resources available to help you in your Salesforce Platform
development journey.
Admin Resources
Salesforce Help & Training Portal
    A site devoted to the help documentation for Salesforce. Get help for what you’re working on, find
    answers to your questions, and download tip sheets and other guides.
Salesforce Trailblazer Community
    Home to a set of extremely useful tools to help you get your Salesforce work done. Connect with
    Salesforce customers, partners, product specialists and employees to learn, get answers to your
    questions, and share new ideas.
Developer Documentation
You’ll find all these guides and more on our developer site at
http://developer.salesforce.com/docs.
Quick Actions Implementation Guide
   Learn about the default actions, how to create object-specific actions, and how to configure publisher
   layouts. Find out how you can extend the Chatter publisher and the Salesforce mobile action bar with
   Visualforce custom actions and Canvas custom actions.
                                                147
Chapter 14 Learning More
                                                         148
INDEX
A                                                    B
About Acme Wireless 12                               business scenario, Acme Wireless 68
About the sample scenario 12
About this book                                      C
     audience 12                                     Canvas
     how do I begin? 12                                   best practices 141, 144–145
Actions                                              Compact layouts
     about action layouts 52                              creating 40
     about custom actions 60                              find out more 43
     about predefined values 57                           overview 39
     assigning to a global page layout 51                 overview for mobile 31
     assigning to a page layout 50                        test it out 42
     create actions 46                                    try it out 40
     creating 49                                     Configuring and enabling offline access 20
     creating a global action 51                     Configuring Salesforce app 17–18
     creating an object-specific action 50           Create a Visualforce page 80
     custom actions 48                               Create a Visualforce tab 83
     customizing an action layout 54                 Custom actions
     default actions 48                                   add the Visualforce custom action to the page
     global actions 46                                           layout 95
     guidelines and best practices 64                     business scenario 94
     log a call actions 46                                create a Visualforce custom action 94
     mobile smart actions 48                              introduction 93
     object-specific actions 46, 50, 55                   test the Visualforce custom action in the
     overview for mobile 45                                      Salesforce app 96
     predefined values for actions 59                custom actions introduction 93
     setting a predefined field value 58
     standard actions 48                             D
     tell me more 52                                 development process for the Salesforce app 71
     testing in Salesforce app 55, 59
     update actions 46                               G
     what they are 46                                Guidelines and best practices
Add the Visualforce tab to the navigation menu 84        actions 64
Audience for Part II, developer guide 68                 custom icons 64
                                                         for administrators 63
                                               149
Index
                                                     150
                                                                                                          Index
151