Monday, January 6, 2014

Invoke Apex Code on Custom Button Click

Hello Accolades,

Description: Sometimes our requirement is like on custom button click, we want to invoke the Apex Class's method & perform some DML operations. There are different ways, but I think the following will be the best possible way.

Scenario: There will be a custom button on Standard Page, onClick of that CB you have to aggregate the Child fields on Standard/Custom object.

Steps to Follow:


1) Create a Custom Button named "Aggregate Child" on your object, Let's consider Stnadard Account as our object which will execute the JavaScript. In code panel you will import two Javascript files as follows:

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


2) Now next step will be create an Apex Class (Web Service) & Method, Call that method on this button Click.
So Let's say my controller Name is AccountController which will be global  & method will be aggregateChilds as Webservice.

global class AccountController1{
           webservice static void aggregateChilds(String accId){
                     Account accObje = new Account();
                     accObje = [SELECT id,(SELECT id FROM ChildObj__r) FROM Account WHERE id=: accID LIMIT 1];
                     System.debug(accObje.ChildObj__r.size());
                     
          /* 1) If you want to return the value. then Set the return type & get it in Javascript

              2) Perform DML Operation Whatever needed. */
              }
}

3) Call this method on Button's Javascript

{!REQUIRESCRIPT("/soap/ajax/14.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/14.0/apex.js")}
var res=sforce.apex.execute("AccountController","aggregateChilds",{accId:"{!Account.Id}"})


4) That's about it. If you can Customize the code as per your requirement. If you face any issues, feel free to mail me at shingavi.a@gmail.com
Happy Coding!!

No comments:

Post a Comment