0

I am working on a custom button on Account detail page which is an Onclick javascript button. I am using the following logic behind the button:

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

var acct = new sforce.SObject("Account"); 
acct.accountId = "{!Account.Id}"; 
acct.MCode = "{!Account.MCountry__c}"; 
acct.MNumber = "{!Account.MNumber__c}"; 


if (acct.MCode == null || acct.MNumber == null){ 
alert("Country and M Number fields are mandatory ") 
} else { 
var response = sforce.apex.execute("Mtest", 
"Mtestmethod", 
{accountId:accountId}); 
if (response == 'true'){ 
alert("Updated successfully.") 
window.location.reload(); 
} else { 
alert("Details could not be updated "); 
} 

The logic of this button is that when any of the MCountry__c and MNumber__c fields are empty , an alert message should be displayed "Country and M Number fields are mandatory". Else if these fields contain values, the control should pass to the apex class.

However, in my case when I click on this button from the Account detail page an error message appears stating that 'accountId' is not defined.

I have never worked on javascript before. Can someone please help what is missing or wrong here.

0

Something like that would be better:

var country = "{!Account.MCountry__c}"; 
var number = "{!Account.MNumber__c}"; 
if (country == null || number == null) {
    alert("Details could not be updated ");
}
|improve this answer|||||
  • Even if I am using it this way : var country = "{!Account.MCountry__c}"; var number = "{!Account.MNumber__c}"; if (country == null || number == null) { alert("Details could not be updated "); } else { var response = sforce.apex.execute("Mtest", "Mtestmethod", {accountId:accountId}); the control gets passed to apex class even if the country and number fields are empty. I am trying to display the alert message whenever any of these fields is empty and the control should not pass to the apex class in case those fields are empty. – Div Snk Nov 6 '16 at 14:25
  • check also if field is empty: if (country == null || country == '' || number == null || number == '') – Itai Shmida Nov 6 '16 at 14:39
  • Thanks a lot man, this logic worked for me. Getting the desired results now. – Div Snk Nov 6 '16 at 14:48
  • Great, please mark this answer as a good one – Itai Shmida Nov 6 '16 at 14:50
  • 1
    @DivSnk There's no need to check for null; the value will always be either an empty string or not. Also, JavaScript doesn't need a comparison that way, you can simply write if(!country || !number). – sfdcfox Nov 6 '16 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.