Create a Salesforce Record with a Button

Creative Way to Capture Opportunity Contact Role
September 20, 2013
update records with javascript button
Update Records with JavaScript Buttons for Salesforce
October 25, 2013

Create a Salesforce Record with a Button

create salesforce record
Applies to: Classic

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.

  • First, we have to include the libraries so add the following to the field box.  These need to be the first items in the script.


  • 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(&amp;quot;Account&amp;quot;);&amp;lt;br&amp;gt;<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. = 'New Account';&amp;lt;br&amp;gt;<br> = '515-123-4567';&amp;lt;br&amp;gt;<br>

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

var result = sforce.connection.create([acct]);&amp;lt;br&amp;gt;<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.

window.location = &amp;quot;/&amp;quot; + result[0].id + &amp;quot;/e&amp;quot;;&amp;lt;br&amp;gt;<br>
alert('Could not create record '+result);&amp;lt;br&amp;gt;<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!

Terry Miller
Terry Miller
Terry has spent over 20 years focused on business leadership and information technology. As an independent consultant, he enjoys working with a variety of customers to help them solve business problems using the Salesforce® platform. His ability to quickly identify bottlenecks and provide understandable solutions has gained him the trust of his customers. If you're looking for expert guidance on your next Salesforce® project, click here to contact Terry today.


  1. Update Records with JavaScript Buttons for - Home Team Consulting says:

    […] writing the post about creating records with a button, it made sense to extend that thought with manipulating record with a button […]

  2. Tina Hill says:

    Thanks for the info on the javascript for the custom button. I’ve copied your code but made a few edits based on our custom object but am getting an error message (“A problem with the OnClick JavaScript for this button was encountered. Unexpected token = “).

    I’m attempting to create a button on a case record that will create a “Agreement record” with some auto-populated fields.

    My code is below. I’d really appreciate any insight as to why this code isn’t working.

  3. Lara says:

    Thanks for explaining the code-snippets, that really helps me to customize for my organization. However, I was wondering if you can share how to do this whole operation in a new window / pop-up. So that you can close the window once the record is created, and return to the previous object.

    • Terry Miller says:

      Lara, I believe all you’d need to do is replace:

      window.location = "/" + result[0].id + "/e";

      with:"/" + result[0].id + "/e");

      I’m not certain if the domain portion of the URL (ie: has to be included in the string so you might have to modify that some.

  4. Jen says:

    I know this is somewhat of an old post, but I was hoping you may be able to help. I have changed a few things to create a record on a custom object (We will call it CustomObject2) from another custom object (We will call CustomObject1) and all of that is working correctly. But when I click Save on CustomObject2 I am brought back to the Salesforce home page.
    How can I get it to go back to the record I was on from CustomObject1.

    Here is my code:


    var cO1 = new sforce.SObject(“CustomObject1__c”);
    cO1.Type__c = ”;
    cO1.Category__c = ”;
    cO1.Product__c = ‘{!CustomObject2__c.Product__c}’;
    cO1.Description__c = ‘{!CustomObject2.Call_Log_Description__c}’;
    var result = sforce.connection.create([cO1]);

    window.location = “/” + result[0].id + “/e”;
    } else {
    alert(‘Could not create record’ +result);

    • Terry Miller says:

      Hi Jen,

      Modify this line from:
      window.location = “/” + result[0].id + “/e”;
      window.location = “/” + result[0].id + “/e?returl=”+ cO1.Id;

      You might have to put in a variable so you can reference it but otherwise the retURL is the missing link you need. :)

      • Rungrat says:

        Amit Lohogaonkar on November 26, 2007 at 3:08 amHi, We want to add new custom butotn next to standard butotn new’ under opportunity section We do not want to override new’ butotn but add new butotn. In butotn and links section it only allows to add butotns under details page not next to new’ butotn when user clicks opportunity tab. Let me know how to add this butotn when user clicks opportunity tab one extra butotn should be displayed next to new’ butotn.Amit Lohogaonkar

        • Terry Miller says:

          Detail buttons only show on the Detail page. To place a custom button on the Tab Overview page, you’d have to create a custom tab and override the default behavior.

  5. Shannon says:


    This is very helpful. However I am wondering how this would work with Quotes? The standard New Quote button is connected to the opportunity as a detail relationship. The button works okay, but I want to prefill some of the fields on the Quote with field values from the oppty. My understanding is to create a custom button. However, I am finding it difficult to get it to link to the oppty like the standard quote button (e.g. oppty name and account name default, quote line items are also included.

    Any help would be appreciated.



    • Terry Miller says:

      You’d have a couple options Shannon.

      What I would recommend is a URL hack approach. Take a look at my blog called URL Hacking for Automation ( In that post, you’re not creating the Quote record until the user has pressed the Save button but you’re pre-filling the fields you want.

      If you want to use the approach in this post, you sure can. Here, you are creating the record and then displaying it for the user to edit. Note the slight difference? This post is creating the record then displaying it in Edit mode. The URL hack opens the form in Edit mode but has not yet saved the record.

      If you want to continue with the approach in this blog, you’ll need something like this in your code. The second line is the missing link for you.

      var q = new sforce.SObject(“Quote”);
      q.OpportunityId = “{!Opportunity.Id}”;

      Hope that helps!

  6. Ali says:

    I know this is an old post but was just going through with custom object and the problem that I have a field that generates auto number. How can I get it populated through this code?

    Completed_Treatment_Number__c field data type is Master Detail &
    It is coming from Treatment object (Master)

    var treat = new sforce.SObject(“Treatment_Completed__c”);
    treat.Completed_Treatment_Number__c = “T-00996”;
    treat.Description__c = “Test”;
    var result = sforce.connection.create([treat]);

    window.location = “/” + result[0].id + “/e”;
    alert(‘Could not create record ‘+result);

    • Terry Miller says:

      First, auto-number fields are generated upon saving a record so you shouldn’t attempt to set anything to that field.

      Second, if I’m understanding your data model Treatment__c is the parent and Treatment_Completed__c is the child. If Completed_Treatment_Number__c is the Master-Detail lookup, you’ll need to set it to Treatment__c.Id. You do that as follows… Hopefully this will either work or get you going down the right path.

      // identify the parent record
      var t = new sforce.SObject(“Treatment__c”); = “{!Treatment__c.Id}”;

      // create the new record variable
      var treat = new sforce.SObject(“Treatment_Completed__c”);

      // set the field values
      treat.Completed_Treatment_Number__c =;
      treat.Description__c = “Test”;

      // save the record
      var result = sforce.connection.create([treat]);

      // verify the results
      window.location = “/” + result[0].id + “/e”;
      alert(‘Could not create record ‘+result);

  7. Ali says:

    Thanks a lot. It actually worked.

  8. Michael Carlson says:

    Hi Terry,
    Thanks very much for this post. Will you have a look at my code below? The new object is created, but data values are not populated.

    Appreciate the help!

    var acct = new sforce.SObject(“Submission__c”);
    Lender_1__c = ‘National Funding’;
    Date_Submitted_1__c = {!TODAY()};
    Lender_1_Result__c = ‘Auto Decline’;
    var result = sforce.connection.create([acct]);
    window.location = “/” + result[0].id + “/e”;
    alert(‘Could not create record ‘+result);

  9. 2k vc says:

    Many thanks very valuable. Will certainly share website with my friends

  10. Bailey says:

    This is probably the most helpful explaination I’ve come across so far, so thanks for that!
    I have searched and searched the community for more detailed explaination of Quote PDFs and if anyone else is using it for a javascript button, and I’ve found a handful of other use cases that have helped me somewhat but I am stuck on this last piece. Hoping you can help.

    I am using a custom onclick javascript button on the quote object that uses the QuotePDFOverlay functionality with the command buttons ‘Save to Quote’ Save & Email Quote’ and ‘Cancel’. Everything works great except that
    1. The ‘Save to Quote’ button does nothing, it just doesnt work. No alerts are logged and the browser doesn’t even seem to recognize the event. The other 2 buttons work as expected.
    2. For the ‘Save & Email Quote’, which works fine, I would like to add a email field value from the quote page and copy it over to the email page’s Sent To field.

    Here is my code:


    var pdfOverlay = QuotePDFPreview.quotePDFObjs[‘quotePDFOverlay’];


    Any help would be appreciated

    • Terry Miller says:

      Here’s a post that sounds similar to what you’re doing; perhaps it will help.
      I’ve not done a lot with the QuotePDFPreview method so I’m not able to add much new insight for you. Hopefully this link will give you some direct. Let me know how it turns out.

  11. Cody says:

    I have created a solution for providing better user feedback than just using a JavaScript alert, It would be a nice addition to the code you have here.

    • Terry Miller says:

      To all my readers, I can’t personally vouch for what Cody has here but it sure looks cool. :)

      To all those moving to Lightning, keep in mind a lot of these little javascript tricks I’ve shared in the past will not work with Lightning (sad face) but Lightning brings us so many other cool things.

  12. Tanmoy Das says:

    I don’t want to verify the final records. just save it. What is the syntax to achieve this.
    “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”. “

  13. Manna says:

    I am able to create a new record in custom object from a custom button using a java script. My code only works for parent to parent object, I am not able to create the records for child object using this button

  14. Danielle says:

    I am trying to create a new Onboarding list from a button click on the Onboarding case. No matter how much I tweak it to your notes above, I get the pop up error on button click “A problem with the OnClick JavaScript for this button or link was encountered: Unexpected identifier”. I am sure I am missing a really easy piece of this, but here is my code.

    the case lookup is a required field, so I tried to follow your master detail notes above.


    var C = new sforce.SObject(“Case”); = “{!Case.Id}”;

    var OBChecklist = new sforce.SObject(“Onboarding_Checklist__c”);

    OBChecklist.Initial_Onboarding_Case__c = C.Id;

    var result = sforce.connection.create([OBChecklist]);

    window.location = “/” + result[0].id + “/e”;
    alert(‘Could not create record ‘+result);

    • Terry Miller says:

      Danielle, I’m not seeing anything obviously wrong in your code. I’d start committing out parts of the code to find which line is the offending code. I’d start by committing everything after the create line. Try the button again and see if the Unexpected Error message stops. Basically, you’re trying to narrow down where the issue is. Hope that helps.

  15. Danielle says:

    Thanks Terry, unfortunately the pop up shows every time i click the button on the case, no matter what I comment out or keep. Might have to use actions or simple URL and make the reps fill in the data for now. Thanks for taking a look!

    • Terry Miller says:

      Hi Danielle, You’re not using Lightning are you? Javascript buttons will not work with that UI. If not, if you comment all lines except the REQUIREDSCRIPT line, do you still get the error? Another thing I do to troubleshoot is to add “alert(“your message”); lines. If the alert pops up then you know your getting at least that far. Also make sure you have the button defined correctly. Perhaps its something there that isn’t quite right.

      • Prissian Lappay says:

        Hi Terry, I’m having a difficulty with the Java Script. I already created a formula but I getting an error “A problem with the onclick javascript for this button or link was encountered: Unexpected identifier”
        …basically, i created a custom Lead and Custom Opportunity objects. I need to have the button “create Opportunity” on my custom lead object to create a new custom opportunity record that will automatically populate the name, office etc.. (values from Custom Lead object…

        here’s my code


        var SM Opportunity = new sforce.SObject(‘Sales_Opportunity__c’);


        var result = sforce.connection.create([Sales_Opportunity__c]);

        window.location = “/” + result[0].id + “/e”;
        alert(‘Could not create record ‘+result);

        let me know what am I doing wrong. Thank you in advance!

        • Terry Miller says:

          try this:


          var SM = new sforce.SObject("Sales_Opportunity__c");


          var result = sforce.connection.create([SM]);

          window.location = “/” + result[0].id + “/e”;
          alert(‘Could not create record ‘+result);

  16. Feroz says:

    Hi Terry,
    Thank you for creating this beautiful blog. I want to create a custom button on a Activity Tracker object (record), which should create an Opportunity record by using the data from Activity Tracker object record and Task object record. How can I write the code to populate the fields on opportunity record using two different records?

  17. Leonie says:

    Lovely just what I was looking for. Thanks to the author for taking his time on this one.

Leave a Reply