Blog

List buttons can be used on list pages, search results and any related list for an object. They allow us to take actions on a group of selected records. In this article we are going to show some examples of how Javascript can be used to work with one or more records in a list view or related list. These are examples for Salesforce Classic, if you want to know about updates to Javascript Buttons in Lightning Experience, check out this article.

Use case: We need to automate the following actions.

  • Quick Create a contact (allow user to enter contact’s name and use the phone number from it's parent account).
  • Activate a set of selected contacts. The Status field should be set to “Active” and Last Contacted field should be set to today’s date.
  • Quick Delete a set of selected contacts. User should confirm changes.


The Contact object has the following custom fields: Status (which indicates if the contact is active or not) and Last Contacted (indicates when the contact was last contacted).


Quick Create

To get started, we need to understand the tools we will be using. We are not using APEX in this example, only Javascript. To allow us to work with the Salesforce database through Javsascript, we need to use the AJAX Developer Toolkit which is a wrapper around the Salesforce API.

So, let’s create the first button which creates a contact record.

Go to Setup – Customize – Contacts – Buttons, Links, and Actions and hit the “New Button or Link” button:

Select “List Button” display type, “Execute JavaScript” behavior and “OnClick JavaScript” content source. It will execute our JS code on click.

Now, we have to connect the Ajax Toolkit. We use the REQUIRESCRIPT function. The Library is connected by following syntax:

{!REQUIRESCRIPT('/soap/ajax/35.0/connection.js')}

More about Ajax Toolkit features can be found in the AJAX Toolkit Developer's Guide

Now we have to create a contact record. This action has the following syntax:

var contact = new sforce.SObject("Contact");

After that we can work with contact variable’s fields as we do with SObject fields in Apex. So, we should assign values to fields:

var name = "";

while (name === "") {
name = prompt("Enter Name");
}

contact.LastName = name;
contact.AccountId = "{!Account.Id}";
contact.Phone = "{!Account.Phone}";
contact.Status__c = "Inactive";

You can see Contact’s Name field is assigned from the Javascript prompt. To save this record we call the sforce.connection.create() method:

var saveResult = sforce.connection.create([contact]);

The saveResult variable contains information about the result of the call to the sforce.connection.create() method. If the record creation is successful, it will contain the saved record ID and a “success” : “true” flag. Otherwise it will contain an error message.

Then we just check the action state and reload the page if it is successful or show the error otherwise:

{!REQUIRESCRIPT('/soap/ajax/35.0/connection.js')}

var contact = new sforce.SObject("Contact");
var name = "";

while (name === "") {
name = prompt("Enter Name");
}

contact.LastName = name;
contact.AccountId = "{!Account.Id}";
contact.Phone = "{!Account.Phone}";
contact.Status__c = "Inactive";

varsaveResult = sforce.connection.create([contact]);
varisSuccess = saveResult[0].getBoolean("success");

if (!isSuccess) {
alert(saveResult[0].get("errors").get("message"));
}

location.reload(true);

Let’s check our button! Go to Setup – Customize – Accounts – Page Layouts and select the layout you need to customize. In Page Layout Editor hit on the Contacts Related List Properties sign and go to the Buttons section:

Let’s add the button and click OK. Then just save Account’s layout.

Now, let’s go to any account record and make sure that our button is displayed on the related list:

Hit the Quick Create button. The dialog box appears to enter a name:

Enter the name for new contact record. For example, John Smith and hit OK button. The page will be reloaded and a new contact record will appear in the related list:

Update Multiple Records

Now let’s create another list button to update multiple records for our Activate use case.

 Go to Setup – Customize – Contacts – Buttons, Links, and Actions and hit the “New Button or Link” button:

As you can see, almost all preferences are the same as in Quick Create button. The difference is in “Display Checkboxes” checkbox. This preference allows us to select multiple records in the related list.

The Javascript code is similar to Quick Create but we need to get the selected records by using the following function:

varselectedContactIds = {!GETRECORDIDS($ObjectType.Contact)};

The GETRECORDIDS function retrieves the selected contact Ids and stores them in the selectedContactIds variable. But they are just Ids, not the records! 

We need to declare an array to collect the contact records that should be updated.  Then we iterate through all the selected records and create a new instance of contact.  We then assign the Id value of the existing record to the new record and in the update call Salesforce will update the fields in the record for the matching record Ids.

Then we have to set the Status and Last Contacted fields to new values and push the record to the array. Notice how to assign the Date field – we use Date().toISOString() function to ensure that Last Contacted field will get correct value. Otherwise we will get an error message about incompatible types.

To update the records, we call the update action and refresh the page:

varsaveResult = sforce.connection.update(contactsForUpdate);

location.reload(true);

 The full code:

{!REQUIRESCRIPT(‘/soap/ajax/35.0/connection.js’)}

varselectedContactIds = {!GETRECORDIDS($ObjectType.Contact)};
varcontactsForUpdate = [];

if (selectedContactIds[0] == null) {
alert(“You must select at least one record”);
} else {
for (vari = 0; i < selectedContactIds.length; i++) {
var contact = new sforce.SObject(“Contact”);
contact.Id = selectedContactIds[i];
contact.Status__c = “Active”;
contact.LastContacted__c = new Date().toISOString();
contactsForUpdate.push(contact);
}
}

varsaveResult = sforce.connection.update(contactsForUpdate);
location.reload(true);

 

As with the Quick Create button we need to add the button to the page layout.

Go to Setup – Customize – Accounts – Page Layouts and select the layout you need to customize. In the Page Layout Editor Contacts Related List Properties go to the Buttons section:

Add the button and click OK. Then just save Account’s layout.

Go to any Account record and make sure that the new button is displayed:

Let’s select our John Smith contact and hit the Contacted button. The page should be refreshed and the John Smith record should be updated:

Delete Records

Finally, lets add a button to delete selected records. Go to Setup – Customize – Contacts – Buttons, Links, and Actions and click the “New Button or Link” button:

The code is similar to the previous examples. Below you can see the full code listing:

{!REQUIRESCRIPT('/soap/ajax/35.0/connection.js')}

varselectedContactIds = {!GETRECORDIDS($ObjectType.Contact)};

if (selectedContactIds[0] == null) {
alert("You must select at least one record");
}
else {
if (confirm("Are you sure?")) {
varsaveResult = sforce.connection.deleteIds(selectedContactIds);
location.reload(true);
}
}

 

As you can see, getting the contact Ids and using an alert if no records are selected are done the same way as the update call.  The sforce.connection.deleteIds()method receives just a set of record ids and performs delete call to Salesforce database.

Let’s add the button to related list. Go to Setup – Customize – Accounts – Page Layouts and select the layout you need to customize. In Page Layout Editor click the Contacts Related List Properties and go to the Buttons section.

Add the button and click OK. Then just save Account’s layout.

Go to the any Account record and make sure that new button is displayed:


Let’s try and delete the John Smith’s contact record. After clicking the Quick Delete button, the confirmation dialog appears:

Now, check that John Smith’s contact does not exist anymore!

What are the advantages of using this approach?

  • We can perform database calls without using Apex.
  • We avoid creating a custom interface.
  • We can use these buttons on a standard list view.


What Certification are you studying for now?

Focus on Force currently provides practice exams and study guides for sixteen certifications

Salesforce List Buttons Javascript Example

List buttons can be used on list pages, search results and any related list for an object. They allow us to take actions on a group of selected records. In this article we are going to show some examples of how Javascript can be used to work with one or more records in a list view or related list. These are examples for Salesforce Classic, if you want to know… Read More

Salesforce List Buttons Javascript Example

Routing work with Salesforce Omni Channel

In the Winter 16 release, Salesforce has introduced a new feature – the Omni-Channel, which is based on a principle of getting work to the right person at the right time. It helps put rules in place to allow the system to determine the importance of work items, and pass it on the right person who is available.  Salesforce Omni Channel is built on 4 Functional Blocks: Image Courtesy: Salesforce… Read More

Routing work with Salesforce Omni Channel

Focus on Automation: Visual Workflow Loops

Loops in Visual Workflow Visual Workflow enables many possibilities to automate processes and reduce or eliminate the need for Apex code. One of the key features of Visual Workflow is the ability to process multiple records using a loop construct, unlike standard workflow, where actions such as a field update operate on only one record. Although Process Builder can operate on multiple records to update related records; once the logic… Read More

Focus on Automation: Visual Workflow Loops

Salesforce Manager Group Sharing Example

Manager Group sharing is a little tricky to understand until you see example scenarios. Here we go through a couple of examples to explain how it works. Understanding the Need for Manager Sharing Groups It is a common practice to group users sharing the same business duties under a single Role. For instance, if your organization has 15 territories within a country – and each territory has an Area Sales… Read More

Salesforce Manager Group Sharing Example

Focus on People: Valerio Lancia

I recently had a chat with Valerio Lancia, a Salesforce CRM Application manager about his journey with Salesforce, what he has learned and his recent certification experience. Q: What is your background? Is it an IT background, or a business background, and how did you first get exposed to Salesforce? A: I have a management engineering degree and my initial job in Italy was as a buyer. After two years… Read More

Focus on People: Valerio Lancia

An introduction to Salesforce APIs

Once you start working in the Salesforce world, it won’t take long until you come across the need to integrate or connect your Salesforce org to an internal or external system. At that point, you will start to hear about API’s. While you may think that is something that only developers need to know and understand it is useful for anyone working with Salesforce to know what they are and… Read More

An introduction to Salesforce APIs

Getting Started with Salesforce Entitlements

When a customer calls and requests support, how does a business know if and what level of service they are entitled to? Or what if service is only provided on certain products? Service could be provided for a certain period (e.g. a warranty) and then a customer must pay for service beyond the warranty period. It could also be that customers can purchase extended warranties or service contracts that may… Read More

Getting Started with Salesforce Entitlements

Winter 16 is Coming

Winter is Coming… While you are pondering over deploying the new Summer ’15 features, here is more news. The plan for Salesforce Winter ’16 release is out. It is time to plan your registrations for getting a sandbox preview of Winter ’16 features as and when it becomes available. You would need to take action before September 4, 2015 in case you are planning to make your Sandbox part of… Read More

Winter 16 is Coming

Native Duplicate Management in Salesforce

Administrators (and developers) are often faced with the task of cleaning up duplicate data from an org. Contact and Lead objects are the usual suspects for duplicate data. Anyone who has made an attempt at cleaning up duplicate data would agree it is a daunting and quite unenviable task. Duplicate data weighs down on your employee performance, application usability, risks customer satisfaction, and skews analytics. So, it is a priority… Read More

Native Duplicate Management in Salesforce

Salesforce Multi Org Dilemma

What exactly is a Salesforce org? The Salesforce document glossary describes an org (or Organization), as “A deployment of Salesforce with a defined set of licensed users. An organization is the virtual space provided to an individual customer of Salesforce. Your organization includes all of your data and applications, and is separate from all other organizations.” So, what is a multi-org situation? The multi-org situation that I refer to in… Read More

Salesforce Multi Org Dilemma

Salesforce Lightning Connect Example

Unlocking Back Office Data through Salesforce Lightning Connect The general approach to enterprise programming is changing. Significant investments are being made in making enterprise IT applications agile and nimble. Salesforce, being the innovators they are, have taken significant strides in this direction. One such move is the introduction of the lightning framework – a philosophy pioneered to reduce the time in developing and deploying enterprise applications. For any enterprise system… Read More

Salesforce Lightning Connect Example

Salesforce Process Builder Example

Lightning Process Builder – Point & Click Process Definition in the Cloud  The Spring ’15 release of Salesforce has opened up a whole new philosophy of developing in the cloud – the lightning framework. One key element of the lightning framework is the Lightning Process Builder. Before diving into Lightning Process Builder, it is good to understand where Salesforce is going with the entire “Lightning” idea. It is positioned as… Read More

Salesforce Process Builder Example

Salesforce Email to Case Setup Example

Email to Case is a standard Salesforce feature that allows cases to be created from emails.  We will be looking into the detail of On-Demand Email-To-Case and Email Services.On Demand Email-To-CaseThe first question when considering this functionality maybe which email address should be used to send to? We cannot send email to just any email address and have a Salesforce case created. We need to generate it using Salesforce configuration.Go… Read More

Salesforce VLOOKUP Example

Many people are aware of the Microsoft Excel vlookup function, that will return a value in a table (or defined range of cells) based on an identifier. Salesforce has a function with the same name, and this post will explain how it can be used using an example.Let’s say that you have a business requirement that only cases that have been open for a certain period of time can be… Read More

Salesforce VLOOKUP Example