0

I'm trying to create a button that Checks a checkbox field if the button is not checked when it's been clicked. If the checkbox is checked, I want it to uncheck the same box. I've written the code below, but it won't check the box when it's unchecked (it'll only uncheck it if it's checked)

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

var a = new sforce.SObject("Account");  
a.Id = "{!Account.Id}";     

if (a.Ownership_Requested__c = true) {
    a.Ownership_Requested__c = false;
} else {
    a.Ownership_Requested__c = true;
}

sforce.connection.update([a]);          
location.reload(true);
3
  • location.reload(true); will erase all unsaved data why you can't use workflow or process builder. Salesforce not in favor of Javascript buttons anymore if you are creating something new create the lightning component. For this create an action. help.salesforce.com/… trailhead.salesforce.com/en/modules/salesforce1_mobile_app/… Commented Jun 19, 2017 at 13:54
  • @AvijitChakraborty what unsaved data? the button won't be visible on the edit page, or if the page goes into inline edit mode. Also, a workflow field update or process builder can't be directly invoked by a button push. Commented Jun 19, 2017 at 13:57
  • Ok. But what about Global Action? Commented Jun 19, 2017 at 14:00

1 Answer 1

3

You use "==" or "===" for equality, and "=" for assignment. Also, you need to merge in the existing value first before you can determine if it's true or not. However, you generally don't need to check equality for a Boolean value, because it's already a Boolean, so we can just toggle it using "!" (the NOT operator).

So, your code would look like this:

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

var a = new sforce.SObject("Account");
// Assign the account Id to update
a.Id = "{!Account.Id}";
// Following line renders as "= !true" or "= !false", effectively toggling
// the value
a.Ownership_Requested__c = !{!Account.Ownership_Requested__c};
// Exercise for the reader: consider validating the API result
sforce.connection.update([a]);
window.location.reload(true);
2
  • Actually - I'm running into another issue: when logged in as any user who is not a System Admin, when I click the button, I get this error "Unexpected token ;" Any ideas? Commented Jun 20, 2017 at 13:49
  • @Shahab I ran into this too - the issue is that Salesforce passes Booleans as 1 and 0. So I just wrote a simple IF statement that starts with if("{!Account.Ownership_Requested__c}" == 1){ Commented Jan 23, 2019 at 20:19

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.