I have add custom button for salesforce's Sales application's 'Opportunities' tab. Once press that button I want to navigate some new tab (I have done it by adding proper URL) and execute following Apex method. How can execute this method. Thanks.
public class JobService {
private JobDao job_dao = new JobDao();
public void insertJob() {
Job__c newJob = new Job__c();
job_dao.insertJob(newJob);
}
}
I have accomplished this task as following way,
Add following java script codes to, custom button's javaScript 'onClick' section.
{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}
//Get Opportunity id
var opId= "{!Opportunity.Id}";
//Call insertJob method by passing that Opportunity id
sforce.apex.execute("JobService","insertJob",{op_id:opId});
//Redirect to that tab
window.location = 'https://ap1.salesforce.com/a0G/o';
Note:
- Thank you very much for Adam & Jeremy Ross for their guide, those are
very much helpful to me.
- Please add some comment if any one know, how can I retrieve
Opportunity' object rather than retrieve 'Opportunity.Id', thanks.
You've got a couple of options:
VF Page
Create a VF page. In the page's controller, call your Apex method, then forward user to the new tab
JavaScript
Expose a simple web service that calls your apex Method. Make the button an "onclick javascript" button and call the web service (see Exposing Apex Classes as REST Web Services and Apex in AJAX for how to do this). Forward the user to the new tab.
Create a lean Visualforce page with Opportunity as your controller and a custom class as an extension:
<apex:page standardController="Opportunity" extensions="RedirectClass" action="{!redirect}"/>
The extension (Apex) can look like the following:
// On load, action="{!redirect}" takes us here
public PageReference redirect()
{
return Page.YourVisualforcePageWithATab;
}
Go to: Name|Setup|Customize|Opportunities|Buttons and Links| New
Select Visualforce Page in Content Source and then this visualforce "redirect" page you just created in the Content field. That should do it.