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

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.
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
  • 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");
  • 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';
acct.phone = '515-123-4567';
  • Now that I have all my fields defined, I’m ready to save the new record.
var result = sforce.connection.create([acct]);
  • 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.
if(result[0].getBoolean("success")){
window.location = "/" + result[0].id + "/e";
}else{
alert('Could not create record '+result);
}

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.

34 Comments

  1. […] 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:

    Hi!
    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:

      window.open("/" + result[0].id + "/e");

      I’m not certain if the domain portion of the URL (ie: https://naX.salesforce.com) 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:

    {!REQUIRESCRIPT(“/soap/ajax/30.0/connection.js”)}

    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]);

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

    • Hi Jen,

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

      You might have to put cO1.id 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

  5. Shannon says:

    Terry,

    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.

    Thanks,

    Shannon

    • 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 (https://www.hometeamconsulting.com/url-hacking-for-salesforce-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:

    Hi..
    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)

    {!REQUIRESCRIPT(“/soap/ajax/29.0/connection.js”)}
    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]);

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

    • 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.

      {!REQUIRESCRIPT(“/soap/ajax/29.0/connection.js”)}
      // identify the parent record
      var t = new sforce.SObject(“Treatment__c”);
      t.id = “{!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 = t.id;
      treat.Description__c = “Test”;

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

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

  7. Ali says:

    Thanks a lot. It actually worked.

  8. 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!

    {!REQUIRESCRIPT(“/soap/ajax/29.0/connection.js”)}
    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]);
    if(result[0].getBoolean(“success”)){
    window.location = “/” + result[0].id + “/e”;
    }else{
    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:

    {!REQUIRESCRIPT(“/soap/ajax/20.0/connection.js”)}

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

    ‘;
    pdfOverlay.summlid=”0EHo0000001E982″;
    pdfOverlay.setSavable(true);
    pdfOverlay.setContents(‘/quote/quoteTemplateDataViewer.apexp?id={!(Quote.Id)}’,’/quote/quoteTemplateHeaderData.apexp?id={!(Quote.Id)}’);pdfOverlay.display();

    Any help would be appreciated

  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. http://www.codebycody.com/2016/11/custom-html-dialog-box-on-standard-salesforce-page-layouts.html

    • 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:

    Hello,
    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.

    {!REQUIRESCRIPT(“/soap/ajax/29.0/connection.js”)}

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

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

    OBChecklist.Initial_Onboarding_Case__c = C.Id;

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

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

    • 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!

    • 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.

      • 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

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

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

        Sales_Opportunity__c.Name='{!Sales_Leads__c.Account_Company__c}’;
        Sales_Opportunity__c.Account_Office_Company__c='{!Sales_Leads__c.Account_Company__c}’;
        Sales_Opportunity__c.Lead_Prospect_Contact_Last_Name__c='{!Sales_Leads__c.Name}’;
        Sales_Opportunity__c.Lead_Source__c='{!Sales_Leads__c.Lead_Source__c}’;
        Sales_Opportunity__c.Office__c='{!Sales_Leads__c.Office__c}’;

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

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

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

        • try this:

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

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

          SM.Name="{!Sales_Leads__c.Account_Company__c}";
          SM.Account_Office_Company__c="{!Sales_Leads__c.Account_Company__c}";
          SM.Lead_Prospect_Contact_Last_Name__c="{!Sales_Leads__c.Name}";
          SM.Lead_Source__c="{!Sales_Leads__c.Lead_Source__c}";
          SM.Office__c="{!Sales_Leads__c.Office__c}";

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

          if(result[0].getBoolean(“success”)){
          window.location = “/” + result[0].id + “/e”;
          }else{
          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