Create,update and Query records using Javascript button in Salesforce

Lots of Use Cases can be achieved without  Apex codes and could be done by Administrators without requiring the help of the developers. Custom Buttons can execute JavaScript on click to perform DML operations. We would be taking an example to create Contact record by clicking on a button placed on Account detail page, will also explain how to query and execute apex using JavaScript.

Step1 : Creating a custom button on Account Object. Click Setup--> Customize --> Accounts --> Buttons, Links, and Actions. Click on New Button or Link  and enter information as mentioned in the screenshot below:

Javascript in custom button

Javascript Code  : 


var Cont = new sforce.SObject("Contact");
Cont.AccountId = '{!Account.Id}';
Cont.lastName = prompt('Enter LastName','');

var result = sforce.connection.create([Cont]);
alert('Contact Created');
alert('Error : '+result);

After pasting the JavaScript Code click on Save 

Step 2:
Add the Newly created button to the account layout.   Edit account layout  and drag the Create Contact button on the layout.

Javascript in custom button

All set, Now click on the Button in the account detail page , enter the last name of the contact and Boom!! You would see the contact created below the account.

Querying Objects using JavaScript
Below Script can be used to query all the Contacts records. 
var ContactRec = sforce.connection.query("SELECT id,LastName 
FROM Contact WHERE AccountId = '{!Account.Id}'");

records = ContactRec.getArray("records");

  for (var i=0; i< records.length; i++) {
    var record = records[i];
    alert("Contact Lastname"+ record.lastName + "Contact Id -- " + record.Id);

Comments are appreciated  :)

About Saurabh Dua


  1. Hi Saurabh..This will not be supported with Lightning.. You may need to add that as a precaution..!


Note: only a member of this blog may post a comment.

Powered by Blogger.