Create a Salesforce Record using a Javascript Button

Terrys Tidbits
2 min readOct 24, 2013

--

Have you ever needed to create a Salesforce record by pressing a button? If so, this will explain how simple this can be.

In this example, I’ll create a new Account record by pressing a button on the Account object. You’ll want to adapt this to a more relevant scenario but this will help you with the basic process.

First, you’ll create the button

  • Navigate to Setup | Customize | Account | Buttons, Links and Actions
  • Press the New Button or Link button
  • Give your button a name
  • Choose the appropriate Display Type option but in most cases you’ll likely choose a Detail Page Button
  • Choose Execute JavaScript as the Behavior
  • In the field box you’ll add the JavaScript which I’ll explain below

The JavaScript for this is pretty simple even if you’re not that familiar with the language. I’m certainly no expert on it either so I’m confident you’ll do fine.

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}<br>

Next, we need to create an object variable to hold our data. In this example, I’ll create my variable, called “acct”, as an Account record. This could be a contact or any other object within Salesforce.

var acct = new sforce.SObject("Account");<br>

Now I will populate the fields on the object. I do this by using the variable name I just created. I can add as many of these as needed to correctly populate my new record.

acct.name = 'New Account';<br> 
acct.phone = '515-123-4567';<br>

Now that I have all my fields defined, I’m ready to save the new record.

var result = sforce.connection.create([acct]);<br>

Finally, you’ll want to verify the record was created. In the last step we saved the results of our save in a variable called “result”. Below we’re reading that variable to determine if we were successful. If we are successful, I’m opening the new record in “edit mode” for the user to make any additional changes. If it was not successful, then I display an error message.

<br> 
if(result[0].getBoolean("success")){<br>
window.location = "/" + result[0].id + "/e";<br>
}else{<br>
alert('Could not create record '+result);<br>
}<br>

With the above, you should take some liberty and process the results in a way that makes sense for your situation. If you remove the ‘ + “/e” ‘ from the end of the window.location line, the new record will show in “read mode”. Maybe, you don’t want to display the new record at all so, in that case you might do another alert() box to simple tell the user the record was successfully created.

Hope this helps you create new records with a simply press of a button. Good luck!

Originally published at https://www.terrystidbits.com on October 24, 2013.

--

--

Terrys Tidbits

Discover how I was able to gain knowledge about Salesforce and grew my career through my years of experiences and handled consultant projects.