LogoLogo
Back to studio
  • Formsort documentation
  • โฉQuickstart
    • ๐ŸŸขGet started with Formsort
    • ๐ŸŽCore concepts
    • โ„น๏ธQuestion and content reference
    • ๐Ÿ“•Key terms
    • ๐Ÿž๏ธCreate your first flow
    • ๐Ÿ“–Add content and collect answers
      • ๐ŸคณCapture demographic data
      • โ„น๏ธAdd informational content
      • ๐Ÿ” Review your variable schema
    • ๐ŸŽจCreate a theme
      • Set brand guidelines
    • ๐ŸคนPersonalize your flow
      • ๐ŸŒŸTemplate your variables
      • ๐Ÿง Add conditional logic
      • ๐Ÿ’ซUsing conditional logic with Calculated and API variables
      • ๐Ÿ”šEnd the flow
    • ๐Ÿ”€Set up integrations
    • ๐Ÿš€Go live
      • Auditing your flow for content, functionality, and design
    • ๐Ÿ’ผCommon use cases
      • ๐Ÿ’”Disqualify responders
      • ๐Ÿ—“๏ธAdd a scheduling option
      • ๐Ÿ“„Allow responders to read and accept your company policies
  • ๐Ÿ—๏ธBuilding flows
    • Flows and variants
      • Flow starts
    • Adding content
      • Groups
      • Steps
        • Settings
        • Logic
        • Style
      • Questions
        • General Settings
        • Style
        • Address
        • Comparison
        • Confirmation
        • Date
        • Date & Time
        • Email address
        • File upload
        • Grid choice
        • Iframe
        • Image upload
        • Number
        • Payment
        • Phone number
        • Postal code
        • Question group
        • Region
        • Select
          • Providing choices via API or calculation
        • Signature
        • SSN
        • Text questions
        • Yes/No
      • Content
        • General Settings
        • Statement
        • Image
        • Video
        • Next button
        • Divider
        • Map
      • Endings
      • Using markdown
      • Using variable templating
        • Template formatting functions
      • Copy-pasting form content
      • Content library
    • Conditions and logic
      • Logical operator reference
      • Advanced logic
    • Variables (answers)
      • Variables from questions
      • Externally provided variables
      • Calculated variables
      • API lookups
      • System Library variables
      • Orphaned variables
    • Schemas
      • JSON Schemas
      • Validating flow schemas
    • Redirects
    • Styling and themes
      • CSS Reference
      • Overriding theme styling
      • Custom CSS overrides
      • Content area
      • Animations and transitions
      • Form Layout
      • Typography
        • Adobe Fonts
        • Hosting custom fonts
      • Color variables
      • Dimension variables
      • Question containers
      • Assets
      • Form Buttons
        • Select buttons
      • Inputs and dropdowns
      • Checkmarks
      • Tables
      • Sliders
      • Divider lines
      • Progress bar
      • Comparison cards
    • Variant settings
      • Form behavior for returning responders
      • Group ranking API
    • Publishing and versions
      • Preview window
      • Deploying
      • History
  • ๐Ÿ’พHandling data
    • Philosophy and data retention policy
    • Viewing form answers
    • Responder UUIDs
    • Environments
      • Loading different environments
    • Passing data in
      • URL parameters
      • POST body
      • Embed query parameters
    • Custom validators
    • Form answers and events
      • Analytics events
      • Signed requests
      • Event payload shape
      • Submission frequencies
      • Runtime error reporting
      • Admin API
      • Flow content data format
    • Integration reference
      • Amplitude
        • Amplitude cross domain tracking
      • BigQuery
      • FullStory
      • Google Analytics
        • Updating from Universal Analytics to GA4
      • Google Cloud Storage
      • Google Sheets
      • Google Tag Manager (GTM)
        • JavaScript triggered by flow events
      • Hubspot
      • Jornaya
      • Optimizely
      • PostgreSQL
      • Redshift
      • Rudderstack
      • S3
      • Salesforce
      • Segment
        • Segment Setup
        • Segment cross domain tracking
      • Stripe
      • TrustedForm
      • Webhooks
        • Zapier
  • ๐Ÿ“บGoing live
    • Custom domains
    • Built-in analytics
    • Embedding
      • Web-Embed API
        • React-embed
      • Adding authentication
      • Embedding forms in iOS and Android
      • Setting up a dev environment
    • Split testing
    • Preflight checklist
  • ๐ŸขTeams
    • Accounts
      • Roles and permissions
    • Events subscriptions
    • Workspace domain detection
Powered by GitBook
On this page
  • Using calculated variables to hide questions
  • Ex 1:
  • Ex 2:
  • Using API variables to hide questions
  • Example

Was this helpful?

  1. Quickstart
  2. Personalize your flow

Using conditional logic with Calculated and API variables

Conditionally render questions with advanced calculations

PreviousAdd conditional logicNextEnd the flow

Last updated 2 years ago

Was this helpful?

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.

First, letโ€™s create a question to capture the userโ€™s 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!

Using API variables to hide questions

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

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

  • 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โ€.

  • 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.

Setting logic against a 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 .

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

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

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.

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

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

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

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

โฉ
๐Ÿคน
๐Ÿ’ซ
date object
number
Date
docs
API variables
template
World Time API
select question
variable type
API Variable documentation
Add the calculated variable
The Calculated variable editor
Setting up the variable
Navigate to Step logic menu
Adding the step logic
Naming our variable
Set the dependent variable
Adding Step logic
Creating the Step logic
The inline Step logic indicator
Creating our Select question
Naming the variable
Adding the API variable
Example call with area: America and region: Denver
Open the available variables menu
Grab the variable we want
Paste the variable into URL path
Error?
Success! Denver is in MST