1

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.

7

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');
  • Hey gus! nice to see you! – Caspar Harmer Jun 16 '15 at 17:12
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

  • 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 – anonymousBlock Jun 16 '15 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. – Bobby White Jun 17 '15 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 :) – anonymousBlock Jun 21 '15 at 11:07
2

Simply use this inside your method:

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

And then use caseID for anything you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.