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.
1 2 3 4 5 6 7 8 9 10 |
public class SuperGreatController { public String Id {get;set;} public String UrlHolder {get;set;} public void navigateToUrl() { UrlHolder = “www.whatagreatlink.com/” + Id; } } |
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.
1 2 3 4 5 |
<apex:actionFunction name=“passIdtoController” action=“{!navigateToUrl}” oncomplete=“window.open(‘{!UrlHolder}’);” > <!– set initial value of invoice id to null; current invoice id will be passed onclick –> <apex:param name=“p1” value=“” assignTo=“{!Id}”/> </apex:actionFunction> |
- 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.
1 2 |
<!– Return false is placed after method call to keep the page from refreshing automatically, before the method has finished running –> <apex:commandLink value=“Click Here” onclick=“passIdtoController(‘{!YourDynamicIDVariable}’);return false;”/> |