Invoking Apex from a Custom Button using a Visualforce Page

This post is about creating a custom button to be placed in a detail page using Visualforce page instead of an S-control (deprecated). I will be using Opportunity object for this example.

The Controller:

public class VFController
{
    private final ApexPages.StandardController theController;
    public List listOpps = new List();

    public VFController(ApexPages.StandardController stdController)
    {
          theController = stdController;
    }
    // Code we will invoke on page load.
    public PageReference autoRun()
    {
        for (Opportunity opp:[select id, name from Opportunity where id =:theController.getId()])
            {
	        opp.Name = opp.name + ' test';
                listOpps.add(opp);
	    }
		Database.update(listOpps);

	return theController.view().setRedirect(true);
    }
}

The Visualforce Page:

You don’t need to do anything special here. The most important part here is the parameter action = “{!autoRun}”.




You shoudn't see this page...

After that, go to Setup –> App Setup –> Customize –> Opportunities –> Buttons and Links. Add a new custom button with the following configuration.

This example simply appends “test” to the Opportunity name when you click on that custom button. This is only to show you that it works. Hope this helps. 🙂

Join the Conversation

1 Comment

  1. Hi Cathy,

    I saw your profile on Odesk under Salesforce contractors. I am contacting you right now, since I have an ongoing Force.com development project that you might be interested in.

    Please contact me anytime, if you are interested. I also have a full-time job opportunity that you might want to discuss with me, too.

    Thank you! 🙂

    Regards,

    Carmela

Leave a comment

Your email address will not be published. Required fields are marked *