+ Start a Discussion
Ravi kumar 292Ravi kumar 292 

How to call an Apex Class when clicking on Custom Button

Hi all,

I have a scenario. Whenever i click on a custom button it will call the apex class. The class consists of some webservice call. That means when i click on button it will call the webservice end point.. We can achieve this by creating VF page and Apex class but i dont want to create a VF page.

How to do this..
Help on this.. 
Create a custom button and use following code for call webservice on custom button
  1. {!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
  2. {!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}
  3. var result = sforce.apex.execute("InvoiceUtilities","renumberLineItems",{invoiceName:"{!
  4. Invoice__c.Name}"});
  5. alert(result);
  6. window.location.reload();
Apex Code for webservice 
  1. global with sharing class InvoiceUtilities {
  2.    // Class method to renumber Line Items for a given Invoice number.
  3.    // Returns a string that indicates success or failure.
  4.    webservice static String renumberLineItems(String invoiceName) {
  6.       // Create a copy of the target Invoice object and its Line Items.
  7.       Invoice__c invoice = 
  8.          [SELECT i.Name, (SELECT Name FROM Line_Items__r ORDER BY Name)
  9.           FROM Invoice__c i
  10.           WHERE i.Name = :invoiceName LIMIT 1];
  12.       // Loop through each Line Item, renumbering as you go.
  13.       Integer i = 1;
  14.       for (Line_Item__c item : invoice.Line_Items__r) {
  15.          item.Name = String.valueOf(i);
  16.          System.debug(item.Name);
  17.          i++;
  18.       }
  20.       // Update the Line Items in one transaction, rollback if any problems
  21.       // and return error messages to the calling environment.
  22.       try {
  23.          Database.update(invoice.Line_Items__r);
  24.       }
  25.       catch (DmlException e) {
  26.          return e.getMessage();
  27.       }
  29.       // On success, return a message to the calling program.
  30.       return 'Line items renumbered successfully.';
  31.    }
  32. }

This is great and I've used it for a couple of years now in a small way.  i have recently had reason to extend the Apex Web service and have run into Code Coverage issues when deploying.  The problem is I cannot get the tests to run the Web Service code and cannot figure out how to fire it from within the test class.  Do you have any idea how I can do this?

Any help greatfully accepted.