
Force.com Cookbook Sample Code
Chapter 4: Best Practices for Writing Apex - Defining an Force.com Web Service and Calling It from an S-Control
To download all the code samples, access the Cookbook. -
This HTML s-control is part of a simple scenario in which Apex is used to define a simple "Hello World" Web service which is then called from an s-control that's displayed in a Web tab.
<html>
<head>
<script type="text/javascript" src="/js/functions.js"></script>
<script src="/soap/ajax/10.0/connection.js"></script>
<script src="/soap/ajax/10.0/apex.js"></script>
<script>
function demo() {
// The apex.execute() command in the AJAX Toolkit
// allows the s-control to access the specified
// Apex class and method.
var result = sforce.apex.execute('HelloWorld2' , 'sayHelloWorld', {arg:"new Apex user!"});
// The next block of code runs any testMethods
// you've written for the HelloWorld2 class
sforce.apex.debug=true;
var request = new sforce.RunTestsRequest();
request.allTests = false;
request.classes = ['HelloWorld2'];
var result_2= sforce.apex.runTests(request);
// Alternatively you can uncomment this block to run
// all of the testMethods you've written.
// sforce.apex.debug=true;
// var request = new sforce.RunTestsRequest();
// request.allTests = true;
// var result_2 = sforce.apex.runTests(request);
// Now display the final result, including the test
// results.
document.getElementById('userNameArea').innerHTML = 'Congratulations! ' + result + '<p>Tests Run = ' + result_2.numTestsRun + ';Test Failures = ' + result_2.numFailures + '</p>';
// Or uncomment the following block to display the
// entire debug log.
// document.getElementById('userNameArea').innerHTML= 'Congratulations! ' + result + '<p>Tests Run = ' + result_2.numTestsRun + '; Test Failures = ' + result_2.numFailures + '</p><p> Full print out = ' + result_2 + '</p>';
}
</script>
</head>
<body onload=demo()>
<div id=userNameArea>
</div>
</body>
</html>
Sample code provided by salesforce.com. All rights reserved.