Flow and FinishLocation

pulling-hair-out-321x300Have you tried using Flows with Visualforce pages and tried to set the finishLocation to a dynamic value?  Odds are yes, and odds are even better that you had (or are having) no end of frustrations trying to get it to fire right.

The key to get your dynamic finishLocation to fire right is to factor your PageReference in such a way where as you are progressing through the flow and while the wrapper Visualforce page is rerendering, you can effectively capture and utilize Flow output variables.

To start, let’s embed a flow in a Visualforce page:

<apex:page controller="flowController">
<flow:interview name="DemoFlow" interview="{!flDemo}" finishLocation="{!prFinishLocation}" />
</apex:page>

You’ll note that the “interview” attribute is in use.  That is one of the necessary steps to make this work – you need to link your Flow to the controller.

public class flowController{
// Instanciate the Flow for use by the Controller - linked by VF "interview" attribute
 public Flow.Interview.DemoFlow flDemo {get;set;}

 // Factor your PageReference as a full GET/SET
 public PageReference prFinishLocation {
 get {
 PageReference prRef = new PageReference('/your/page/location?var1= + strOutputVariable);
 prRef.setRedirect(true);
 return prRef;
 }
 set { prFinishLocation = value; }
 }

 // Factor your Flow output variable pull as a full GET / SET
 public String strOutputVariable {
 get {
 String strTemp = '';

 if(flDemo != null) {
 strTemp = string.valueOf(flDemo.getVariableValue('your flow output variable name');
 }

 return strTemp;
 }

 set { strOutputVariable = value; }
 } 

}

You’ll see that both the finishLocation’s PageReference as well as the variable that captures the Flow’s output variable are all in fully broken out GET/SET logic.  Factoring your code in this manner is the trick; as you move through the flow, the Visualforce page re-renders each time the user progresses through a Flow Screen.

**NOTE!  There is also a trick to how your actual Flow is set up.  For instance – if your Flow is creating a Contact and you want to direct the user to that Contact’s standard detail record upon completion of the Flow, you will need to have one last screen at the end to force the Visualforce page re-render so your controller can grab that Contact’s Id.

**ANOTHER NOTE!  You will NOT be able to get 100% test coverage when you link Flow to a controller like this.  Because Flow requires user-interaction, if you try and reference the “flDemo” variable from the example above without first checking to see if it’s null (which it will be in the Unit Test), your test will fail.  There is NO way right now (confirmed by Salesforce) to full test a Flow using this method…don’t pull your hair out trying.

Good luck!  Hit me up in the comments if you have other great Flow hacks or if you have issues getting this method to work.

Thanks for reading!