7

How does one to get query string parameters with apex in a controller and eventually into a visualforce page?

3 Answers 3

12

This would be a clean way to do it:

apexPages.currentPage().getParameters().get();

// For URL - http://test.salesforce.com/apex/helloworld?q=texas


//use the following
String queryString ='';
queryString = ApexPages.currentPage().getParameters().get('q');

Source

1
  • How can this answer get 12 upvotes? I wish there was a more full fledged example than this. What is written in Apex and example of it called in VF page?
    – compski
    Jan 13 at 3:54
7

Parameters passed to the page through URL can be accessed in controller using below syntax,

String parameterValue = ApexPages.currentPage().getParameters().get('parameterName');

Usually it is used in constructor of controller to get value and then do operations based on the parameter value.

1

Apex provides methods to get the current URL parameters.

The salesforce documentation PageReference class has information regarding getting the page instance and then getting query string parameters.

Example from the Salesforce documentation:

public class MyController {
   public Account getAccount() {
        return [SELECT Id, Name FROM Account
                WHERE Id = :ApexPages.currentPage().getParameters().get('Id')];
    }
}

VisualForce Page

<apex:page controller="MyController">
    <apex:pageBlock title="Retrieving Query String Parameters">
        You are viewing the {!account.name} account.
    </apex:pageBlock>
</apex:page>
2
  • 4
    This is a horrible example. You should not be querying records directly in a getter, nor should you ordinarily be grabbing the ID value from a query string; instead, you should be using the standardController attribute and allow Visualforce to query the account on your behalf.
    – sfdcfox
    Mar 20, 2015 at 15:39
  • 1
    @sfdcfox , I copied this from the salesforce documentation. Sorry i'm new. I guess this example is a bit niave. Could you possibly help me with a better example?
    – chrisjlee
    Mar 20, 2015 at 15:56

You must log in to answer this question.

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