在Salesforce中,你可以通过自定义JavaScript按钮或链接来触发Apex代码的执行。这可以通过使用JavaScript Remoting或Visualforce页面来实现。以下是一些步骤来将JavaScript按钮与Apex代码链接起来:
使用JavaScript Remoting链接JavaScript按钮到Apex代码:
@RemoteAction注解来标记方法,以便从JavaScript中调用它。public class MyApexController {
@RemoteAction
public static String executeApexCode() {
// 在这里编写你的Apex代码
// 返回任何结果
return 'Apex code executed successfully';
}
}
{!REQUIRESCRIPT("/soap/ajax/41.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/41.0/apex.js")}
var result = sforce.apex.execute("MyApexController", "executeApexCode", {});
// 处理Apex代码执行的结果
alert(result);
使用Visualforce页面链接JavaScript按钮到Apex代码:
标签的standardController属性指定对象,然后在页面中包含JavaScript按钮。<apex:page standardController="Your_Object__c">
<script>
function executeApexCode() {
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.MyApexController.executeApexCode}',
function(result, event) {
if (event.status) {
// 处理Apex代码执行的结果
alert(result);
} else {
// 处理错误
alert('Error: ' + event.message);
}
}
);
}
script>
<button onclick="executeApexCode();">Execute Apex Codebutton>
apex:page>
这些步骤将使你能够通过JavaScript按钮或链接执行Apex代码。确保在Apex代码中包含所需的逻辑,并根据需要处理结果。同时,确保在按钮或链接的可见性和访问控制方面进行适当的设置,以确保只有授权的用户可以执行Apex代码。
Calling a Lightning component from a Classic custom button involves a slightly different approach than doing it in Lightning Experience. Here’s how you can achieve this:
Create a Visualforce Page:
To bridge the gap between Classic and Lightning components, you can create a Visualforce page that contains your Lightning component.
Here’s an example of what the Visualforce page might look like:
<apex:page >
<apex:includeLightning />
<div id="lightning-component-container">div>
<script>
$Lightning.use("c:YourApp", function() {
$Lightning.createComponent(
"c:YourLightningComponent",
{},
"lightning-component-container",
function(component) {}
);
});
script>
apex:page>
"c:YourApp" with the name of your Lightning app (if applicable) and "c:YourLightningComponent" with the name of your Lightning component.Create a Custom Button in Classic:
Choose Button Behavior:
Configure Button Properties:
Add the Button to Page Layout:
Test the Custom Button:
This approach leverages a Visualforce page as a bridge between Classic and Lightning components. When the custom button is clicked, it loads the Visualforce page, which then embeds and initializes your Lightning component.