3

How can I take a URL parameter and pass it to a custom controller method? For example, I have a button from a case that goes to VF page with its ID in the url. (ex - https://visual.force.com/apex/CustomSearch?caseID=18238345iu3) I want to then press a button on the VF page that will execute a method from my custom controller and use the case ID parameter found in the URL.

Thanks.

3 Answers 3

12

When passing parameters in a URL, you can grab the parameter values in your Visualforce Controller by using:

String thecaseID = System.currentPageReference().getParameters().get('caseID');
1
  • Hey gus! nice to see you! Jun 16, 2015 at 17:12
4

Simply use this inside your method:

String caseID = Apexpages.currentPage().getParameters().get('caseID');

And then use caseID for anything you want.

3

Change the name of the parameter to simply "Id", the standard controller will handle it automatically.

Add your custom methods to an Extension controller instead.

<apex:page standardController="Case" 
    extensions="MyCustomCaseControllerExt" showHeader="false">
    <apex:outputText value="{!foo}" />
</apex:page>

In the controller, you don't explicitly have to fetch the Id, it's already done and available to you as you can get the record directly with getRecord()

public class myCaseControllerExtension {

    private final Case myCase;

    // The extension constructor initializes the private member
    // variable Case by using the getRecord method from the standard
    // controller.
    public myCaseControllerExtension(ApexPages.StandardController stdController) {
        this.myCase = (Case)stdController.getRecord();
    }

    public String foo() {
        return 'Something interesting  (' + myCase.id + ')';
    }
}

See: Build an Extension Controller

3
  • Actually you would still need to do stdController.getId() where stdController is the instance of the standardController sent into the extension's constructor. This enables us to do a bit of delegation of code to the standard controller methods Jun 16, 2015 at 18:26
  • I'm revising the answer to include the Extension controller implementation. Yes, you could get that Id in the controller, or it's implicitly already there to be used in the constructor as evidenced by the fact that the getRecord() method works. Jun 17, 2015 at 20:08
  • What you're saying works in all the cases, but getRecord() does something more than just fetch the ID. It fetches all the referenced field values on the page, including ID. It would be better if you could make this distinction, so a naive reader can make an informed choice based on his/her use case :) Jun 21, 2015 at 11:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .