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
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>
var acct = new sforce.SObject("Account");<br>
acct.name = 'New Account';<br> acct.phone = '515-123-4567';<br>
var result = sforce.connection.create([acct]);<br>
<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!
34 Comments
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.
Hi Tina,
Can you post your code or email it to me? I’m not seeing it on your comment.
See: https://help.salesforce.com/HTViewSolution?id=000007604&language=en_US
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.
Lara, I believe all you’d need to do is replace:
with:
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.
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. 🙂
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
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.
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 (http://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!
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);
}
Thanks a lot. It actually worked.
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);
}
Hi Michael,
I believe you just need to add “acct.” in front of your field names. ie: acct.Lender_1_c=’National Funding”;
Many thanks very valuable. Will certainly share website with my friends
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
Here’s a post that sounds similar to what you’re doing; perhaps it will help. http://sforce.co/2azAe4L
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.
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.
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”. “
Just skip the last step.
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
Share with me your code and I’ll take a quick look.
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.
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);
}
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?
Lovely just what I was looking for. Thanks to the author for taking his time on this one.