[SalesForce] Execute Apex Class with Button

I'm trying to create a button to execute an Apex Class with the Javascript attached. I'm getting the syntax error: Field object.id does not exist. Check spelling. What am I missing? What is window.location.href= looking for?

enter image description here

Error Msg

Global class InvoiceAccounts_Button {
  Webservice static void createInvoiceAccounts() {
    // Create a list of InvoiceAccounts
    List<InvoiceAccount__c> InvA_List = new List<InvoiceAccount__c> {
         new InvoiceAccount__c(Name='Kim_Button',Account_Owner_Name__c='Shain',Account_Owner_Title__c='Sir')};

    // Bulk insert all InvoiceAccount__cs with one DML call

    insert InvA_List;

  }
}

Best Answer

You have a few problems with your code. Take a closer look at the example for sforce.apex.execute. The first parameter is the class name, which in your case should be InvoiceAccounts_Button. The second value is the method name, which in your case should be createInvoiceAccounts. The third value is the arguments map, which in your case should be empty.

What you have:

sforce.apex.execute("InvoiceAccount", "createInvoiceAccounts", {});
//                  ^^^^^^^^^^^^^^^^ that's not the name of your class

What you should have:

sforce.apex.execute("InvoiceAccounts_Button", "createInvoiceAccounts", {});

Your second problem is in your merge field. You have {!Object.Id}, but where you have Object, you should instead have the API Name of your specific object.

What you have:

window.location.href = "/{!Object.Id}"

What you should have:

window.location.href = "/{!InvoiceAccount__c.Id}"

Even better:

window.location.href = "{!URLFOR($Action.InvoiceAccount__c.View, InvoiceAccount__c.Id)}"
Related Topic