function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SesameTomSesameTom 

Java script button- how to get object ID of object?

How do you get the ID of the specific object/record that a button was clicked for?

Best Answer chosen by Admin (Salesforce Developers) 
JitendraJitendra

Hi,

You can simply use the {!Account.Id} to access the current account ID.

 

Try this:

 

{!REQUIRESCRIPT
  ("/soap/ajax/14.0/connection.js")}
 
  var account = new sforce.SObject("Account");
 
  account.ID = '{!Account.Id}';
 
  account.Test_Field__c = 'hello';
 
  result = sforce.connection.update([account]);
 
  window.location.reload();

 

All Answers

JitendraJitendra

Hi,

Can you please explain more? Where the button is? In VF page or Page Layout, Type of button etc

SesameTomSesameTom

Sorry to not originally supply this information.  This is my first button and post.

 

The button is on the regular account details page at the top where custom buttons go.  It is:

  • A Detail Page Button
  • Execute JavaScript
  • OnClick JavaScript

 

  Based on reading SFDC help and other sources on the web I got it to do JavaScript, update an account, and redisplay the page to see the results.  But I had to hard code the account ID to do this as I have not found out how to get the ID of the account that the button was clicked on.  My test button so far has this in it:

  {!REQUIRESCRIPT

  ("/soap/ajax/14.0/connection.js")}

 

  var account = new sforce.SObject("Account");

 

  account.ID = '001E000000JAtSX';

 

  account.Test_Field__c = 'hello';

 

  result = sforce.connection.update([account]);

 

  window.location.reload();

 

I have the need to manipulate various fields in the account record when the button is clicked.  It appears that I have the basics except the ID of the account.

JitendraJitendra

Hi,

You can simply use the {!Account.Id} to access the current account ID.

 

Try this:

 

{!REQUIRESCRIPT
  ("/soap/ajax/14.0/connection.js")}
 
  var account = new sforce.SObject("Account");
 
  account.ID = '{!Account.Id}';
 
  account.Test_Field__c = 'hello';
 
  result = sforce.connection.update([account]);
 
  window.location.reload();

 

This was selected as the best answer
SesameTomSesameTom

Changing account.ID = '001E000000JAtSX'; to be account.ID = {!Account.Id}; gets this error at run time:

     identifier starts immediately after numeric literal

 

And this is the syntax that the documentation leads me to believe is correct.  So, what else could be wrong?  Especially when I assign a fixed ID value it works.

JitendraJitendra

Please try this:

 

account.ID = '{!Account.Id}';
SesameTomSesameTom

Hello:

 

  Double quotes around it also works.

 

Thanks,