๐Ÿ’ซUsing conditional logic with Calculated and API variables

Conditionally render questions with advanced calculations

There are plenty of reasons to conditionally render questions in your flow - that is, either present or hide questions because of specific conditions. Some factors may be based on the information your users provide in their answers, like rendering certain questions based on age, or it could be based on factors external to that, like a marketing team hiding an offer that is out of season.

Fortunately, the synergy between Formsortโ€™s conditional logic and API and Calculated variables allows us to automate when questions should be available to the users filling out our forms. But, like anything, this takes a little bit of configuring.

Using calculated variables to hide questions

The power of calculated variables lies in the flexibility they provide by using Javascript functions (in Typescript format). This requires a little bit of JS/TypeScript familiarity, but itโ€™s a powerful tool!

Below, weโ€™ll go over a couple examples of using Calculated Variables for creating logic.

Ex 1:

In this example function, weโ€™ll return a Boolean true/false value based on whether or not the user in inside or outside the hours of operation, which are 9am - 5pm, M-F. This will require no direct input from the user, but instead will draw the local time from their browser.

In the variant weโ€™re going to create this logic in, letโ€™s head to our Calculated Inline tab under Variables, and then into the Calculated variable editor.

Letโ€™s give the variable a name - weโ€™ll call this one dayparting_offers, change the Variable Type to Boolean so Formsort knows to expect a T/F return, and drop the code into the Getter Function Body.

You can check the function using the โ€œTest API variableโ€ section at the bottom of the editor.

Here is a copy of the code weโ€™re using:

function myFunction(): boolean { // readonly line
  var now = new Date();
  var hours_in_GMT = now.getUTCHours();
  var days_in_GMT = now.getDay();
  var days_in_desired_timezone = days_in_GMT;

  //time difference to GMT
  //In this case EST is 5 hours behind GMT
  var time_difference_to_desired_timezone = -5;

  var hours_in_desired_timezone = hours_in_GMT + time_difference_to_desired_timezone;

  //if its past midnight in GMT, make sure to adjust
  if (hours_in_desired_timezone < 0 ) { days_in_desired_timezone = (((days_in_desired_timezone - 1) +7) % 7);
 hours_in_desired_timezone = hours_in_desired_timezone + 24;
  }
  
//set the parameters for open hours using military time where Sunday is 0
  var start_time;
  var close_time;

  if ([1,2,3,4,5].indexOf(days_in_desired_timezone) > -1) {
  start_time = 9;
  close_time = 17;
  }

  else {
  start_time = 0;
  close_time = 0;
  }

  if (hours_in_desired_timezone < close_time && hours_in_desired_timezone >=   start_time) {
  return true;
  }

  else {
    return false;
  }
}    

Now, lets use this variable to create logic on steps we only want available inside the hours of operation.

  • In Content, head to the step weโ€™re putting the logic on. Here, it is going to be Step 1.

  • Click Logic โ†’ Show conditionally โ†’ Add conditionโ€ฆ

  • Select our variable dayparting_offers in the variable logic editor, and set it equal to true. Save condition.

  • You can repeat this on Step 2 as well, but instead set the variable value to false.

  • You should see that the step logic will be visible on the steps weโ€™ve set it on.

Now, depending on your local time, you will see either Step 1 or Step 2. Try it out in Live Preview!

Ex 2:

This next example will hide a step based on our userโ€™s age. This will require us to take the userโ€™s date of birth response as an input to our calculated variable, run a function that will return an age, and set our step logic based on that age.

Setting logic against a date object can be tricky and unreliable. If you opt to filter users based on their age, itโ€™s recommended to use this method, which sets logic against a number.

First, letโ€™s create a question to capture the userโ€™s dob.

  • At the desired step, choose โ€œAdd questionโ€ and select the Date component. Set the Variable name (weโ€™re using dob).

Now, we can take this input and dynamically create an age, depending on the userโ€™s answer.

Head to Calculated Inline in our Variables section, and โ€œAdd calculated variableโ€.

  • Give the function a name (weโ€™ll call this one age) and set the Variable Type to number so Formsort knows to expect an integer.

  • Toggle โ€œUses other variablesโ€, and select dob from your variable list.

  • Drop in the function

You can check the function using the โ€œTest API variableโ€ section at the bottom of the editor.

Here is a copy of the code weโ€™re using:

// dob is taken from our "Uses other variables" input
function myFunction(patient_dob: string): number { // readonly line
  const ageDifMs = Date.now() - (new Date(dob)).getTime();
  const ageDate = new Date(ageDifMs);
  return Math.abs(ageDate.getUTCFullYear() - 1970);
}

Now, lets use this variable to create logic on steps for users at or above a certain age.

  • In Content, head to the step weโ€™re putting the logic on. Here, it is going to be Step 3.

  • Click Logic โ†’ Show conditionally โ†’ Add conditionโ€ฆ

  • Select our variable age in the variable logic editor, and set it to greater than 17. Save condition.

Now, if our userโ€™s dob puts them at an age that is younger than 16, they will skip Step 3 and move right on to Step 4. Try it out in Live Preview!

For more information on Calculated Variables and the options in our Calculated Variable editor, see our docs!

Using API variables to hide questions

API variables make it possible to fetch data from a server that returns JSON responses. This server can be one you own, or it can be a 3rd party server that has information you need. As long as it returns a JSON response, and you can provide authentication into it (if necessary), we can ping it.

Once the API call returns the information we need, we can use the response to create logic on the steps we want to conditionally render.

Example

In the example below, we will template a userโ€™s response into our call to the World Time API to determine their timezone, and thus determine which questions to hide.

First, letโ€™s set up a question to find out where the user lives.

  • Head into your variant and create the question. Weโ€™re using a select question here to provide a list of possible responses for our user.

  • Give the variable name something recognizable. This question will have the variable name user_city.

Now, letโ€™s set up the API variable to return the time zone, based on the userโ€™s answer.

  • Head into Variables โ†’ API lookups and then โ€œ+Add api variableโ€.

  • Add a variable name, and set the variable type. Variable type is the expected data type weโ€™ll be receiving from the API response (i.e. string, number, boolean, object, array).

  • If we call this particular API with the area and region specified in the URL path, we will get an object return with the timezone information about the region.

  • Now that we know what kind of return to expect, we can add the variable value of user_city to our URL path, to make the API call dynamic.

    • Click โ€œVariablesโ€ฆโ€, select user_city, and paste the variable into the URL path.

  • Now, we can double check the API call using the Test API variable section to make sure weโ€™ll get the response we want. Select a value from the USER_CITY dropdown, then hit โ€œSend test requestโ€.

  • Looks like we have a matching result! All we want from this call is the value for the abbreviation field in our return. Letโ€™s use the JSON Accessor in Result processing.

  • We returned an error! The API editor is still expecting an object, but the JSON accessor is returning string value. Letโ€™s adjust our expected variable type and re-test.

We have the question we need to grab our userโ€™s city, and we have confirmed that our API call will work with that information. All thatโ€™s left to do is create logic on the questions we want to hide, depending on the userโ€™s time zone.

  • Letโ€™s create a Step that will not be available to users in โ€œMSTโ€. On that step, head to Logic, toggle Show conditionally on, and create the logic required. Save condition.

  • Now, when a user answers โ€œDenverโ€ to question 1, they will not see question 2, and will instead skip to question 3. Try it out in Live Preview!

This is one simple API variable use case, but there are a lot of different ways the API variable editor can be configured, like using a mapping function to parse API responses, adding a URL fallback in case the API is unavailable, or making the API fetch conditional on some other conditions.

Make sure to see our API Variable documentation, or, if youโ€™re like us, play around with it and see what you can do!

Last updated