You need to sign in to do that
Don't have an account?
SeattleSFDC
Custom button executing Javascript
So I'm trying to execute Javascript from a custom button on the Event object. The alert(result) is coming back with nothing even though it should be returning my oppResult object with the oppId and errormessage. Any ideas what I'm missing, or what needs to change?
The custom button:
{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")} {!REQUIRESCRIPT("/soap/ajax/25.0/apex.js")} var meetingID = '{!Event.Id}'; var agree = confirm("Are you sure you want to create an opportunity?"); if(agree){ var result = sforce.apex.execute("MeetingOpportunity","createOpportunity",{meetingID: meetingID}); alert(result); }
Class:
global class MeetingOpportunity { webservice static OppResult createOpportunity(ID meetingID){ OppResult res = new OppResult(); //based on logic set variables in the result object res.errorMsg = 'oh no something broke'; res.oppId = '01pW00000000000'; system.debug(res); return res; } global class OppResult{ global String errorMsg; global Id oppId; } }
Just change the below to use webservice keyword. It should fix your issue
All Answers
Using http://teachmesalesforce.wordpress.com/2011/05/02/call-apex-code-from-a-custom-button/ it looks like your js code is fine.
Two thoughts - It might be that your returning a full sObject to JS doesn't work. I would try a method that returns a number or string to confirm things are working.
The other thought is looking at your Apex Class you're not inserting the Opportunity. So you're returning a non inserted sobject. That might also be causing the issue.**Edit I really should read things more carefully. Brain automatically adding words not there.**What are you hoping to do after the button is clicked?
Just change the below to use webservice keyword. It should fix your issue
Thanks Kartik, that worked. I have another question though, the alert(result) works but I tried pulling out a single field from the object by doing (result.errorMsg) but I'm getting back "undefined". Any ideas?
hmm. the sforce.apex.execute generally returns the types as arrays. So try using result[0].errMsg. this should work
I personnally have never liked this solution, calling a webservice from JavaScript in a button.
If you are adding a button to Salesforce (as opposed to a web page), you are already on the platform.
I suggest creating a 1-line Visualforce page with a page statement which defines an "action" which is called in the controller extensio; I do this all the time :
- if you need to collect input from the user, displays messages, etc then do it in this VF page
- reuse the controller method you have already written to do whatever processing needs to be done
- if you need to display stuff after the call, return a new PageReference to another VF page to do that stuff.
I hope this helps. Sorry, I'm on my iPad so don't have sample code at hand : search "action" attribute of the <apex:page> marker.
Rup
Hope it clears your doubt.