Update (2/23/2011): The new custom scripting documentation is live! Head over here to check it out: www.surveygizmo.com/documentation/scripting/
SurveyGizmo has some amazing logic and survey flow features, but sometimes you need to go beyond what’s available in the core application and add special functionality to your survey.
That’s why we added custom scripting to SurveyGizmo.
The scripting language you are about to learn will allow you to achieve any number of application in SurveyGizmo. Here are a few sample uses:
- Negative option piping (piping unselected items from a question into a follow-up question)
- Calculations
- Looking up reference data and using it in the current survey
- Executing complex logic, randomization and branching
- Accessing environmental variables not available using merge codes
- Create PDF documents with custom drawings and text
Getting Started
The SurveyGizmo Scripting action allows you to create complex logic and calculations from within your survey to extend the base behavior of SurveyGizmo.
The Script Action can be added to your survey by clicking [Add Action] in the bottom-right of each survey page and selecting “Custom Script.”
Like Questions, Actions are survey elements that must be placed on a page. These actions are then processed in order (with questions) from the top of the page to the bottom when the page is rendered. Keep this in mind if you are setting values for questions using custom scripting. If the question has already been rendered (because it is above the custom script on the same page) you won’t see the effect of your script when you run your survey. This is simply because the HTML for the question has already been rendered.
Syntax
Scripting actions follows similar rules to PHP with several exceptions noted below. Actually, scripting was originally pure PHP, but for security reasons it now uses a sand-boxed interpreter.
- You cannot define classes and any functions you create must start with ‘sgapi’
- The following control structures are available: for, foreach, if, elseif, else, while, and switch.
- The standard functions you can call are listed in this guide.
- All variables begin with %% rather than $ (all other rules are the same).
- %%output is your output stream. It will display text & html directly to the survey page.
Example Script
Hello World, Script
This script represents a VERY basic custom script. It displays the words “Hello, World!” inline in the survey where the action is.
//---- start script %%output = "Hello, World!"; //---- end script
Good Morning/Afternoon Script
This function is a little more complex. It shows you how to use custom scripting functions such as sgapiDate. The script will show “Good Morning” if the current hour is less than 12 and “Good Afternoon” if it’s greater than or equal to 12.
This script also shows you how to construct an if statement.
//---- start script
%%hour = sgapiDate("H"); //get the hour in 24 hour format
if(%%hour < 12)
{
%%output = "Good Morning";
}
else
{
%%output = "Good Afternoon";
}
//---- end script
Concatenating Output
Many times you’ll want to build up output over time and display it. For example, you want to build up a table of information to display in your survey from an array. This example shows you how to loop through and array of information and how to display it in a table while concatenating to the %%output variable.
//---- start script
%%array_of_example_data = array();
%%array_of_example_data[] = array("Dogs",12);
%%array_of_example_data[] = array("Cats",10);
%%array_of_example_data[] = array("Grapes",5);
%%output = "<table border=1 >";
foreach(%%array_of_example_data as %%record)
{
%%output .= "<tr>";
%%output .= "<td>" . %%record[0] . "</td>";
%%output .= "<td>" . %%record[1] . "</td>";
%%output .= "</tr>";
}
%%output .= "</table>";
//---- end script
Negative Option Piping
Piping is the term SurveyGizmo uses for repeating a page or question based on the answer to a previous question in the survey. SurveyGizmo has many features an options for this, but one feature that has not been added to the core platform is the ability to pipe off of options that were *not* selected in the source question.
For example, let’s say that you asked the question: Which cars from this list did you test drive at our dealership?
Now you want to ask the survey taker which cars they might want to drive in a future visit. In this question you want to show items that were unselected in the first question. This is how:
//---- start script
//the 2 questions must be separated by one or more pages.
//place this script on the same page as the 2nd question (but above it on the page).
//question IDs
%%source = 2;
%%dest = 4;
//get the selected options from the source question
%%selected_data = sgapiGetValue(%%source);
//remove selected options from the target question
//for this to work, the 2nd question needs to have all of the options that we have in the 1st question.
foreach (%%selected_data as %%key => %%value)
{
sgapiRemoveOption(%%dest,%%value);
}
//---- end script
Script Functions
These are the bulk of the SurveyGizmo Scripting functions available to the script control.
sgapiSubmitSurvey()
This function records the current survey as a ‘partial’. It also records a snapshot of the survey information for immediate reporting
sgapiSubmitSurveyComplete()
This function submits the survey as a “Complete”. All collected data in the survey is also submitted to reporting.
sgapiGetValue(%%questionID)
This function gets the value of an answered question (or null, if not answered) and returns it. In most cases, a single value is returned (a string). The following question types will return an array with the keys assigned as [O0], [O1], [O2], etc. and the values as the entered/selected values in the survey:
Example
- Multiple Text Fields
- Checkbox (The number in the key represents the Option sku, first option listed in the survey is 0)
- Image Choice (Multi-Select)
- Ranking – Table Format (Returns the rank of each column in order)
- Continuous Sum
- A single row of a Table of Checkboxes
- A single row of a Table of Drop-Down Menus
- A single row of a Table of Textboxes
- A single row of a Star Ranking Table
Note: The Multiple Drop-Downs question type is not accessible via sgapiGetValue.
sgapiSetQuestionProperty(%%questionid, %%property, %value) [v3 only]
This function sets the given property to the given value for the given question.
Example
sgapiIsAnswered(%%questionID) [v3 only]
This function returns Boolean true if the given question has been answered.
sgapiQuestionsAnsweredOnPage(%%page,%%options) [v3 only]
This function returns a count of answered questions in a given page. %%options can be used to filter by question type. It accepts the following values as a comma separated string: RANK,RADIO,CHECKBOX,TEXTBOX,MULTI_TEXTBOX,TABLE,GROUP,MENU,LIST,CONT_SUM
sgapiCheckboxTotalChecked(%%questionID)
This function returns the number of checkboxes selected for the given question.
sgapiGetScore(%%questionID) [Depricated in v3]
This function is identical to the function sgapiGetValue.
sgapiURLValue(%%name)
This function returns the value of a query string variable passed into the survey where ‘%%name’ is the name of the url variable.
sgapiResultsQuestionTotal(%%questionID)
The next real-time reporting function. This returns the total answer for the question id given across all completed surveys in real time. For instance, if you ask in a textbox question for the number of guests (an Auto-Format as Whole Number text field question), this function can be used to get a total number of guests entered in so far by all previous respondents.
sgapiGetQuestionResponseCount(%%questionID,%%osku = null)
This is also a real-time reporting function. It allows you to query the number of times a question has been answered. It’s a count, not an average. By passing an “option sku” you can see how many times a question was answered a particular way. This function is very useful for programming quota limits! Helpful Tip: %%osku should be quoted out “%%osku” to avoid issues with an osku of zero.
sgapiGetQueryResponseCount(%%name)
This function returns the number of responses (completes) that have been collected for the current survey. It take an optional “%%name” parameter that filters by a URL variable. %%name should be in the format of: “urlvar_VariableName=Value”. Thus, to filter for a variable called ‘domain’ and a value called ‘bob.com’, you would use:
%%name = 'urlvar_domain=bob.com';
sgapiSetValue(%%questionID,%%value)
This function populates the response of a hidden, text, essay, radio button, or drop-down menu question when %%value is a ‘string’. If %%value is an array(), you can populate a checkbox question. This can also be used for a list of drop-downs, radio button table/matrix, and checkbox table/matrix if you specify the %%questionID of the table’s row (not the table’s question ID) and submit the appropriate format of %%value. You can also use it set script content to write dynamic scripts!
NOTE: When setting values on the same page, the custom script must be at the top of the page!
sgapiSetTitle(%%questionID,%%value,%%language = “English”)
This function sets the title of a question or the text of a description area. HTML is allowed.
sgapiGetTitle(%%questionID,%%language = “English”)
This function returns the ‘title’ of a question.
sgapiAddContactToInvite(%%linkid, %%emailaddress, %%fields) [v3 only]
This function adds a contact with the list of given fields to the given invite.
sgapiRemoveContactFromInvite(%%linkid, %%emailaddress) [v3 only]
This function removes the given contact from the given invite.
sgapiSetHTMLEmail(%%questionID,%%value,%%language = “English”)
This function sets the content of an HTML email (auto-responder).
sgapiSetTEXTEmail(%%questionID,%%value,%%language = “English”)
This function sets the TEXT version of an auto-responder’s body content.
sgapiGetQuestionOptionSelected(%%questionID)
This function is deprecated and should not be used. Use sgapiGetValue.
This function returns a zero-based index of the option selected for a Radio, Multi-Select Menu, Image Select or Drop-Down Menu question. (If the question is randomized, the index is based on the un-randomized version of that question).
sgapiGetQuestionOptions(%%questionID, %%type)[v3 only]
This function returns an array of options for the given question, options can either be type “Reporting” or “Title” (default for type is “Title”).
sgapiHideQuestion(%%questionID,%%hide)
This function hides or shows a question (the %%hide attribute is set to ‘true’ [without quotes, lowercase] to hide and ‘false’ [without quotes, lowercase] to show).
sgapiShowPage(%%pageID,%%show)
This function shows or hides a page (the %%show attribute is set to ‘true’ [without quotes, lowercase] to show and ‘false’ [without quotes, lowercase] to hide), default is to show it (‘true’) [without quotes, lowercase].
sgapiHidePage(%%pageID,%%show)
Pending future upgrade. Place a feature request if you would like to express interest in this function.
sgapiRemoveOption(%%questionID,%%option)
This is the scripting way of doing Dynamic Show/Hide. This function removes (hides) a multiple choice option (by reporting value as %%option). For table questions it hides the column associated with that option for all rows.
Example
sgapiSetRequired(%%questionID,%%req)
This function toggles the “Required” status of a question (the %%req attribute is set to ‘true’ [no quotes, lowercase] to require and ‘false’ [no quotes, lowercase] to not require).
sgapiAllQuestionsOfType(%%type,%%pagenumber = 1)
This function returns an array of all the questions (of a particular type) on a particular page. Possible values for %%type: “RADIO”, “CHECKBOX”…
sgapiTrimStr(%%value)
This function trims a string of trailing and preceding whitespace.
sgapiStrPos(%%haystack,%%needle,%%offset = 0)
This function returns the offset of a substring within a string.
sgapiSubStr(%%string,%%offset = 0,%%len = 255)
This function returns a substring of a string based on length and position.
sgapiStrLen(%%string)
This function returns the length of a string.
sgapiStr_replace(%%search,%%replace,%%subject)
This function looks for %%search inside of %%subject and overwrites %%search with %%replace.
sgapiIsArray(%%string)
Evaluates as ‘true’ if the variable is an array.
sgapiCSVSplit(%%string)
Splits the given string into an array (comma separated values).
sgapiCount(%%array)
Returns the number of elements in an array.
Show/Hide Example
sgapiArraySet(%%array,%%index,%%string)
Sets the value of an item with an array (supports hash tables).
sgapiArrayGet(%%array,%%index)
Gets the value of an item in an array.
sgapiJumpToPage(%%pageID)
This function jumps the survey taker to the specified page ID. Hover your mouse over the ‘Delete Page’ option on the target page and look at the bottom of the browser window for the target URL. The variable qid=## gives you the page id number.
Note:Be advised there can be a conflict when using this function to jump to a page that has the same Page ID as the Page Number of the script.
Fix: Copy the page that is the target of the jump, delete the original page, and use the new Page ID.
sgapiDisqualify(%%message)
This function disqualifies the user and ends the survey, displaying a customized message to the user.
sgapiCreateLoopCount(%%increment)
This function creates an array of numbers (1 to 500) that can be used to power a loop.
sgapiURLDecode(%%string) [v3 only]
This function runs the PHP urldecode function on the given value and returns the results.
sgapiParseURL(%%url, %%part) [v3 only]
This function runs the PHP parse_url function and returns the results (default for part is 1).
sgapiNumberFormat(%%value, %%decimals) [v3 only]
This function runs the PHP number_format function on the given value using the parameter decimals (default is 0).
sgapiStrToLower(%%string) [v3 only]
This function returns the given string in all lower case using the PHP function strtolower.
sgapiFullChop(%%string) [v3 only]
This function runs the PHP rtrim and ltrim function on the given value and returns the results.
sgapiIConv(%%in_charset, %%out_carset, %%String) [v3 only]
This function uses the PHP function iconv to convert the given string to the requested character encoding.
sgapiStrtotime(%%string,%%time)
This function takes a string and converts it to a Unix timestamp, relative to the timestamp %%time. %%time is optional.
sgapiDate(%%format,%%time)
This function converts %%time, a Unix timestamp, into a human readable date and time. %%time is optional and defaults to the current time. See the PHP date() function for possible values of %%format.
sgapiReferrer(%%url) [v3 only]
This function runs the URL the survey taker came from.
sgapiGetResponseBySGUID(%%surveyid,%%sguid)
This function does not work in version 3 of SurveyGizmo
This function will return an array of the status, responseid and the edit link for any response associated with that SGUID and survey. Evaluates as false if the SGUID does not exist.
sgapiOpenSurveyResponse(%%responseguid) [v3 only]
This function sets the response data for this response to the response data of another response.
sgapiList(%%surveyid, %%page, %%countperpage, %filtering) [v3 only]
This function returns the list of responses for the given survey (default for page=1, countperpage=50, filterstring=null). This function is used as a way to pull data from the Rest API.
Example
sgapiListAdd(%%surveyID, %%item) [v3 only]
This function post a response to the given survey using the array of item. This function is used as a way to push data through the Rest API.
sgapiListRemove(%%surveyID, %%itemid) [v3 only]
This function removes the given response from the given survey. This function is used as a way to remove data through the Rest API.
sgapidListReplace(%%surveyID, %%itemID, %item) [v3 only]
This function replaces the given response for the given survey with the array of item. This function is used as a way to replace data through the Rest API.
sgapiSetSGUID(%%sguid) [v3 only]
This function sets the sguid for the current response.
sgapiGetResponseData(%%surveyid, %%responseid, %%sguid) [v3 only]
This function returns full data for a given response.
sgapiGetRespondantResponseID(%%surveyid) [v3 only]
This function gets the responseid for the current response.
sgapiSetSGUID(%%sguid) [v3 only]
This function sets the sguid for the current response.
sgapiGetSGUID() [v3 only]
This function returns the sguid for the current response.
sgapiRandomizeTable(%%questionID)
Given the Question ID of a table, this function will shuffle the rows of the table and return the newly ordered rows. (NOTE: The table has already been shuffled after the function call, the return is just useful for seeing the new order of the rows.)
sgapiGetTableQuestionTitles(%%questionID)
This function accepts the Question ID of a table and returns an array in the following format: [questionID] => ‘title’ (i.e. the question id is the key and the title is the value for each item in the array).
sgapiGetTableQuestionSkus(%%tablesku) [v3 only]
This function returns an array of skus for the given table.
sgapiGetPipeSkus(%%questionid) [v3 only]
This function returns an array of skus=>values for the given piped question.
sgapiGetPipeValues(%%questionid) [v3 only]
This function returns an array values for the given piped question.
sgapiSetPipeValues(%%questionid, %%array) [v3 only]
This function pipes the given question for each element of the array.
sgapiPipeMatrixRows(%%questionID, %%rows) [v3 only]
This function pipes the given rows into the given Custom Table question.
sgapiSetTableOrderByTable(%%tableID,%%referenceTableID,%%language=’English’)
This function accepts two table Question IDs and orders the rows of the %%tableID Table by the %%referenceTableID. Useful when carrying down randomized table rows to a copy of the original table.
sgapiSetCustomTableValue(%%questionID, %%rowname, %%value) [v3 only]
This function allows you to set the value for a row in a custom table question.
sgapiRunAction(%%questionID)[v3 only]
This function causes the given action to run and returns true if it is successful (returns false if given questionid isn’t an action).
sgapiSetPageStartingNumber(%%question_num)[v3 only]
This function sets the number of the first question of the page (Default is 1).
sgapiImplode(%%glue, %%pieces)
Like the PHP implode() function. Given an array of %%pieces it will create a string delimited by the string %%glue.
sgapiExplode(%%delimiter, %%string, %%limit=null)
Like the PHP explode() function. Given a string %%string it will create an array breaking the string up by %%delimiter. Limit is optional. If set, the returned array will only contain up to %%limit elements.
sgapiPrint_R(%%mixed)
Given any variable it will return a string of that variable’s contents. Use with %%output to print to the screen. Very useful when looking at arrays of data or objects.
Example
sgapiShuffle(&%%array)
Given an array this function will randomly reorder the array. It will evaluate as true on success and false on failure.
sgapiArray_Pop(%%array)
Given an array this function will return the last element of the array and remove that element from the array itself.
Show/Hide Example
sgapiArray_Diff(%%array1,%%array2)
Given two arrays this function will compare %%array2 against %%array1 and return an array of values that are present in %%array1 but not present in %%array2.
sgapiArrayMerge(%%array1,%%array2)
Given two arrays this function will append the elements of %%array2 to the end of %%array1 and return combined elements (the array is reindexed).
sgapiArrayUnique(%%array1)
Given an array, this function will remove any elements that contain duplicate values and return the deduped array.
sgapiArray_Flip(%%array1)
Given an array this function will exchange an element’s key with that element’s value and return the resulting array.
sgapiSort(%%array, %%flag) [v3 only]
This function runs the PHP sort function on the given array using the flag parameter (default is “SORT_REGULAR”).
sgapiASort(%%array, %%flag) [v3 only]
This function runs the PHP asort function on the given array using the flag parameter (default is “SORT_REGULAR”).
sgapiCurrentPageTitle()
This function will return the title of the page it is currently on. This is useful if you’ll be copying the script and moving it to different pages.
sgapiURLEncode(%%str)
Given a string this function will URL encode it making your links safe.
sgapiRand(%%min, %%max)
Generates a random number (typically 9 or 10 digits long). If the optional %%min and %%max integers are specified, it will generate a number between %%min and %%max instead. Randomization is by Mersenne twister.
sgapiRound(%%number,%%decimal=0)
Returns the %%number rounded to the nearest whole number by default. If the optional %%decimal is also included, it defines the number of decimal positions to include.
sgapiSqrt(%%number)
Returns the square root of the value in %%number.
sgapiLog(%%number,%%base=10)
Returns the natural logarith of %%number. If %%base is provided (optional), it is used in the following mathematical fashion: Log%%base%%number
sgapiPow(%%base,%%power)
Returns the value of %%base raised to the power of %%power. Mathematically written as: %%base%%power
sgapiIs_Null(%%variable)
Returns either TRUE or FALSE if the variable passed is Null. This is equivalent to the is_null function in PHP. Note: it is a capital i and capital n in the function name.
sgapiMd5(%%string)
Returns the MD5 hash of the provided string. Can be used to compare two strings for an exact match by comparing their MD5 hash values.
sgapiStrCaseCmp(%%str1,%%str2,%%case=false)
This function will compare %%str1 with %%str2 in a case-insensitive manner (default), returning the results as either a negative number (str1 < str2), 0 (match), or a positive number (str1 > str2) in the same manner as the PHP StrCaseCmp function. If the optional %%case is passed as ‘true’ (no quotes, lowercase), the comparison will be case-sensitive like the PHP StrCmp function.
sgapiEvaluateMergeCodes(%%code) [v3 only]
This function returns the value for the given merge code.
sgapiNewPDF(%%pdftitle, %%paper, %%orientation) [v3 only]
This function creates a pdf object that you can build and store (%%paper and %%orientation are null by default).
sgapisetFontPDF(%%pdftitle, %%font, %%style) [v3 only]
This function set the font and style of the given pdf (%%font is ‘Helvetica’ and %%style is ‘Null’ by default).
sgapiSetColorPDF(%%pdftitle, %%r, %%g, %%b) [v3 only]
This function sets the text color for the given pdf (%%r, %%g, %%b are set to 0 by default).
sgapiNewPagePDF(%%pdftitle) [v3 only]
This function creates a new page in the given pdf.
sgapiTextPDF(%%pdftitle, %%text, %%size, %%options, %%test) [v3 only]
This function adds text to the given PDF.
sgapiTablePDF(%%pdftitle, %%data, %%cols, %%title, %%options) [v3 only]
This function adds a table to the given PDF.
sgapiImagePDF(%%pdftitle, %%image, %%pad, %%width, %%resize, %%just, %%border) [v3 only]
This function adds an image to the given PDF.
sgapiClosePDF(%%pdftitle) [v3 only]
This function closes the given PDF object .
sgapiPDFOutput(%%pdftitle, %%options, %%close) [v3 only]
This function returns the output of your pdf.
sgapiEmailSend(%%to, %%toName, %%from, %%fromName, %%subject, %%textBody, %%htmlBody, %%bbc, %%mailReplayTo, %%type, %%attachments) [v3 only]
This function constructs and sends an email at the runtime of your custom script.
The %%output Variable
%%output literally is echo’d to the page, where the custom script is present. If there is a problem with the script, it will not output properly. Imagine, in PHP terms, that whatever is captured in the %%output variable would be subject to this automatically at the end of the script:
echo %%output;
That is what happens automatically. It does NOT need to be added (and would create an error) to your script. Thus, assign values or concatenated values works fine. Example:
%%output = "This is a test. This is a " . sgapiGetValue(%%variable); %%output .= ""; %%output .= sgapiPrint_R(%%array);
Example Script
This script example adds up all the checkboxes that are checked on the first and second pages of a survey.
If they choose 10 items then it submits the survey.
If they choose over 10 it disqualifies them (throws them out of the survey).
Less than ten and they are free to proceed to the current (next) page.
%%pagestocheck[] = 1;
%%pagestocheck[] = 2;
%%total = 0;
foreach(%%pagestocheck as %%page)
{
%%questionIDs = sgapiAllQuestionsOfType("CHECKBOX",%%page);
foreach(%%questionIDs as %%questionID)
{
%%total += sgapiCheckboxTotalChecked(%%questionID);
}
}
if(%%total == 10){
sgapiSubmitSurvey();
}
if(%%total > 10){
%%over = %%total - 10;
%%msg = "
<h1>You have selected %%total nominees.</h1>
<h1>";
%%msg .= "I'm sorry but that's<span style="color: red;"> ".%%over." too many. </span></h1>
Thanks for your time.";
sgapiDisqualify(%%msg);
}
else
{
%%output = "Thus far you have selected ".%%total." nominees";
}Example Script #2
This script will check two fields for matching data. If the data does not match, it jumps back to that page.
/*=========Variables=========*/ %%field1 = 3; //Question ID of first textbox %%field2 = 4; //Question ID of second textbox %%pageid = 1; //Page ID of page containing field1 and field2 /*=========Script=========*/ %%vala = sgapiGetValue(%%field1); %%valb = sgapiGetValue(%%field2); if (%%vala != %%valb) sgapiJumpToPage(%%pageid);
Example Script #3
This script prechecks the values of a checkbox question (general categories, Q2) based upon selections in a previous checkbox question (Q1).
Q1 has a Question ID of 7 and has the options of:
- UK
- China
- HK
Q2 is on a later page, has a Question ID of 11, and has the options of:
- Eastern
- Western
/*=========Variables=========*/
%%questionid1 = 5;
%%questionid2 = 11;
/*=========Script=========*/
%%answerarray = array();
foreach (sgapiGetValue(%%questionid1) as %%value){
switch(%%value){
case 'UK':
%%answerarray[1] = 'Western';
break;
case 'China':
case 'HK':
%%answerarray[2] = 'Eastern';
break;
}
}
sgapiSetValue(%%questionid2,%%answerarray);Equals Sign ( =, ==, ===, !=, and !== )
The following content is adapted from an article on the equals sign in PHP.
There are 3 primary uses of the equals sign within Custom Scripting:
- Assignment ( = ): Assigns the value on the right to the %%variable on the left
- Equality ( == ): Checks if the left and right values are equal (used in IF statements!)
- Identical ( === ): Checks if the left and right values are equal AND the identical type (’1′ is a string, 1 is an integer; not identical)
Secondarily, there is also the use of the exclamation point to state not:
- Not Equal ( != ): Checks if the left and right values are not equal
- Not Identical ( !== ): Checks if the left and right values are not equal and not identical
%%a = 1; // Sets the value of $a as 1 by assignment
%%b = TRUE; // Sets the value of $b to the boolean TRUE
if (%%a == %%b){
%%output = 'a is equal to b.';
}
if (%%a === %%b){
%%output = 'a is identical and equal to b.';
}Output: a is equal to b.
%%a = 1; // Sets the value of $a as 1 by assignment
if (%%a != 2){ // if %%a is not equal to 2 then this is a TRUE statement and the IF will be executed
%%output = 'a does not equal 2.';
}Output: a does not equal 2.
As a rule of thumb, IF statements will not use a single equals sign within the evaluated section. Double-check your scripts to ensure your IF statements are double equals signs rather than a single equals sign inside of the parenthesis of an IF statement!
Control Structures
The following explanations are adapted from a PHP reference book, with permission.
if, elseIf, else
if (expr) {
// If expr is TRUE, do this, then exit the IF loop
}elseif (expr2) {
// If expr is FALSE, and expr2 is TRUE, do this, then exit the loop
}else{
// If all expr's are FALSE, do this, then exit
}There can be only one instance of else in an if statement, but multiple elseif expressions are allowed prior to the else statement.
Example:
%%x = 1;
if (%%x < 1){
%%output = '%%x is less than 1';
}elseif (%%x == 1){ // Note the double equals, for comparison
%%output = '%%x is equal to 1';
}else{
%%output = '%%x is neither equal to 1 or less than 1';
}Output: %%x is equal to 1
Switch
switch (expr) {
case value:
// Do this if value matches
break;
case value2:
// Do this if value2 matches
break;
default: // [optional]
// Do this if no other cases match. Does not have to be at the end
break;
}expr – A string, integer, or float to be compared against
A switch evaluates the expr against any number of cases or options, specifying the behavior for each case. Cases can be ‘stacked’ to allow the same portion of code to be evaluated for different cases:
switch (expr) {
case value:
case value2:
// Do this if value or value2 matches
}The switch is evaluated line-by-line, and therefore if there was no break command, the case declaration would effectively be ignored and the code would continue to be processed until the switch ends or a break; is reached.
%%x = 1;
switch (%%x) {
case 1:
%%output .= '1'; // Note the lack of a break;
case 2:
%%output .= '2'; // Without the break, this is processed line-by-line
}Output: 12
Finally, the default statement is optional, but defines what to do if no cases are matched. It can be used in troubleshooting to identify when you failed to include a case for an expected output.
Examples:
%%x = 2;
switch (%%x) {
case 1:
%%output .= '1';
break;
case 2:
%%output .= '2';
break;
case 3:
%%output .= '3';
break;
}Output: 2
%%x = 'howdy';
switch (%%x) {
case 'hi':
%%output .= 'Hi there';
break;
default: // Can be anywhere, all cases evaluated before it is used
%%output .= 'Greetings';
break;
case 'hello':
%%output .= 'Hello there';
break;
}Output: Greetings
while
while (expr) {
// If expr is TRUE, do this, then evaluate expr again
}The while loop checks the expr and if it evaluates as true, the script runs through the entire contents of the while until it finishes, then it evaluates the expr again and repeats until the expr evaluates as false.
Example:
%%x = 1;
while (%%x < = 3){
%%output .= "%%x, ";
%%x++; // increments %%x by adding 1. Short-hand version
}Output: 1, 2, 3,
do-while
do {
// Do this
} while (expr);The do-while loop performs whatever is inside the do statement, checks the expr, then if it evaluates as TRUE, runs through the entire contents of the do until it finishes, evaluating the expr again, and repeating until the expr evaluates as FALSE.
Example:
%%x = 1;
do {
%%output .= "%%x, ";
%%x++; // Makes %%x = 2, therefore the while will evaluate as false
} while (%%x < = 1);Output: 1,
for
for (expr1; expr2; expr3) {
// If expr2 is TRUE, do this
}When started, the for loop executes expr1 once at the beginning. Next, expr2 is evaluated. If expr2 is true, the code inside the for loop is executed. When the for loop reaches the end, expr3 is executed before looping and checking expr2 again.
Example:
for (%%x = 1; %%x < = 5; %%x++){
%%output .= %%x;
}Output: 12345
foreach
foreach (%%array as %%value){
// Do something
}
// Another form, for keys and values
foreach (%%array as %%key => %%value){
// Do something
}The foreach loop goes through all items in an array, assigning a temporary variable name for value and, if chosen, the key as well so they can be used within the executed code inside the loop.
Examples:
%%array = array('John' => 20, 'Jane' => 24, 'Joseph' => 28);
foreach (%%array as %%value){
%%output .= "$value, ";
}Output: 20, 24, 28,
foreach (%%array as %%name => %%age){
%%output .= %%name." - ".%%age;
%%output .= ''; // XHTML for a line break
}Output:
John – 20
Jane – 24
Joseph – 28
The following two items are used within control structures and perform specific tasks.
break [%%integer]
%%integer – [optional] Specifies the number of nested loops to break out of
Exits and stops execution of the current (default) for, foreach, while, do-while, or switch loop.
Example:
%%counter = 0;
while (1 == 1){ // Will run forever
while (0 == 0){ // Will also run forever
$counter++; // Increment $counter plus 1
%%output .= $counter;
if (%%counter == 5){
break 2;
}
}
%%output .= 'First while loop'; // Never displayed because of break 2;
break; // Never run, but if it did, would end the first while loop
}Output: 12345
continue [%%integer]
%%integer – [optional] Specifies the number of nested loops to skip out of
Note: The %%integer does not supply the number of iterations to skip, it always only stops the current iteration from continuing any further.
Skips the rest of the current loop iteration and if applicable, continues to the next iteration of the loop1.
Example:
for (%%x=1;%%x< =10;%%x++){
if (%%x == 5){
continue;
} // The output never occurs if %%x == 5
%%output .= %%x;
}Output: 1234678910
AND, OR, and XOR
SurveyGizmo’s scripting language supports the combination or comparison of values within a control structure using special syntax for AND, OR, and XOR:
- AND is represented as &&
- OR is represented as ||
- XOR is represented as xor
if (%%a < 5 && %%a != 0 ){
// if %%a is less than 5 AND %%a is not equal to 0
// then this is a TRUE statement and the IF will be executed
%%output = 'a is 1,2,3, or 4.';
}if (%%a < 5 || %%a > 10 ){
// if %%a is less than 5 OR %%a is greater than 10
// then this is a TRUE statement and the IF will be executed
%%output = 'a is less than 5 or greater than 10';
}Working Examples
sgapiGetValue & sgapiPrint_R
In this example, we return the value(s) of a checkbox question using sgapiGetValue() and sgapiPrint_R()
%%output .= sgapiPrint_R( sgapiGetValue(2) );
sgapiList
In this example there are two surveys: ‘Survey A’ and ‘Survey B’. Both surveys request the student ID number of the respondent. Survey B uses this function to check if the entered survey ID has been previously recorded on survey A.
See it in action (make sure to leave enough time for your first response to process):
Survey A
Survey B
//this script is located at the top of page 2 on survey B
%%id = 2; //2 is the id of the unique field
%%student = sgapiGetValue(%%id); //defines student as the ID
%%surveyA = 646222;
//check if the student completed survey A
%%status = sgapiList(%%surveyA,1,1,'&filter[field][0]=[question(2)]&filter[operator][0]==&filter[value][0]=' . %%student);
//set flag for whether or not Survey A has been completed
%%flag = 3; //3 is the ID of the completed question
if(sgapiCount(%%status['data']) == 0){
sgapiSetValue(%%flag,'No');
}else{
sgapiSetValue(%%flag,'Yes');
}sgapiSetQuestionProperty
This script randomizes the orientation of the target question
%%questionid = 2;
%%property = "orientation";
%%random = sgapiRand(0,1);
if (%%random == 0) {
%%value = "VERT";
}else{
%%value = "HORZ";
}
sgapiSetQuestionProperty(%%questionid,%%property,%%value);sgapiRemoveOption
Here, we use the function sgapiRemoveOption to remove an option from a question based on the answer to a previous question.
%%q1 = 4; %%q2 = 8; %%value1 = sgapiGetValue(%%q1); sgapiRemoveOption(%%q2,%%value1);