URL Parameters within Apex and Visualforce

28 Sep

Get a URL parameter from a Visualforce page

String MyParameter = ApexPages.currentPage().getParameters().get('urlparm');

Get a map of URL parameters from a Visualforce page

Map UrlParameterMap = ApexPages.currentPage().getParameters();
// check for a specific parameter
if (UrlParameterMap.containsKey('urlparm')){
  //do something with the parameter... UrlParameterMap.get('urlparm')
}       

Get URL Parameters in a Visualforce page

This assumes the URL is looks like this, “http://www.salesforce.com/apex/MyPage?urlparm=something”.


Put values into Visualforce page’s URL and load a new page

Method 1: write out the URL

public PageReference MyPageMethod() {
  String MyParameter = 'something';

  // redirect to a Visualforce page containing a url parm
  PageReference MyNewPage = new PageReference('/apex/newvfpage?urlparm=' + MyParameter);    
  // -or- redirect to a records page
  PageReference MyNewPage = new PageReference('/' + MyObj.Id);

  MyNewPage.setRedirect(true);
  return MyNewPage;
}

Method 2: Put parameters into a PageReference

public PageReference MyPageMethod() {
  String MyParameter = 'something';

  PageReference MyNewPage = Page.PageTwo;
  MyNewPage.getParameters().put('urlparm',MyParameter);

  MyNewPage.setRedirect(true);
  return MyNewPage;
}

Put values into the current test page’s URL in a Test Class

@isTest
private class MyControllerTest {
  static testMethod void myUnitTest() {
    // create a new page reference, set it as the current page, 
    // and use the ApexPages.currentPage() method to put the values
    PageReference PageRef = Page.MyPage;
    Test.setCurrentPage(PageRef);
    ApexPages.currentPage().getParameters().put('urlparm', 'theValue');      

    // load the controller and proceed with testing
    MyController controller = new MyController();
  }
}

Salesforce Help

$CurrentPage Documentation
Controller Navigation Methods
Visualforce Parameters

2 Replies to “URL Parameters within Apex and Visualforce

Comments are closed.