Business Requirement
On user click of a link, we want to pass an ID to an Apex method. That Apex method then returns to us a URL string. We open a new window that loads that URL.

Technical Problem
We can call Apex methods and variables from Visualforce pages; however, passing parameters back and forth between Visualforce and Apex methods is not as intuitive – in fact, you can’t pass a parameter from a Visualforce  page directly to an Apex method.

  • Not supported: {!methodExample(param)} – you cannot call an Apex method from a Visualforce page that requires parameters
  • Supported: {!methodExample} – you can call an Apex method from a Visualforce page that takes no parameters

How can we pass our ID parameter to our Apex method from our Visualforce page?

Technical Solution
Apex class: We initialize the variable outside the method since we cannot pass parameters directly from the VF page. The navigateToUrl method sets the UrlHolder variable string based on the Id we pass it

Visualforce Page

  • Defining an ActionFunction
    We declare an actionFunction, which works like an Apex method, and name it passIdtoController. The actionFunction calls the navigateToUrl method and, once the method has run, opens a new window with the UrlHolder string. Using onComplete ensures the window won’t open until the method has set the UrlHolder. Note, we cannot access UrlHolder later in another method or actionfunction because our value will be gone.To tell the method which URL to retrieve/format, we pass a parameter called p1, leaving the initial value blank, and assign it to the Id variable in our Apex class. You can pass an actionFunction as many parameters as you like by adding more  <apex:param /> lines.

  • Calling the ActionFunction
    We call the passIdtoController function onclick of the link and pass it the variable which determines what URL will be retrieved in the navigateToUrl method.