Invoking Apex from a Button (JS –> Apex Web Service)

In January I posted about how to invoke Apex from a Custom Button using a Visualforce Page.  It has been a popular post and is a topic which is of interest to many developers.  I wanted to draw your attention to another post.  Sam Arjmandi, from Salesforce Source, posted about how to invoke Apex from a button by calling the Apex directly from JavaScript whereby the Apex must be available as a web service.

Both methods work just fine and there is a choice of approach.  Recently, my personal choice for implementing this kind of functionality is to use Sam’s approach and it’s mostly due to the user experience.  Using this approach, the code is called directly and there is no time spent by the browser needing to load a new blank page only to return to the same page.  It works much more seamlessly.  You also get the benefit of having less objects to develop (no VF page) and tie together.  The only real downside (outside of requirement-specific ones) is that Salesforce won’t bark at you if you delete the web service class because it doesn’t know that the web service is tied to JavaScript.  If your Apex Code is a controller for your VF page, Salesforce will protect you from deleting it accidentally.

2 Comments

  1. Danny Walker Said,

    July 20, 2009 @ 7:45 am

    The downside to this method is that it doesn’t allow you to return a PageReference. I’m trying to construct a wizard that starts on a different page depending on what values are required for the current task.

  2. Scott Hemmeter Said,

    July 20, 2009 @ 8:59 am

    @Danny

    I return a String in my methods. If it starts with “Error:”, I put up an alert box. If not, I will be returning a URL and I use window.location to redirect the user. Works well.

    In Apex, you can use PageReferences and then use the getUrl method to get the URL for send the user there.

RSS feed for comments on this post