Activity › Forums › Salesforce® Discussions › How to execute Apex from Custom button or Javascript?
Tagged: Custom Button, Javascript, Salesforce Apex, Salesforce SOQL
-
How to execute Apex from Custom button or Javascript?
Posted by Nauman on March 22, 2016 at 12:05 PMI would really appreciate if you could share an example….
Parul replied 7 years, 7 months ago 6 Members · 7 Replies -
7 Replies
-
We can call any apex method through JavaScript by following function:
sforce.apex.execute(“class_Name”,”Method_Name”,{Parameter_Name:Parameter_Value}); - [adinserter block='9']
-
In this case you can use apex action function.
-
Example
VF Page—
<apex:page Controller=”myController”>
<apex:form>
<apex:actionFunction name=”callAction” action=”{!myFunction}” />
<button type=”button” onclick=”callAction()“>Call My Function</button>
<apex:outputPanel rendered=”{!panel}”>
Controller function Called.
</apex:outputPanel>
</apex:form>
</apex:page>Apex Class—
public class myController {
public Boolean panel {get;set;}
public myController(){
panel = false;
}
public void myFunction(){
panel = true;
}
} -
{!requireScript(“/soap/ajax/20.0/connection.js”)}
{!requireScript(“/soap/ajax/20.0/apex.js”)}retStr = sforce.apex.execute(“Testapex”, “method()”,{});
the class which you are calling must be a global class
global Testapex{
global void method(){
}
} -
Hi,
global class MyClass
{
webservice static void myMethod() // you can pass parameters
{
// Do something
}
}Now create a custom button:
Goto –> Setup –> Object –> Buttons, links and Actions section–>Click New Button or Link.
Enter the Name of the button
Behaviour : Execute Javascript
Content source : On-Click Javascriptuse below JS:
{!REQUIRESCRIPT(“/soap/ajax/30.0/connection.js”)}
{!REQUIRESCRIPT(“/soap/ajax/30.0/apex.js”)}if({!Account__c.Name}!=Null)
{
sforce.apex.execute(“SampleClass”,”sampleMethod”,{}”});
alert(“This is {!Account__c.Name}”);
}Thanks
-
Hi,
You need to create action function in vf page which will call apex, action function will be called by js.
So indirectly you are calling apex from js.
Hope this helps.
-
Hi,
Example –
You have to make use of AJAX toolkit to call the method in Apex Controller.
{!REQUIRESCRIPT(“/soap/ajax/30.0/connection.js”)}
{!REQUIRESCRIPT(“/soap/ajax/30.0/apex.js”)}
//sforce.apex.execute(“classname”,”methodname”,”parameters seperated by comma”);
sforce.apex.execute(“classname”,”removeItemFromEbayList”);
The consideration for this is that the class and the methods should be global and webservice. so you should modify the access modifier in your class to global and method from public to webservice.Hope this helps.
-
Hi,
Refer the above example to execute Apex using Javascript and custom button. It provide you solution
Thanks
Log In to reply.