You are on page 1of 246

Survey Programming Fundamentals Table of Contents

d
Table of Contents
Chapter 1 Introduction to Survey Programming ..................................................................................... 1
The Big Picture ........................................................................................................................................ 1
What is Survey Design About? ............................................................................................................ 2
The Survey Process ............................................................................................................................. .... 2
Dimensions Scripting Overview ................................................................................. ............................. 2
Interview Object Model .......................................................................................................................... 2
Object Oriented Programming ............................................................................................................... 3
What is Object Oriented Programming? ............................................................................................ 3
Dimensions Development Library Overview .......................................................................................... 3
Navigating the DDL ............................................................................................................................. 4
Examples ............................................................................................................................................. 4
DDL Links ............................................................................................................................................. 5
What is mrStudio? ............................................................................................................................. ..... 6
Whats Next?........................................................................................................................................... 7
Chapter 2 Constructing Questions........................................................................................................... 9
Metadata Items Format .......................................................................................................................... 9
Information Items ................................................................................................................................. 10
Numeric Questions ............................................................................................................................. .. 11
Minimum and Maximum Parameter Options................................................................................... 12
Text Questions ...................................................................................................................................... 12
Categorical ............................................................................................................................................ 14
Parameter Options Restricting the Number of Responses to be Chosen ...................................... 14
Date....................................................................................................................................................... 17
Boolean ................................................................................................................................................. 19
Chapter 3 Creating an mrStudio Interview Script.................................................................................. 21
Opening mrStudio ................................................................................................................................. 21
Overview of Toolbars/Shortcuts ........................................................................................................... 23
Formatting Toolbars ......................................................................................................................... 23
View Toolbar ..................................................................................................................................... 24
Interview Options Toolbar ................................................................................................................ 25

I
Table of Contents Survey Programming Fundamentals

Tips for Creating Metadata ................................................................................................................... 25


Viewing and Testing the Survey in mrStudio ........................................................................................ 26
Exercise ................................................................................................................................................. 28
Chapter 4 Special Responses and Options ............................................................................................ 31
Single Response Choices in Multiple Selection Questions ................................................................... 31
Special Responses with Categorical Questions..................................................................................... 34
Categorical Responses with NonCategorical Questions ...................................................................... 36
Collecting Other Text Responses in Categorical Questions .................................................................. 38
Subheading ........................................................................................................................................... 39
Exercise ..................................................................................................................... ............................ 42
Chapter 5 Basic Routing Logic................................................................................................................ 45
Asking Questions................................................................................................................................... 47
Read Only Items .................................................................................................................................... 49
Conditional Statements ........................................................................................................................ 50
If Then Else ......................................................................................................................... ......... 50
Select Case ............................................................................................................................................ 52
Goto ...................................................................................................................................................... 55
Logical Expressions ............................................................................................................................. .. 56
Numeric Questions ........................................................................................................................... 56
Boolean Questions ............................................................................................................................ 57
Text Questions ............................................................................................................................. ..... 57
Categorical Questions ....................................................................................................................... 58
Logical Operators .............................................................................................................................. 60
Tips for Routing Section Syntax ............................................................................................................ 62
Adding Error Handling........................................................................................................................... 63
Exercise ......................................................................................................................................... ........ 64
Chapter 6 Shared Lists ............................................................................................... ............................ 67
Creating Subheadings with Shared Lists ............................................................................................... 69
Chapter 7 Sorting Categorical Response Lists ....................................................................................... 73
Sorting in Metadata .............................................................................................................................. 74
Routing Section Sorting ........................................................................................................................ 75
Not Sorting Specific Responses............................................................................................................. 75

II
Survey Programming Fundamentals Table of Contents

Keeping Specific Categories Grouped Together ................................................................................... 77


Exercise ................................................................................................................................................. 78
Chapter 8 Restricting Responses ........................................................................................................... 79
Filter Categories .................................................................................................................................... 79
Limiting Numeric Question Ranges Based on Logic.............................................................................. 86
Exercise ............................................................................................................................. .................... 88
Chapter 9 Multiple Questions on One Page .......................................................................................... 91
Page......................................................................................................................... .............................. 92
Block...................................................................................................................................................... 94
Controlling How Page and Block Questions are Displayed ................................................................... 98
Filtering a Page/Block ....................................................................................................................... 98
Sorting a Page/Block ......................................................................................................................... 99
Exercise ............................................................................................................................. .................. 100
Chapter 10 Repetitive Questions Loops & Grids ............................................................................. 101
Categorical Loops/Grids ...................................................................................................................... 102
For Each loops ................................................................................................................................. 106
Categorical Loops with a Numeric Question .................................................................................. 108
Numeric Loops .................................................................................................................................... 111
Exercise ................................................................................ ............................................................... 114
Chapter 11 Debugging Tools within mrStudio................................................................................... 115
Auto Answer Questionnaire ............................................................................................................... 115
Producing Test Data ............................................................................................................................ 117
Adding Additional Data Sources ..................................................................................................... 119
Setting Breakpoints ............................................................................................................................. 120
Troubleshooting Specific Sections of Code......................................................................................... 121
Working with Macros.......................................................................................................................... 123
Updating/Deleting Existing Macros ................................................................................................ 123
Adding Additional Macros .............................................................................................................. 123
Chapter 12 Conditioned Loops and Grids .......................................................................................... 125
Previous Responses Within the Loop ................................................................................................. 125
Loops/Grids Filtered on Previous Responses Outside the Loop/Grid ................................................ 127
Loops/Grids Filtered on Responses to a Different Loop/Grids Questions......................................... 129

III
Table of Contents Survey Programming Fundamentals

Loops/Grids Filtered on a Sublist of Categories.................................................................................. 131


Exercise ............................................................................................................................. .................. 134
Chapter 13 Controlling the Look of Your Survey ............................................................................... 137
Overview of the Formatting of a Survey ............................................................................................. 137
Templates ........................................................................................................................................... 137
Applying a Template within Your Script. ........................................................................................ 139
Folders ............................................................................................................................................ 140
Tips for Scriptwriters Regarding Templates.................................................................................... 141
Styles ............................................................................................................................................. ...... 141
Default Styles ...................................................................................................................................... 141
Default ............................................................................................................................. ............... 142
Categories ....................................................................................................................................... 143
Grid ................................................................................................................................................. 144
Labels .............................................................................................................................................. 146
Navigation ....................................................................................................................................... 146
Questions ........................................................................................................................................ 147
Question Styles ................................................................................................................................... 148
Categorical Questions ..................................................................................................................... 148
Text Questions ................................................................................................................................ 149
Metadata Styles .................................................................................................................... .............. 150
Custom Controls ............................................................................................................................. .... 151
XHTML in Labels .................................................................................................................................. 151
What is XHTML? .............................................................................................................................. 151
Final Thoughts on Formatting............................................................................................................. 152
Exercise ............................................................................................................................. .................. 153
Chapter 14 Text Substitutions and Text Headings............................................................................. 155
Displaying Responses to Previous Questions ................................................................................ ..... 155
Insert Text into the Metadata that will be controlled in the routing section..................................... 158
Text Headings...................................................................................................................................... 162
Chapter 15 Enhancing Survey Flow ................................................................................................... 165
Must Answer ....................................................................................................................................... 166
Default Answers .................................................................................................................................. 166

IV
Survey Programming Fundamentals Table of Contents

Hidden default responses ............................................................................................................... 169


Initial Response ................................................................................................................................... 170
Exercise ............................................................................................................................. .................. 172
Chapter 16 Customizing the Standard Error Messages ..................................................................... 173
Global changes to error messages ...................................................................................................... 175
Error messages changes for a specific metadata file.......................................................................... 175
Error messages changes for a specific question ................................................................................. 176
Customizing the error message .......................................................................................................... 177
Chapter 17 Functions & Subroutines................................................................................................. 179
Definition of Functions and Subroutines ............................................................................................ 179
Subroutine ...................................................................................................................................... 180
Subroutine Example ............................................................................................................................ 180
Function .......................................................................................................................................... 184
Exercise ............................................................................................................................. .................. 188
Chapter 18 Validation ........................................................................................................................ 189
Validating Text Question Patterns ...................................................................................................... 189
Checking Custom Logic ....................................................................................................................... 192
Adding custom errors ......................................................................................................................... 193
Adding custom properties to metadata ......................................................................................... 198
Chapter 19 Compound Questions ..................................................................................................... 201
Defining Compound Questions ........................................................................................................... 201
Validating a compound question ........................................................................................................ 204
Compound vs. Loop ............................................................................................................................ 206
Chapter 20 Working with Sample ...................................................................................................... 207
Testing sample information within mrStudio ..................................................................................... 209
Alternative to Sample Management to pass information into the survey ......................................... 213
Chapter 21 Working with Quotas ...................................................................................................... 215
Defining Survey Quotas ...................................................................................................................... 215
Checking Quotas .......................................................................................... ....................................... 218
Quotas In mrStudio ......................................................................................................................... 221
Activation with Quotas ....................................................................................................................... 222
Viewing & Changing Quotas ............................................................................................................... 222

V
Table of Contents Survey Programming Fundamentals

Chapter 22 Creating MultiLingual Projects....................................................................................... 227


Overview of Translating Studies in Dimensions.................................................................................. 227
Setting the language within the script ................................................................................................ 228
Ask a question to collect and set the language .................................................................................. 228
Set language from a sample field variable.......................................................................................... 229
Tips for creating multilingual projects ............................................................................................... 230
Chapter 23 Additional information for Analysis ................................................................................ 231
Alternate Text for Analysis.................................................................................................................. 231
Adding Analysis Context with mrStudio ......................................................................................... 231
Factors................................................................................................................................................. 232
Creating Question Items for Analysis.................................................................................................. 233
ElementTypes............................................................................................................................ ...... 234
Axis Expressions .............................................................................................................................. 236
Tips creating analysis elements .......................................................................................................... 239
Summary ............................................................................................................................................. 239

VI
Survey Programming Fundamentals Chapter 1 Introduction to Survey Programming

Chapter 1 Introduction to Survey Programming


This course is designed to provide a firm foundation in understanding the Dimensions Scripting
language, specifically the task of programming surveys.

This chapter
p will contain::
An overview
e of the interview process

o of Dimensions scripting
A definition

An introduction
u to documentation and
d
mrStudio

The Big Picture


The overall process of running a survey can be grouped into three main categories.

Design: Creating the survey instrument and the questions associated with it
Collect: Collect the information required of the survey instrument
Report: Analyze the results and report the findings of the research

For each stage there are different tools we can use. For Dimensions this could look like

mrStudio S
SPSS
Build AActivity Reporter
mrInterview
mrPaper mrTables
m
mrDialer
D
Author mrStudio
mrScan
mrTranslate Clementine
C

1
Chapter 1 Introduction to Survey Programming Survey Programming Fundamentals

What is Survey Design About?


Here are some of the tasks involved in survey design:

Creating a quality survey instrument


Programming survey content and logic
Survey testing (Quality control)
Transferring the project to data collection servers (Activation)
Survey translation
Sample integration
Defining quotas

The Survey Process


The historic process for the survey process has at times been tedious. There are a lot of repetitive
tasks that take time and money. Dimensions is changing that paradigm. Dimensions scripting
allows users to incorporate more automation and reusable code in the process. Dimensions
scripting is one unified language for survey design, collection and reporting, so there is less
repetition and a more streamlined process.

Dimensions Scripting Overview


When working in mrStudio we will be using Dimensions Scripting. There are two languages in
Dimensions scripting.

Language Description
mrScriptBasic A programming language that is based on Microsoft VBScript.

mrScriptMetadata Proprietary Dimensions syntax used to define survey questions/


metadata.

When programming surveys we will make use of both languages. mrScriptMetadata will be used
to create the question for our survey. mrScriptBasic will control when and if we ask those
questions.

Interview Object Model


The Interview Object Model, typically referred to as IOM, is the foundation of survey programming in
Dimensions. IOM defines, for Dimensions, what the components of a survey are and what actions
we can take with each component.

2
Survey Programming Fundamentals Chapter 1 Introduction to Survey Programming

Object Oriented Programming


When programming a survey in Dimensions you will be using object oriented programming (OOP).

What is Object Oriented Programming?

A basic definition would read something like: A type of programming in which programmers define not
just the data type of a data structure, but also the types of operations (functions) that can be applied
to the data structure. In this way the data structure becomes an object that includes both data and
functionality.

If you have not been exposed to OOP in the past, the concepts and terminology can seem confusing at
times. However, don't get caught up in the terminology. If you understand the concept of creating a
questionnaire, then you can learn the content of this manual.

Think about OOP in terms of a survey. Specifically, let's look at a survey question as an object. A
question has question text, potential responses, as well as many other possible items. These are in fact
the data structure, what can make up part of a question. At the same time a question will require
functionality, such as asking the question or filtering the responses. These potential actions would
make up the operations that can be applied to the data structure. If this makes sense to you, then you
are on your way to grasping the concepts of OOP. (If it doesnt, this concept will make more sense as
you continue your learning.)

Dimensions Development Library Overview


Commonly referred to as the DDL, the Dimensions Development Library is a collection of resources. It
consists of extensive technical documentation as well as a wide variety of example code.

3
Chapter 1 Introduction to Survey Programming Survey Programming Fundamentals

You can access the DDL through the Help Contents menu choice in mrStudio, or through:

Start Programs SPSS Dimensions Dimensions Development Library Documentation 4.5

Navigating the DDL


There are many different ways to navigate around the DDL.

Tab Description
Contents All the DDL topics arranged in a table of contents. You can use this view like looking
through a book. It is also helpful for identifying topics related to a page you are
currently reading.
Index The index is an alphabetical list of keyword contained in the DDL. Use this view
when you know the keyword and want to quickly find topics related to it.
Search A fulltext search of the DDL. You can search on a single word, combination of
words and phrases.
Favorites Create a list of topics you have found valuable.

All the Dimensions product documentation is contained in the DDL, so finding specific topics
is a skill in itself and will take time to develop.

For this course, a good place to start is in the Contents tab:

mrStudio Interview Scripting Getting Started

Examples
When you installed the DDL you also installed many examples files. The default path for these
examples is:

C:\Program Files\SPSS Dimensions\DDL\

Specifically for survey programming you should be aware of:

C:\Program Files\SPSS Dimensions\DDL\Scripts\Interview

These example projects will prove very valuable to give you new ideas for programming.

4
Survey Programming Fundamentals Chapter 1 Introduction to Survey Programming

DDL Links
Throughout these materials you will see links pointing you to the DDL for additional information on a
topic. These are jump links and will look like:

For more information on the Interview object model, see the DDL diagram:
IOMLib.chm::/interview_Object_Model.html

To use a link, right click on the title bar in the DDL:

Select the Jump to URL menu item.

5
Chapter 1 Introduction to Survey Programming Survey Programming Fundamentals

Enter (or copy and paste) the link into the Jump to this URL: textbox. Then click OK.

This will take you to the page requested. You can also do the reverse, and copy the current URL shown
above and share with others.

What is mrStudio?
mrStudio is a desktop program that assists programmers with creating scripts. Its core component is an
integrated development environment (IDE) that allows you to create, edit, run and debug Dimensions
scripts.

For survey programmers, one of the big strengths is the ability to run surveys directly inside mrStudio,
without the need for a server. You can create, test and debug a survey directly on your machine.

6
Survey Programming Fundamentals Chapter 1 Introduction to Survey Programming

Since you will be using mrStudio throughout this course, lets start with a brief overview of the
toolbars:

Toolbar Description
File: Used to create, open, save and print files.
Edit: Cut, copy, paste, undo and redo, find.
View: Controls which tabs are showing in
mrStudio.
Debug: Used to start, stop, pause and move
through a script.
Formatting: Indentations, commenting,
macros and options.
Workspace: Create and manage workspaces.

Interview Options: routing context options,


activation, quotas, and metadata tools.

You will get to see many features of mrStudio as you move through this training.

Whats Next?
So now you have been introduced to Dimensions Scripting, object oriented programming, the
Dimensions Development Library, and mrStudio. This manual will focus on using mrStudio to create
surveys for data collection with mrInterview. We will start with basic questions and quickly move into
advanced concepts to help you create more complex surveys.

7
Chapter 1 Introduction to Survey Programming Survey Programming Fundamentals

8
Survey Programming Fundamentals Chapter 2 Constructing Questions

Chapter 2 Constructing Questions


The core of a survey is the questions. In this chapter, we will build our knowledge of creating questions
within mrStudio.

In this chapter we
w will:
a questionss
Create basic

m
Create a metadata filee in mrStudio

View and test a surveyy within mr Studio

Metadata Items Format


Metadata items follow a distinct pattern you will see as we complete this chapter:

Name "Text" type parameters;

Item Description
Name Unique identifier for the ite m within your questionnaire. They must start with a
letter or underscore
c ( _ ) and contain only alphanumeric characterss or the
sy mbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
Type Identifies the item for its functionality
c (categorical
t questions, text only items,
etc.)
Parameters These are optional and vary by item type. An example would be the responses
to question.
Semicol on Between each item in the m etadata section o there is a semicolon.

The next sections cover many of the different types of questions.

9
Chapter 2 Constructing Questions Survey Programming Fundamentals

Information Items
To create an opening page with an introduction or have a page with graphics or opening text without
questions, you need to create an information item. The syntax is as follows:

Name "Text" info;

Item Description
Name Unique identifier for the ite m within your questionnaire. They must start with a
letter or underscore
c ( _ ) and contain only alphanumeric characterss or the
sy mbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
info Keyword to create a textonlyy item. This is the default type if it is not
o specified.
Semicolon Between each item in the metadata section there is a semicolon.

Intro "Please participate in our research about travel. Your answers will help us to better
Example understand the travel needs of consumers."

info;

The introduction will display in mrInterview like this:

10
Survey Programming Fundamentals Chapter 2 Constructing Questions

Numeric Questions
To collect numeric data from your respondents, use one of the following item types:

Name "Text" long [min..max];

Name "Text" double [min..max];

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _.
"Text" Text associated with the item (considered the label in the object model).
long Wholenumbers only (no decimals). The range is from 2,147,483,648 to
2,147,483,647.
double Decimal numbers. 64bit floating point number with at least 15 digits of
precision, in the range 1.79769313486232E308 to 4.94065645841247E324 for
negative values; 4.94065645841247E324 to 1.79769313486232E308 for
positive.
[Min..Max] Optional parameters. Controls the minimum and maximum values the
respondent can enter. Automatically issues an error message if the amount
entered is below the minimum or above the maximum.

The following example will display boxes for the respondent to fill in with a numeric response.

DaysTravelYr "On average how many days per year do you travel for business or leisure?"
Example
long [0 .. 365];

AmtSpentAccom "What price did you pay for your last overnight accommodations?"

double [0 .. 3999.99];

11
Chapter 2 Constructing Questions Survey Programming Fundamentals

The browser will display a box and the respondent can fill in amounts of their choice, as shown below:

Minimum and Maximum Parameter Options


When specifying the minimum and maximums for numeric questions, [min..max], you have many
options to collect the numeric data necessary.

Item Description
[1..] Minimum amount without specifying a maximum
[..] No minimums or maximums (will allow negative numbers)
[1..100,^50] Number after ^ symbol are excluded from the range.
[1,3,5] Commas denote single values or breaking ranges.
[1..10,50..100]

Text Questions
When you want to create a question that collects any type of text information, use a text type.

Name "Text" text [min..max];

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
text Keyword to enter any characters in the question. Allows up to 4000 characters.
[Min..Max] Optional parameters. Controls the minimum and maximum characters allowed
for the question.

Here is a simple example of an open ended question.

12
Survey Programming Fundamentals Chapter 2 Constructing Questions

BestVacation "Please tell us about your best vacation experience."


Example
text [1..];

Will display like the picture below:

If you state the maximum at 40 or less, you will see a line instead of a box. You also
have full control of the box size with styles, covered in the Controlling the Look of Your
Survey section.

13
Chapter 2 Constructing Questions Survey Programming Fundamentals

Categorical
To create a question which offers a list of options to choose from is considered a categorical type
question.

Name "Text" categorical [min..max]

{ID1 "AltText1" ,

IDn "AltTextn" };

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
categorical Keyword to create a question with categories for response choices.
[Min..Max] Optional parameters. Controls the minimum and maximum amount of
categories that can be chosen by a respondent. Default is open to any amount
of choices. Automatically issues an error message if the number of responses
chosen is below the minimum or above the maximum.
{ } Indicates the start of the categories you wish the respondent to choose from for
the question
ID1, IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.

Parameter Options - Restricting the Number of Responses to be Chosen


As stated above, the minimum and maximum options provide the number of responses that can be
answered for a specific question. There are some variations in syntax to consider.

Item Description
[1] When only one number is specified in the minimum/maximum parameter, it is
assumed that this number is both the Minimum AND maximum amount.
Example shown allows for a single response to be chosen for the question. Is
the same as typing [1..1]
[1..] Allows for multiple categories to be chosen (multiple response question). Not
stating a maximum amount allows ease of updating the question with additional
responses as needed.
[1..3] States the minimum amount of categories to be chosen is 1 and the maximum is
3. Useful for questions which ask for responses Answer up to X categories.
[..] No minimums or maximums (this is the default)

14
Survey Programming Fundamentals Chapter 2 Constructing Questions

Be aware that not stating a minimum number of answers will allow the respondent to move forward in
the survey without providing a response. Allowing no answer in this way provides no method to
determine if the respondent was presented this question. The data for the respondent will simply
contain a blank.

Later in the course we will learn how to allow for the respondent to not answer a question, yet
have the data store a value showing that the respondent was exposed to the question.

TravelItem "From the list below, which one item would you most want to bring with you
Example on a leisure trip?"

categorical [1..1]

Camera,

Map,

ComfortableFootwear "Comfortable Footwear",

FriendTravelCompanion "Friend/Travel Companion"

};

Creates a single categorical question with radio buttons:

15
Chapter 2 Constructing Questions Survey Programming Fundamentals

CountryVisited "Which of the following countries have you visited?"


Example
categorical [1..]

Antarctica,

Africa,

Asia,

Australia,

Europe,

NorthAmerica "North America" ,

SouthAmerica "South America"

};

Note in the examples above, alternate labels are not required when the text you want to
display is also a legal label name.

The checkboxes indicate that more than one response can be given as stated in the syntax as [1..].

16
Survey Programming Fundamentals Chapter 2 Constructing Questions

Date
When requesting a date from the respondent, it is easier to collect a date type versus multiple long
type fields.

Name "Text" date ["min".."max"];

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
date Keyword to enter a date and time field. Can enter dates and times or one or the
other. Takes many different date formats (See below).
["Min".."Max"] Optional parameters. Controls the minimum and maximum date range allowed
for the question. Note the addition of the double quotes around the min/max.

Key points regarding dates:

The format for the date is very flexible. Some (not all) of the formats taken are:
o DDMonthNameYYY (7 April 2007)
o DDShortMonthNameYYY (7 Apr 2007)
o YYYY/MM/DD (2007/04/07)
o MM/DD/YY (04/07/07)
If you leave off certain portions of the date/time field, it will make assumptions. An example
would be if you were collecting only month and year and enter April 2007, mrInterview will
record the date as April 1, 2007. If a time is not chosen, it assumes the current time.
When you run the interview you may enter times in 12hour or 24hour format; for example,
2:30pm or 14:30. If you do not specify AM or PM, it will assume a 24hour clock.
Metadata language controls the format of the date taken. An example would be trying to
enter a UK English date of dd/mm/yy when the metatdata languages do not contain English
UK, only English US. In this case, the date would be transformed to the English US version of
mm/dd/yy.

If you want more control over the date field, create a custom control, such as the example
calendar.htm in the DDL: DDL.chm::/interviewscripting_templates_custom_writing.htm.

7
Chapter 2 Constructing Questions Survey Programming Fundamentals

Example
LastTripDate "What was the date you left for your last trip?"

date;

TimeforTravel "What time of day do you prefer to travel in the morning?"

date ["1:00am" .. "11:59am"];

The result of the LastTrip date question would look like this:

18
Survey Programming Fundamentals Chapter 2 Constructing Questions

Boolean
Boolean type questions record a true or false value. In web surveys, this type is an easy way to provide
a single checkbox response.

Name "Text" boolean;

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
boolean Keyword to create a true/false question. Creates a checkbox on web surveys.
Checking the box is a True response and leaving it empty is false.

You can add categories to a Boolean question to simulate a categorical question. Be sure
if you use this option that you will only have 2 responses, never any more.

Here is an example of a Boolean question and what it will look like in the browser:

ReceiveTravelInfo "Check here if you wish to receive an email regarding travel safety."
Example
boolean;

9
Chapter 2 Constructing Questions Survey Programming Fundamentals

20
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script

Chapter 3 Creating an mrStudio Interview Script


Now that you know how to create some basic question types, lets start using mrStudio to create and
test our script. We will use mrStudio to create the Dimension Scripting for our surveys.

This
T chapter will cover:
How to reeate an mrStudio metadata file
f

o mrStudio and the toolbars and


Overview of
menus

How to esst your survey with mrStudio


o

Opening mrStudio
You will find mrStudio at:

Start Programs SPSS Dimensions mrStudio.

21
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals

Under File New File you will see the different types of files you can create in mrStudio.

For this course we will be creating a Metadata File (.mdd). Under file name fill in a file name for your
project and choose Open. Now you are ready to start typing the code discussed in Chapter 2 into the
metadata section.

If you need help at first, Control M displays the list of question types that you can choose
one and have the structure of the question to start with. The macros can be a nice place
to start when you dont want to go back to the DDL or manual for syntax questions.

22
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script

Overview of Toolbars/Shortcuts
mrStudio has many tools to help you with the creation of your script. Lets review the different
toolbars and parts of the mrStudio screen.

Formatting Toolbars
The formatting toolbars provide basic but needed editing skills in mrStudio.

File Toolbar: Used to create, open save and print files.

Edit Toolbar: Cut, copy, paste, undo, redo and find.

Formatting Toolbar: Indentations, commenting, macros and options.

Indenting left or right icons. Indenting will become a very important aspect of your script
writing in the routing section. It will help make your code easy to follow.
Comment and Uncomment Selection icons. The comments in Dimensions Scripting are
indicated by a single quote mark and will turn the commented text green. By highlighting large
blocks of text, you can comment and uncomment the sections easily with the toolbar icons
above.
The macros icon allows you to access the predefined syntax for mrStudio. You also have the
ability to add your own macros as well.

Note that you can copy macro definitions from one machine to another by copying the file
MacroDefinitions.xml from the default mrStudio directory.

3
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals

View Toolbar
This toolbar controls which tabs are showing in mrStudio. Depending on what you are trying to
accomplish, you will want to show different aspects of mrStudio.

For now, lets start with two helpful aspects, Metadata Explorer and the locals pane.

Metadata Explorer
As you create your metadata, you can open the Metadata viewer to see a treeview version of your
script:

The icons shown in this viewer are used throughout all Dimensions products to represent the question
types.

24
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script

Locals
As you run a survey, the locals allows you to see your responses to the questions as shown below.

In addition, the locals pane will provide extremely helpful in this course as you start to understand the
questions as objects, as you can see the different properties of the questions.

Interview Options Toolbar


The Interview Options toolbar gives you access to mrStudio tasks.

From left to right the options are:

Adding routing contexts


Removing routing contexts
Metadata tool1
Metadata tool2
HTML tidy (tries to improve your HTML code in your templates to be perfectly formed)
Creating quotas (opens the Quota Tool Application)
Activation of the survey to mrInterview

Tips for Creating Metadata


We will discuss the mrStudio environment and the tools provided to help you create your scripts
throughout the manual. Here are a few tips to get you started:

All keywords are color coded in blue. All text within double quotes is also color coded.
When troubleshooting syntax errors, look for the appropriate color coding to help you find the
problems.
Save frequently, as your metadata will be checked for syntax errors when you save.
Error messages will state the line numbers associated with it. Notice the line numbers on the
left side of your code in mrStudio to help you with this.

25
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals

After saving and closing the document, mrStudio reformats your metadata into a standardized
format. The term used for this is rehydration. Be aware of this so you dont spend additional
time on proper formatting in the metadata section.

Viewing and Testing the Survey in mrStudio


When you have saved so that you know all errors are gone, you are ready to view the results of your
script. Click the start button on the toolbar:

On the browser tab in mrStudio (if you cannot see the browser tab, from the menu choose View
Browser ) you will be able to see the interview as it will appear when it is activated in mrInterview.

26
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script

Later in this course we will add formatting and templates to enhance the look of the
interview; these will also be viewable in the mrStudio browser window.

You can choose to answer the questions yourself, or you can choose F5 to let mrStudio automatically
answer the questions on the screen for you. (This will prove helpful later when testing surveys with
large grid questions).

The interview will complete, but if you wish to interrupt the script, click on the Stop button in the
browser window, or the Stop (square icon) in the toolbar.

As you can see, there are many features in mrStudio to help you create your interview scripts. Some
features you will use immediately, such as the local testing of surveys and the autoanswering
questions with F5. Others, such as creating macros and viewing the locals pane information will come
later in your learning.

27
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals

Exercise
Open mrStudio and create a metadata file called GroceryBill.mdd. Complete the following questions
in this document, then test the survey within mrStudio.

GroceryIntro As you agreed to previously, please have your last grocery bill available for reference for
this next section of the survey.

GroceryDate Looking at your last grocery bill, what date did you go to the store?

StoreName What was the name of the store in which you shopped?

Walmart
Safeway
Kroger
Albertsons
Ahold USA
Delhaize
Publix
WinnDixie

ItemTypes Which of the following categories of groceries did you purchase on this shopping trip?

Cheese/Olive Bar
Salad Bar
Deli Items
Meat/Seafood
Produce
Canned Goods
Pasta/Grains

Generic On this particular shopping trip, did you purchase any generic brand items?

Yes
No

28
Survey Programming Fundamentals Chapter 3 Creating an mrStudio Interview Script

ItemsBought How many items did you buy?

GroceryCost Exactly how much did you spend?

PurposeTrip Briefly describe the reason for your trip to the grocery store on that particular day.

AgreeContact Please check the box below if you agree to allow us to contact you later if we have
additional questions regarding your trip to the grocery store.

29
Chapter 3 Creating an mrStudio Interview Script Survey Programming Fundamentals

30
Survey Programming Fundamentals Chapter 4 Special Responses and Options

Chapter 4 Special Responses and Options


In Chapter 2 we covered basic question syntax. This chapter will expand on the concepts of that
chapter and add additional options to enhance those question types.

In this
t chapter we will cover:
Special keyywords to provide additional
functionality

Collecting specific text responses


e when
respondent chooses other

Creating su
ubheadings o improve the
appearance of categor ical questions

Single Response Choices in Multiple Selection Questions


With multiple selection categorical questions, you may want to have certain responses that cannot be
chosen in combination with any other response. In order for that logic to happen, you must indicate
that the response should be a singleselect choice using the keyword, exclusive.

Name "Text " categorical [min..max]

{ID1 "AltText1",

IDn "AltTextn" exclusive };

31
Chapter 4 Special Responses and Options Survey Programming Fundamentals

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
categorical Keyword to create a question with categories for response choices. Question
type must be categorical to use the exclusive keyword.
[min..max] Optional parameters. Controls the minimum and maximum amount of
categories that can be chosen by a respondent. Default is open to any amount
of choices. Automatically issues an error message if the number of responses
chosen is below the minimum or above the maximum.
{ } Indicates the start of the categories you wish the respondent to choose from
ID1, IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.
exclusive Makes a specific response the only choice that can be chosen in a multiple
selection question. Keyword is placed after the category name and alternate
text (if present).

AirlinesFlown "In the past year, which of the following airlines have you used for travel?"
Example
categorical [1..]

American,

Delta,

United,

OtherAirline "Other airline",

NeverFlown "Never flown before" exclusive

};

32
Survey Programming Fundamentals Chapter 4 Special Responses and Options

If the respondent tries to choose the response Never flown before and any other response, the
following error will appear:

Exclusive responses show up in bold by default. This can be overwritten by templates or


styles, which will be discussed in Chapter 13 .

3
Chapter 4 Special Responses and Options Survey Programming Fundamentals

Special Responses with Categorical Questions


There are special keywords which represent some common responses to interviews, No Answer, Dont
Know, and Refused to Answer.

Name "Text" categorical

{ID1 "AltText1",

ID2 "AltText2" ,

IDn "AltTextn" Keyword};

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
categorical Keyword to create a question with categories for response choices.
{ } Indicates the start of the special response categories you wish the respondent to
choose from for the question
ID1, ID2, IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltText2, will apply when the name of the question is not the same as the text you wish to
AltTextn show the respondent.
Keyword Represents one of the keywords NA (No Answer), DK (Dont Know), or REF
(Refused)

Benefits for using these keywords:

The response is automatically set to be exclusive and fixed in the position in which it was typed
when the category order is changed.
When using the CATI (Computer Aided Telephone Interviewing) option, these keywords have
shortcut keys for the ease of use for the interviewers
These responses can be identified in a systematic way, which makes it easier to reference
these question types when creating subroutines or functions.

34
Survey Programming Fundamentals Chapter 4 Special Responses and Options

Example
HotelChainStayed "Choose the hotel chains you have stayed at this past year."

categorical [1..]

InterContinental,

Cendant,

Marriott,

Accor,

Choice,

Hilton,

DontKnow "Dont Remember" DK,

Refused "Prefer not to Answer" REF

};

You can use the keywords as the names for the responses; however after rehydration the names will
show as a dash ().

35
Chapter 4 Special Responses and Options Survey Programming Fundamentals

Categorical Responses with Non-Categorical Questions


You can add categorical responses to question types that are numeric, text, or date. The special
keyword options of NA, DK and REF are typically used in this scenario, as this can prove valuable to
provide respondents with a way to indicate they dont know or prefer not to answer the question.

Name "Text" qtype [min..max]

codes (

{ID1 "AltText1" Keyword,

IDn "AltTextn" Keyword}

);

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
Qtype Represents the noncategorical question types of long, double, text or date.
[Min..Max] Optional parameters. Controls the minimum and maximum values that can be
chosen by a respondent.
codes Keyword to indicate you are adding special response categories to a non
categorical question.
{ } Indicates the start of the special response categories you wish the respondent to
choose from for the question
ID1, IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.
Keyword Represents one of the keywords NA (No Answer), DK (Dont Know), or REF
(Refused). This keyword is optional.

36
Survey Programming Fundamentals Chapter 4 Special Responses and Options

AmtSpentYr "What price did you pay for your last airline flight?"
Example
double [0 .. 3999.99]

codes (

dontknow "Dont remember" DK,

Refused "Prefer not to answer" REF

);

This code would create checkboxes below the numeric response box as shown below:

37
Chapter 4 Special Responses and Options Survey Programming Fundamentals

Collecting Other Text Responses in Categorical Questions


The other keyword allows the respondent to enter an answer that is not on the category list.

Name "Text" categorical

{ID1 "AltText1",

IDn "AltTextn" other};

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
categorical Keyword to create a question with categories for response choices.
{ } Indicates the start of the categories you wish the respondent to choose from for
the question
ID1, ID2 Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltText2 will apply when the name of the question is not the same as the text you wish to
show the respondent.
other Keyword to create a text box on the response to collect additional information.

HotelChainStayed "Choose the hotel chains you have stayed at this past year."
Example
categorical [1..]

{ InterContinental ,

Cendant,

Marriott,

Accor,

Choice,

Hilton,

OtherHotel "Other Hotel Chain" other,

DontKnow "Dont Remember" DK,

Refused "Prefer not to Answer" REF };

38
Survey Programming Fundamentals Chapter 4 Special Responses and Options

This will create a text box to collect the specific name of any hotel chains not listed.

You can have multiple other specify responses per question.

Subheading
You can create textonly items to describe a group of responses by creating subheadings.

Name "Text" categorical


{
Subhead1 "SubText1"
{
ID1 "AltText1",
ID2 "AltText2"
},
Subheadn "SubTextn"
{
ID3 "AltText3",
IDn "AltTextn"
}
};

39
Chapter 4 Special Responses and Options Survey Programming Fundamentals

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
categorical Keyword to create a question with categories for response choices.
{ } Indicates the start of the subheadings and categories
Subhead1, Name for Subheading item
Subheadn
SubheadText1, Represents alternate text for the Subheadings.
SubheadTextn
ID1, ID2,IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltText2, will apply when the name of the question is not the same as the text you wish to
AltTextn show the respondent.

TravelHelp "Have you used any of the following to help you with your travel
Example arrangements?"
categorical [1..]
{
TravelBooks "Travel Books"
{
LonelyPlanetBook "Lonely Planet",
Fodor "Fodor's",
Frommer "Frommer's"
},
Websites "Websites"
{
Expedia "Expedia" ,
Orbitz "Orbitz" ,
Govt "Government Websites"
}
};

40
Survey Programming Fundamentals Chapter 4 Special Responses and Options

The previous code will create the following question in the browser:

41
Chapter 4 Special Responses and Options Survey Programming Fundamentals

Exercise
Update the first exercise (GroceryBill.mdd ) with the following additions that are highlighted below:

GroceryIntro As you agreed to previously, please have your last grocery bill available for reference for
this next section of the survey.

GroceryDate Looking at your last grocery bill, what date did you go to the store?

StoreName What was the name of the store in which you shopped?

Walmart
Safeway
Kroger
Albertsons
Ahold USA
Delhaize
Publix
WinnDixie
Other (Specify)

ItemTypes Which of the following categories of groceries did you purchase on this shopping trip?

Prepared Foods
Cheese/Olive Bar
Salad Bar
Deli Items
NonPrepared Foods
Meat/Seafood
Produce
Canned Goods
Pasta/Grains
None of These

Generic On this particular shopping trip, did you purchase any generic brand items?

Yes
No
Dont Remember

42
Survey Programming Fundamentals Chapter 4 Special Responses and Options

ItemsBought How many items did you buy?

GroceryCost Exactly how much did you spend?

Prefer not to Answer

PurposeTrip Briefly describe the reason for your trip to the grocery store on that particular day.

AgreeContact Please check the box below if you agree to allow us to contact you later if we have
additional questions regarding your trip to the grocery store.

43
Chapter 4 Special Responses and Options Survey Programming Fundamentals

44
Survey Programming Fundamentals Chapter 5 Basic Routing Logic

Chapter 5 Basic Routing Logic


So far, we have only created the metadata portion of our survey. This chapter focuses on how to
control the flow of the survey questions.

h
This chapter o
covers:
n
Understanding, e
adding, removing routingg
context

u questions
Changing the order of your

Adding skip logic/routing to your survey

n
Understanding n Functions and use
Dimensions
with logic statements

Here are some of the many things the routing section allows you to do:

Control what questions are asked


The order of questions
Add conditional statements about questions to control if/how they are asked
Allows a single metadata file with different routings for ease of changes to multimode surveys

To access the routing section, click on the Web tab in your .mdd file as shown below:

45
Chapter 5 Basic Routing Logic Survey Programming Fundamentals

You can add additional routings to your questionnaire. This would be necessary for surveys fielded
with multiple collection methods, such as web, paper scanning, and telephone interviewing. You
would also need to add routing if you originally created your metadata using either mrInterivews Build
activity or the accessory Word Capture, as they create a paper routing that is read only.

To add an additional routing:

Tools
Add Routing Context

46
Survey Programming Fundamentals Chapter 5 Basic Routing Logic

You will be prompted for a name for the routing.

To remove a routing context, click on the tab of the context you wish to remove and choose

Tools Remove Routing Context as seen in the diagram above.

When setting up your routing, here are a few things to remember:

There is no rehydration of the routing section, so format counts. Use Tabs to indent and make
your code easy to read.
Saving does not check the routing syntax; only when you start the survey will you see the
runtime problems.

Asking Questions
All we have done so far is create metadata and run the survey to review the questions. mrStudio will
run all the questions in the metadata if there is nothing in the routing section. This is not a practical
option, as almost all scripts have some routing. Additionally, mrInterview will not run a script without
having a proper routing section. The main items in your routing are statements to ask the questions.

Name.Ask()

Item Description
Name Metadata item name
.Ask() Displays and asks the question

We will need to create .Ask() statements for each question in our survey. To quickly ask all the
questions in your metadata,

View the Metadata Explorer


Click on the Fields folder
Rightclick to choose Copy as Ask
Paste in the routing section

47
Chapter 5 Basic Routing Logic Survey Programming Fundamentals

By expanding the Fields folder, you can pick and choose specific questions to copy as .Ask
statements.

48
Survey Programming Fundamentals Chapter 5 Basic Routing Logic

Read Only Items


There is a way to show the question and current response for a question without the ability to change
the response:

Name.Show()

Item Description
Name Metadata item name
.Show() Displays the question and its current response in readonly format

When .Show() is used with a question, the choices are grayed out and you are only able to see the
current response for the question as shown below.

.Show() can also be used with info items; there is no difference using a .Show() or .Ask with
an info item.

49
Chapter 5 Basic Routing Logic Survey Programming Fundamentals

Conditional Statements
Now that we have asked all the questions, lets look into ways to determine if a respondent should be
asked certain questions. This is usually called routing or skip patterns. There are two conditional items
we will review to help us create the routing for our surveys.

If Then Else
Select Case

If Then Else
If then else is a conditional statement which will compare two or more statements and test the
results. If the results are true, the then actions are taken; if not, the else actions are taken. The
syntax in Dimensions scripting is:

If condition Then

Actions

End if

For simple conditions it can all be stated on a single line:

If condition Then Action

Additionally, you could add the options for Else if and/or Else:

If condition Then

Actions

ElseIf condition Then

Actions

Else

Actions

End If

50
Survey Programming Fundamentals Chapter 5 Basic Routing Logic

Now lets look at some examples of these conditional statements. To do this, we will need to
understand the syntax for some of the Actions you could use in the conditional statements. One
action to use in the routing section is testing the response to a previous question. We will look at
many ways to do this throughout the manual. For this conditional section, here is some basic
information.

Name.Response.Value = condition or response

Item Description
Name Represents the metadata item name
.Response.Value Property to reference the named questions current response value
Condition or Any condition to represent a possible response for the named question, or
response specify an actual response

In the next example, we have the following questions as shown in the metadata:

Metadata (enUS, Question, Label)


Example
TravelItem "From the list below, which one item would you most want to bring with you
on a leisure trip?"
categorical [1..1]
{
Camera,
Map,
ComfortableFootwear "Comfortable Footwear" ,
FriendTravelCompanion "Friend/Travel Companion"
};

'If Friend/Travel Companion is chosen in TravelItem, ask FriendRelate


FriendRelate "What is the relationship of that person to you?"
text;

'If Camera is chosen in TravelItem, ask TravelItemCost


TravelItemCost "How much would you expect to pay for the camera?"
Double [0..5000];

End Metadata

51
Chapter 5 Basic Routing Logic Survey Programming Fundamentals

The logic for the questions is, if the answer to the TravelItem question is Friend/Travel Companion,
then ask the FriendRelate question. The logic is achieved in the following routing section with the use
of an If Then statement:

Routing(Web)
Example
TravelItem.Ask()

If TravelItem.Response.Value = {FriendTravelCompanion} Then

FriendRelate.Ask()

End If

If TravelItem.Response.Value = {Camera} Then

TravelItemCost.Ask()

End If

End Routing

If the question is categorical, you will need to refer to the Name of the response (not the label that is
shown to the respondent) and enclose this in curly brackets as shown in the above example.

Select Case
Select Case statements work similar to an If Then statement. Select Case statements allow you to
create conditional actions based on a question type that can only have a single value (single
categorical, numeric, Boolean).

Select Case Name.Response.Value

Case Response1

Actions1

Case ResponseN

ActionsN

...

[Case Else

ActionsN]

End Select

52
Survey Programming Fundamentals Chapter 5 Basic Routing Logic

Item Description
Select Case Marks the Start and end of the select case statement
End Select

Name.Response.Value Question and its response that you are testing


Case Response1, Case Represents responses to a question or expressions that group responses to
Response2 the question.

Actions1, Actions2 Represent one or more statements to be executed if the question's response
matches the response for the current Case statement.

Case Else Represents one or more statements to be executed for respondents who fail
ActionsN all the previous Case tests

The case statement can be useful when you have many responses to test since you only specify the
question name once. The following shows the previous example for an if then statement, now with
the select case syntax.

Metadata (enUS, Question, Label)


Example TravelItem "From the list below, which one item would you most want to bring with you
on a leisure trip?"
categorical [1..1]
{
Camera,
Map,
Comfortablefootwear "Comfortable Footwear",
FriendTravelCompanion "Friend/Travel Companion"
};

'If Friend/Travel Companion is chosen in TravelItem, ask FriendRelate


FriendRelate "What is the relationship of that person to you?"
text;

'If Camera is chosen in TravelItem, ask TravelItemCost


TravelItemCost "How much would you expect to pay for that item? "
Double [0..5000];

End Metadata

53
Chapter 5 Basic Routing Logic Survey Programming Fundamentals

Routing(Web)

TravelItem.Ask()

Select Case TravelItem.Response.Value

Case {FriendTravelCompanion}

FriendRelate.Ask()

Case {Camera}

TravelItemCost.Ask()

End Select

End Routing

To have mrStudio create the case statement for you, view the metadata explorer, then
choose the question in which you will be basing the select statement. Choose the questions
categories folder and rightclick to choose Copy as Select statement. You can then paste a
shell of the select statement with the questions categories as a starting point.

54
Survey Programming Fundamentals Chapter 5 Basic Routing Logic

Goto
In the examples above, we have been creating our routing based on good programming practices in
which you nest questions within conditional statements. The methods shown thus far can help make
your code easy to follow and debug. Sometimes, however, it may be helpful to skip around statements
in the routing section. The Goto keyword can allow you to do this when combined with a conditional
statement.

Goto lineLabel

lineLabel:

Item Description
Goto Keyword indicating the script should skip to the line label indicated
Linelabel Represents a line label of your choice. The naming convention for line labels follows
the pattern of all names in the metadata. These are not seen by the respondent.
: Needed to indicate this is the line label item.

As an example, suppose we asked if the respondent travels for business. Then there are a series of
questions about business travel, and a series of questions about travel for pleasure. We can use a goto
and line labels to achieve the routing necessary.

Routing(Web)
Example
TravelforBusiness.Ask()

If TravelforBusiness.Response.Value = {No} then goto PleasureSection

DaysPerYrBusinessTravel.Ask()

InternationalBusiness.Ask()

PleasureSection:

TravelforPleasure.Ask()

End Routing

55
Chapter 5 Basic Routing Logic Survey Programming Fundamentals

Logical Expressions
In the previous section, we looked at some very simple logical expressions, such as
QuestionName.Response.Value = response. We will cover additional options for creating expressions.

Numeric Questions
For testing numeric questions (long or double), use the math operators listed in the table below.

Item Description
= Equal to
<> Unequal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to

Metadata(enUS, Question, Label)


Example
AmtSpentAccom "What price did you pay for your last overnight accommodations?"
double [0 .. 3999.99];

'If AmtSpentAccom is $150 or greater, ask TypeAccom question


TypeAccom "At what type of accommodations did you stay?" categorical [1..1]
{ Hotel,
Motel,
BedBreakfast "Bed and Breakfast",
Hostels,
Resorts,
OtherAccom "Other Accommodations" other};
End Metadata

Routing(Web)

AmtSpentAccom.Ask()

If AmtSpentAccom.Response.Value >= 150 Then

TypeAccom.Ask()

End If

End Routing

56
Survey Programming Fundamentals Chapter 5 Basic Routing Logic

Boolean Questions
Boolean questions have values of True or False, so they can easily be checked with a simple statement:

Name.Response.Value = condition

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
Response.Value Current response to the question identified by name above
condition True (checkbox was checked) or False(checkbox was left empty)

Text Questions
With text questions you can test whether the response matches a pattern. The expression format is:

Name Like "pattern"

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
like Keyword to indicate you are trying to match a test pattern
pattern Represents the text with which the response is to be compared. An underscore
(_)in the text matches any single character, and a percent sign (%) matches any
number of characters, including zero

The following code checks text questions to see if it contains the word, Luftansa. If it does, then it
follows up with another question.

Metadata(enUS, Question, Label)


Example BestAirTravel "Explain your best experience with air travel. Please mention your
destinations, airports and airline."
text;

TimesWithLuftansa "And how many times over the past year have you flown Luftansa?"
long [0..365];
End Metadata

Routing(Web)
BestAirTravel.Ask()
If BestAirTravel.Response.Value Like "%Luftansa%" Then
TimesWithLuftansa.Ask()
End If
End Routing

57
Chapter 5 Basic Routing Logic Survey Programming Fundamentals

Categorical Questions
For singleresponse categorical questions, you may find simple expressions to suffice, such as
Name.Response.Value={Yes} . However, things will get complex, and youll need the Dimensions
functions to make more advanced logic statements.

Dimensions functions for categorical responses were created specifically for Dimensions scripting. We
will cover 3 basic functions for routing purposes, ContainsAll , ContainsAny and AnswerCount.

For a full list of functions, see DDL.chm::/funclib_overview.htm

ContainsAll
Identifies whether a category list contains all of the categories in a given list. And condition for an
individual question.

Name.ContainsAll({ID1, IDn},parameter)

Item Description
Name Represents the question name
ContainsAll Dimensions function testing whether a list of categories are all contained in the
named question. (And condition)
ID1, IDn Unique identifying name for the response.
parameter Represents an optional parameter. If the parameter is set to true, then the
function will be true only if the response contains all of the categories and no
others (exclusive). If the parameter is set to false (default), then the function
will be true if the response contains all of the responses listed, regardless of
other responses chosen from the question.

Example
CountryVisited.ContainsAll({NorthAmerica,SouthAmerica})

This statement would be true if a respondent chose both North America and South America in the
CountryVisited question, regardless of other responses chosen from the question.

58
Survey Programming Fundamentals Chapter 5 Basic Routing Logic

Example
CountryVisited.ContainsAll({NorthAmerica,SouthAmerica}, true)

This statement would be true if a respondent chose both North America and South America AND did
not choose any other responses in CountryVisited.

ContainsAny
Identifies whether a category list contains one or more categories in a given list. Or condition for an
individual question.

Name.ContainsAny({ID1, IDn},true)

Item Description
Name Represents the question name
ContainsAny Dimensions function testing whether any of the list of categories are contained
in the named question. (Or condition)
ID1, IDn Unique identifying name for the response.
True Represents an optional parameter. If the parameter is set to true, then the
function will be true only if the response contains any of the categories and no
others (exclusive). If the parameter is set to false (default), then the function
will be true if the response contains any of the responses listed, regardless of
other responses chosen from the question.

Example
CountryVisited.ContainsAny({NorthAmerica,SouthAmerica})

The above statement would be true for respondents choosing North America, South America, or both.

59
Chapter 5 Basic Routing Logic Survey Programming Fundamentals

AnswerCount
The function AnswerCount counts the number of mentions chosen for a specific categorical question.

Name.AnswerCount()

Item Description
Name Represents the question name
AnswerCount Dimensions function returning how many responses have been chosen in the
named categorical question.

It returns a numeric value, so you would use numeric operators to test the result of the function.

If CountryVisited.AnswerCount() > 3 then


Example
WhySoMany.Ask()

End if

The example above states that if the number of answers mentioned in the categorical question,
CountryVisited, is greater than 3, then ask the followup question.

Logical Operators
You can also use the logical operators of Not, And, Or, and Xor to create more complex routing
conditions.

NOT

It is used to negate expressions. Its recommended to enclose the item to negate in parenthesis as
shown below.

Example
Not (TravelHelp.ContainsAny({Expedia}))

The above would be true if the respondent did not answer Expedia for the TravelHelp question.

60
Survey Programming Fundamentals Chapter 5 Basic Routing Logic

AND

Returns true when both parts of the expression are true.

Example
DaysTravelYr > 5 And TravelHelp.ContainsAny({Expedia})

The above will be true if the respondent traveled more than 5 days and used Expedia.

OR

Returns true when either or both parts of the expression are true.

Example
DaysTravelYr > 5 Or TravelHelp.ContainsAny({Expedia})

The above will be true if the respondent traveled more than 5 days or used Expedia.

XOR

Returns true when one part (but not both parts) of the expression are true.

Example
DaysTravelYr > 5 Xor TravelHelp.ContainsAny({Expedia})

The above will be true if the respondent traveled more than 5 days and did not use Expedia, or if the
respondent traveled 5 days or less and did use Expedia.

61
Chapter 5 Basic Routing Logic Survey Programming Fundamentals

Some find xor confusing, but it can save some syntax. The following statement is the equivalent of the
previous xor statement:

Example
(DaysTravelYr > 5 And (Not (TravelHelp.ContainsAny({Expedia}))) ) Or (DaysTravelYr <= 5 And
TravelHelp.ContainsAny({Expedia}))

As you can see when creating complex conditions with combinations of and, or, and not statements,
put parenthesis around things you want evaluated together.

If you need to refer to the special responses DK, REF, NA in a noncategorical question, you
need to refer to it as QuestionName.Response.Coded = {ID}, where ID is the ID of the special
response.

Tips for Routing Section Syntax


There are numerous ways to write the syntax within the routing section. Here are some hints to help
you to take full use of the ScriptAssist within mrStudio.

CtrlQ to see the full list of questions in your metadata


CtrlR will display the responses for a Question listed
Rightclick on a question name in the routing section and choose Goto Definition which will
take you to that question in the metadata section
Choose the period (.) to see valid choices for your statement

This may not always work, as there are multiple ways to write the statements. You will
notice the ScriptAssist may not always provide the proper choices. A good example would
be Dimensions functions, such as ContainsAny. The method used in this chapter,
Name.ContainsAny({Response}), does not provide script assistance. The fully documented
way, ContainsAny(Name.Response.Value,{Response}), will show parameters needed.

62
Survey Programming Fundamentals Chapter 5 Basic Routing Logic

Adding Error Handling


Another important aspect of the routing section is the ability to send error messages to both the
respondent and the mrInterview logging when there is a problem with the script. Error handling allows
the system to gracefully handle errors that occur, as opposed to a generic error messages that will not
provide appropriate information to fix the problem and possibly confuse respondents. The code can
be standardized and placed in every script. Below is a simple example to use as a starting point.

Routing(Web)
Example ' Error handler
If Not IOM.Info.IsDebug Then On Error Goto DefaultErrHandler
Goto StartOfScript

DefaultErrHandler:
Dim errmsg, numerror
errmsg = "Script error at line " + CText(Err.LineNumber) + ", " + Err.Description
IOM.Log(errmsg, LogLevels.LOGLEVEL_ERROR)
If IOM.Info.IsTest Then
IOM.Banners.AddNew("ScriptErrMsg" + CText(numerror), errmsg)
numerror = numerror + 1
End If
Resume Next

StartOfScript:
' End error handler

End Routing

Breaking down the example above:

The IOM.Info.IsDebug prevents the error handler being enabled if the script is being run in
mrStudio.
On Error Goto DefaultHandler sends all erros to the error handler. When an error occurs, the
error handler writes the error message and the line number to the log file, IVW*.tmp.
IOM.Info.IsTest displays the message on the top of the current page.
The Resume Next line allows the interview to continue after an error.

63
Chapter 5 Basic Routing Logic Survey Programming Fundamentals

Exercise
Use the metadata file, Routing.mdd as your starting point. Complete the routing section and
routing/skip patterns shown below.

CookAtHome Do you ever cook food at home?

Yes
No (Skip to ItemsOwned)

CookMealWk How many meals per week do you cook at home?

PeopleCookFor Do you normally cook for any of the following at your home? Check all that apply.

Spouse/Other Adults in the household


Children in the household
NonHousehold Member Adults
NonHousehold Member Children
Only for Myself

(If CookMealWk is greater than or equal to 5 and PeopleCookFor question has adults, ask Wine)

Wine Do you ever serve wine with the meals you serve to others?

Yes
No

(If PeopleCookFor is both Children in HH and NonHousehold Member Children, ask AllergyKids)

AllergyKids Do any of the children you make meals for have food allergies?

Yes
No

64
Survey Programming Fundamentals Chapter 5 Basic Routing Logic

PrepTime On average, how much time do you devote to preparing a single meal?

30 minutes or less
3190 minutes
Over 90 minutes
Dont know

(If PrepTime is 30 minutes or less, ask MealStrategy)

MealStrategy Please list some of your strategies for preparing meals so quickly.

(If PrepTime is 3190 minutes, ask AmtPrep)

AmtPrep Do you feel that your preparation time for meals is

Too short
Too long
Just right
Dont Know

(If PrepTime is Over 90 minutes, ask PrepDescrip)

PrepDescrip Do you take over 90 minutes to prepare meals mainly because of

The amount of entrees created


The complexity of the dishes
The number of interruptions during the process
Other (specify)
Dont Know

65
Chapter 5 Basic Routing Logic Survey Programming Fundamentals

ItemsOwned Which of the following kitchenware items do you own?

Bread Maker
Food Processor
Stand Mixer
Wok
Fondue Pot
None of These

(If respondent owns 3 or more kitchen items in ItemsOwned, ask UseItems)

UseItems Do you use some/all the items mentioned previously

Daily
Weekly
Monthly
Yearly
Never

(If CookAtHome is No, and UseItems not equal to Never, ask WhatUseFor)

WhatUseFor Please explain what you use your kitchen items for if you do not cook at home.

66
Survey Programming Fundamentals Chapter 6 Shared Lists

Chapter 6 Shared Lists


When creating a survey, you may repeat the same responses question after question. Using a shared
list will allow you to create the response list once and use it many times. In addition, if changes need
to be made to your response list, you have one central location to make the changes to update many
questions at once.

This chapter covers:


o
Creating a reuseable ressponse list

s
Including subheadings inn a list

Dealingwiith identical esponse text in two


or more lir sts

Creating a shared list is very similar to adding categories to a categorical question.

ListName "Text" define

{ID1 "AltText1",

IDn "AltTextn" } ;

Item Description
ListNamee Unique identifier for the shared list in the metadata. They must start with a
c
letter or underscore ( _ ) and contain only alphanumeric characterss or the
sy mbols @, $, #, or _
"Text" Optional text when list is used as a sublist.
Define Keyword to create a shared list
{ } Indicates the start of the categories for the define list
ID1, IDn Unique identifying name for the t response. This needs to be unique per
qu estion, not metadata
e s
file. Rules for the response names are the same as the
name
m of the qu estion.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.

67
Chapter 6 Shared Lists Survey Programming Fundamentals

To make use of the responses in a question:

Name "Text" categorical [Min..Max]

{use listname} ;

Item Description
Name Name of the Question
"Text" Text associated with the question (considered the label in the object model).
Categorical Keyword to create a question with categories for response choices.
[Min..Max] Optional parameters. Controls the minimum and maximum amount of
categories that can be chosen by a respondent. Default is open to any amount
of choices. Automatically issues an error message if the number of responses
chosen is below the minimum or above the maximum.
Use Keyword to include the categories from a define list in the question.
Listname Represents the name of the define list to use for the categories of the question.

ResortTypes define
Example {
Historical,
AmusementPark "Amusement Park",
Beach,
Adventure
};

ResortStayed "Of the following, which Resort types have you stayed at in the last year?"
Categorical [1..]
{ use ResortTypes };

Some things to keep in mind about shared lists:

You can use more than one list within the same question
You can create shared lists that are made up of other shared lists
You can use a shared list with a question in addition to adding other categories to that specific
question

68
Survey Programming Fundamentals Chapter 6 Shared Lists

Creating Subheadings with Shared Lists


You learned to create subheadings in a previous chapter. Now that you have learned shared lists,
there is another way to create subheadings using multiple shared lists.

Name "Text" categorical [min..max]

{use listname1 Sublist "Sublistname1",

Use listnameN Sublist "SublistnameN" } ;

Item Description
Name Name of the Question
"Text" Text associated with the question (considered the label in the object model).
Categorical Keyword to create a question with categories for response choices.
[Min..Max] Optional parameters. Controls the minimum and maximum amount of
categories that can be chosen by a respondent. Default is open to any amount
of choices. Automatically issues an error message if the number of responses
chosen is below the minimum or above the maximum.
Use Keyword to use the categories from a define list
listname1, Represents the name of the define lists to use for the sublist categories of the
listnameN question.
Sublist Keyword to designate the preceding define list as a subheading list
Sublistname1, Optional Text to display as the subheading Text. If not specified, will use label
SublistnameN specified in the define list.

69
Chapter 6 Shared Lists Survey Programming Fundamentals

The following example uses the concept of sublist using two define lists to create subheadings in the
categorical question.

Metadata (enUS, Question, Label)


Example ResortTypes "" define
{
Historical,
AmusementPark "Amusement Park",
Beach ,
Adventure
};
CampingTypes "" define
{
GovtPark "Government Park",
RainForest "Rain Forest",
River "River (Canoe/WhiteWater Rafting)",
Mountain "Mountain Climbing"
};

CamporResortStayed "Of the following, which Resorts have you stayed at and what types
of camping have you participated in the last year?"
Categorical [1..]
{
use ResortTypes sublist "Resorts:" , use
CampingTypes sublist "Camping:", Noneofthese
"None of these" style (Indent = 0) NA
};
End Metadata

70
Survey Programming Fundamentals Chapter 6 Shared Lists

The example shows a None of these choice. This demonstrates that you can have additional
categories in a question outside of any define lists used.

Instead of stating the subheading text after the keyword sublist, this could have been
placed between the empty in the define lists.

71
Chapter 6 Shared Lists Survey Programming Fundamentals

72
Survey Programming Fundamentals Chapter 7 Sorting Categorical Response Lists

Chapter 7 Sorting Categorical Response Lists


You may need to change the order of the categorical responses in a question. This is sometimes done
to prevent bias within a survey or simply to reorder the list alphabetically. This chapter will cover the
sorting options for mrInterview.

w show you how


This chapter will w to:

Change he order of your response lists

Use the sorting


o n in both the
commands
metadata and routing sections

r
Ensure certain respon ses are not sorted
e
within a sorted list

The types of sorts available in mrInterview are as follows:

Item Descripti n
Rotate o list is rotated by one category before each presentation of the
The category
list.
Randomize The category list is presented in randomized order.
Reverse The category
o list is reversed
e before each presentation. This means that thee list
is presented
e topdown to the first respondent,
e bottomup to the
t next, etc.
Ascending The category list is sorted in ascending alphabetical order.
Descending o list is sorted in descending alphabetical order.
The category

You can use any of the sorting features above in either the metadata or the routing sections as shown
in the next sections.

There is a difference using the randomize feature in the metadata and routing sections
when using the same response list for multiple questions. Using the metadata method will
hold the same pattern for each question per respondent; the routing method will change
the pattern for each question.

73
Chapter 7 Sorting Categorical Response Lists Survey Programming Fundamentals

Sorting in Metadata
To sort a question in the Metadata section, use any of the keywords for sorting following the curly
brackets of a category list.

Name "Text" categorical [min..max]


{ID1 "AltText1",
IDn "AltTextn" } sortingkeyword;

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
categorical Keyword to create a question with categories for response choices.
[Min..Max] Optional parameters. Controls the minimum and maximum amount of
categories that can be chosen by a respondent. Default is open to any amount
of choices. Automatically issues an error message if the number of responses
chosen is below the minimum or above the maximum.
{ } Indicates the start of the categories you wish the respondent to choose from for
the question
ID1, IDn Unique identifying name for the response.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.
sortingkeyword Represents one of the sorting keywords rotate or rot; randomize or ran; reverse
or rev; ascending or asc; descending or desc

In the example below, adding the ran keyword randomizes the response list.

Metadata (enUS, Question, Label)


Example

Souvenirs "Which of the following souvenirs do you prefer to purchase when on holiday
or vacation?"

categorical [1..]
{
Clothing,
Hats,
Postcards ,
SnowGlobes "Snow Globes"
} ran;

End Metadata

74
Survey Programming Fundamentals Chapter 7 Sorting Categorical Response Lists

Routing Section Sorting


In the routing section, the syntax for sorting is:

Name.Categories.Order=orderconstants.osortingkeyword

Item Description
Name Represents the name of the question to sort
Osortingkeyword Represents one of the sorting keywords oAscending, oDescending, oCustom,
oRandomize, oReverse, or oRotate.

Routing(Web)
Example
Souvenirs.Categories.Order=orderconstants.oAscending

Souvenirs.Ask()

End Routing

The above statement will sort the list alphabetically A to Z.

Not Sorting Specific Responses


There may be certain responses that you do not want sorted within a list, such as None of These or
All of These. To force a group of categories to retain its original position when the overall category
list is sorted, use the keyword fix.

Name "Text" categorical [min..max]

{ID1 "AltText1" fix,

IDn "AltTextn"} sortingkeyword;

Item Description
Fix Keyword to make the category prior to the keyword fixed in its original position,
regardless of the sort order
sortingkeyword Represents one of the sorting keywords listed in the previous section (example
ran)

75
Chapter 7 Sorting Categorical Response Lists Survey Programming Fundamentals

The following example will not sort the None of these option; it will stay at the bottom of the list. In
addition, the Other responses will always be the last in the series of items for their individual lists.

Metadata (enUS, Question, Label)


Example TravelHelp "Have you used any of the following to help you with your travel
arrangements?"
Categorical [1..]
{
TravelBooks "Travel Books"
{
LonelyPlanetBook "Lonely Planet",
Fodor "Fodor's" ,
Frommer "Frommer's" ,
otherBooks "Other Travel Book" other fix
} ran,
Websites
{
Expedia ,
Orbitz,
Govt "Government Websites",
otherwebsite "Other Website" other fix
} ran,
Noneofthese "None of these" style (indent = 0) fix exclusive
} ran;
End Metadata

This also demonstrates a style being used to force the None of these response to be lined up with
the Subheadings instead of indented (indent=0). You will learn more about styles in Chapter 13
Controlling the Look of Your Survey.

76
Survey Programming Fundamentals Chapter 7 Sorting Categorical Response Lists

Keeping Specific Categories Grouped Together


You may need to keep pairs or groups of categories together within a list, even when adding
randomization. You can achieve this by creating a sublist with the items that need to be kept together,
while randomizing the main question. The example below will randomize the TypeAccom question but
always keep the responses in the define list resorts together.

Metadata (enUS, Question, Label)


Example
Resorts define
{
FamilyResorts "Family Resorts",
CouplesResorts "Couples Resorts"
};

TypeAccom "At what type of accommodations did you stay?"


categorical [1..1]
{
Hotel ,
Motel ,
BedBreakfast "Bed and Breakfast",
Hostels ,
use Resorts sublist ,
OtherAccom "Other Accommodations" other fix
} ran;

End Metadata

77
Chapter 7 Sorting Categorical Response Lists Survey Programming Fundamentals

Exercise
Update the following questions by adding the features highlighted below in your GroceryBill.mdd file
to include sorted categories.

StoreName What was the name of the store in which you shopped? (RANDOMIZE)

Walmart
Safeway
Kroger
Albertsons
Ahold USA
Delhaize
Publix
WinnDixie
Other (Specify)

ItemTypes Which of the following categories of groceries did you purchase on this shopping trip?

(RANDOMIZE BOTH THE GROUPS AND THE ITEMS WITHIN THE GROUPS)

Prepared Foods
Cheese/Olive Bar
Salad Bar
Deli Items
NonPrepared Foods
Meat/Seafood
Produce
Canned Goods
Pasta/Grains
None of These

78
Survey Programming Fundamentals Chapter 8 Restricting Responses

Chapter 8 Restricting Responses


The logic behind the survey is an important part of research to ensure accurate data. In this section,
we can learn how to present the respondent with logical choices.

In this chapter we
w will:
Filter responses displayed
e on a questiono
based on previous
p answeers to questions

Filter responses based on your internal logic

Limit the maximum


m or minimum
m u
amounts
for numeric questions based
a on logic

Filter Categories
The Filter property can be used to limit the categories displayed by a question in the routing section.

Routing(Web)
Name.Categories.Filter=condition
Name.Ask()
End Routing

Item Description
Name Unique identifier for the question
s name.
Categories Property (keyword) of the question denoting the responses
Filter Property (keyw ord) to state you are restricting the categories
e for the question
condition Represents anything that states the categories to display for the question

79
Chapter 8 Restricting Responses Survey Programming Fundamentals

Here is an example in which we are asking respondents to choose all the hotel chains they have stayed
in the past year. The followup question is Of those chains, which is your favorite? The response list
for the followup question is restricted to only the answers given in the first question.

Metadata (enUS, Question, Label)


Example
HotelChainStayed "Choose the hotel chains you have stayed at this past year."
categorical [1..]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};
FavHotelChain "Of those chains, which one would you most prefer to stay at again?"
categorical
[1..1]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};

End Metadata

Routing(Web) HotelChainStayed.Ask()
FavHotelChain.Categories.Filter=HotelChainStayed.Response.Value
FavHotelChain.Ask()

End Routing

80
Survey Programming Fundamentals Chapter 8 Restricting Responses

If you choose:

The result will be:

Special Responses of DK, REF, and NA are not filtered out automatically. In addition, if any
of those special responses are chosen, it skips the filtered question.

81
Chapter 8 Restricting Responses Survey Programming Fundamentals

How does the above work? The filters are based on the NAMES of the responses. While it is not
necessary to use shared lists for filtering, it is a good practice when the response lists are identical to
ensure that the names are also identical.

You do NOT need to have the lists identical to filter one question off another. mrInterview will simply
match what it can and disregards the rest. For instance, what if our lists were different:

HotelChainStayed "Choose the hotel chains you have stayed at this past year."
Example categorical [1..]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};

FavHotelChain "Of the chains listed below in which you stayed, which one would you
most prefer to stay at again?" categorical
[1..1]
{
Accor,
Choice,
Hilton,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};

Routing(Web) HotelChainStayed.Ask()
FavHotelChain.Categories.Filter=HotelChainStayed.Response.Value
FavHotelChain.Ask()
End Routing

82
Survey Programming Fundamentals Chapter 8 Restricting Responses

If you choose:

The result is:

As you can see, even though InterContinental was chosen, it does not show in the list, since it is not
part of the categories in FavHotelChain.

The above examples assume a naming convention for your category names. This is
recommended as names that identify the response make more sense across the entire
project lifecycle.

83
Chapter 8 Restricting Responses Survey Programming Fundamentals

Additionally, the filter does not need to be a single question. This can be a multitude of conditions,
such as Dimensions functions or specific categories.

Suppose our previous example was slightly different. What if we had two separate questions that
collected the hotels stayed in the past year. We will need two filter statements:

Filter the response from the first question so that it cannot be chosen from the 2nd list
Filter to combine both the first response and the 2nd response for the final question

HotelChainStayMost "Choose the hotel chain you have stayed at the MOST this past
Example year."
categorical [1..1]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};

HotelChainStayed "Choose the other hotel chains you have stayed at this past year."
categorical [1..]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};

FavHotelChain "Of the chains listed below in which you stayed, which one would you
most prefer to stay at again?"
categorical [1..1]
{
Accor,
Choice,
Hilton,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};

84
Survey Programming Fundamentals Chapter 8 Restricting Responses

Routing(Web)
HotelChainStayMost.Ask()

HotelChainStayed.Categories.Filter= HotelChainStayed.Categories
HotelChainStayMost.Response.Value
HotelChainStayed.Ask()

FavHotelChain.categories.filter=Union(HotelChainStayMost,HotelChainStayed)
FavHotelChain.Ask()
End Routing

See the Dimensions Development Library for more categorical functions to help with filters,
such as Difference and Intersection) DDL.chm::/categorical_functions.htm

85
Chapter 8 Restricting Responses Survey Programming Fundamentals

Limiting Numeric Question Ranges Based on Logic


Another aspect of accurate data is to be able to set the minimum or maximum amount that can be
entered for a numeric response based off previous answers from the respondent. You can control the
minimum and maximum values for a question with the following statements in the routing section.

Name.Validation.MinValue = condition

Name.Validation.MaxValue = condition

Item Description
Name Metadata item name
Validation Property of questions
MinValue Property to control the minimum value allowed for a numeric question. Takes
precedence over what is stated as the minimum in square brackets on the
question.
MaxValue Property to control the maximum value allowed for a numeric question. Takes
precedence over what is stated as the maximum in square brackets on the
question.
Condition Represents the new value for the minimum or maximum limits

Metadata(enUS, Question, label)


Example
AmtSpentonHoliday "Approximately how much in total did you spend last year on your
holidays/vacations?" long [0..10000];

AmtSpentAir "And of that amount, how much was spent on airfares?" long [0..10000];

End Metadata

Routing(Web)
AmtSpentonHoliday.Ask()
AmtSpentAir.Validation.MaxValue = AmtSpentonHoliday.Response.Value
AmtSpentAir.Ask()
End Routing

86
Survey Programming Fundamentals Chapter 8 Restricting Responses

If you answered 5000 for the question AmtSpentonHoliday, then tried to submit an answer greater
than 5000 for AmtSpentAir, you would see the following:

87
Chapter 8 Restricting Responses Survey Programming Fundamentals

Exercise
Create a new metadata file called MealsOut.mdd. Make sure that:

You make shared lists for American Cuisine, International Cuisine, and restaurant attributes.
FavCuisine only displays the cuisines the respondent has ever eaten.
The answer to EatMealOut is not greater than the OrderMealOut amount.
Make the filter for the RestaurantOthr question be the responses not chosen in Restaurant1.
In addition, the other specify choice should show in RestaurantOther regardless if it was
chosen in Restaurant1.

CuisineEaten Which of the following types of Cuisine have you ever eaten?

American Cuisine
Barbecue
Cajun
Southern
Southwestern
International Cuisine
Italian
Russian
Polish
French
Caribbean
None of These

FavCuisine Of those mentioned, which one do you prefer?

American Cuisine
Barbecue
Cajun
Southern
Southwestern
International Cuisine
Italian
Russian
Polish
French
Caribbean
None of These

OrderMealOut On average, how many meals per week do you order from a restaurant?

(If zero to OrderMealOut, skip to Thanks)

88
Survey Programming Fundamentals Chapter 8 Restricting Responses

EatMealOut Of those meals, how many do you eat at the restaurant, as opposed to home delivery or
carryout?

(If zero to EatMealOut, skip to Thanks)

Restaurant1 When you eat at a restaurant, what one thing makes you want to return to the restaurant
again?

Good food
Good service
Nice Atmosphere
Large Selection of menu choices
Other (Specify)

RestaurantOthr What other factors also influence your decision to return to a restaurant?

Good food
Good service
Nice Atmosphere
Large Selection of menu choices
Other (Specify)

Thanks Thank you for your input.

89
Chapter 8 Restricting Responses Survey Programming Fundamentals

90
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page

Chapter 9 Multiple Questions on One Page


By default mrInterview displays one question per screen. There will be times when you will want to
display multiple questions on the same screen.

In this chapter we
w will:
q
Learn to place multiple questions on the
same screeen

Discuss hee differences between


b pagess and
blocks

ontrol if a question is presented on


Learn to co
the screen
n or in what rder.
o

You can place multiple questions on the same screen by using page or block statements.

Page metadata items reference other questions in the metadata to group them on the same
screen. If you are only trying to present more than one question on a screen, use a page.
Block metadata items contain other questions, similar to how a grid question can contain
multiple questions. The block type can be used to group a list of questions for presentation
and organizational purposes. For example, if you are trying to group questions together for use
with the analysis products mrTables and Desktop Reporter.

91
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals

Page
Creating a page in metadata creates a metadata item that states the questions you want displayed on
a screen and the order in which they should be displayed.

In the metadata section:

Name "text" page(QuestionName1, QuestionName2, QuestionNameN);

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"text" Optional text to show on the top of the screen
page Keyword to state we are grouping the following questions on the same page
QuestionName1, Represents the question names to display on the page together.
QuestionName2,
QuestionNamen

In the routing section, ask the page, not the individual questions:

Name.Ask()

Item Description
Name Name of the page metadata item
.Ask() Ask the questions listed in the page item

If you have many pages to create .Ask statements for, in the metadata viewer choose the
Page folder. Rightclick to choose Copy as Ask.

92
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page

The following is an example showing multiple demographic questions on the same screen.

Metadata (enUS, Question, label)


Example HouseHold "Including yourself, how many people currently live in your household?"
long [1 .. 99];

Age "To which of the following age categories do you belong?"


Categorical [1..1]
{
Under18 "Under 18",
_18to34 "18 to 34",
_35to54 "35 to 54",
_55plus "55 and over" ,
Refused "Prefer not to Answer" REF
};

Participate "Check here if you wish to participate in future studies on travel."


boolean;

Demos "Now a few demographic questions"


page(
HouseHold,
Age,
Participate
);
End Metadata

Routing

Demos.Ask()

End Routing

93
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals

Will display as:

Block
Blocks are metadata items that contain the questions you want displayed together on a screen.

Name "text" block fields

QuestionName1 "text" QuestionType;

QuestionNamen "text" QuestionType;

);

94
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page

Item Description
Name Represents the name of the block
"text" Optional text to show on the top of the screen
block Keyword to identify the item as a block
fields Start of the questions contained in the block
QuestionName1, Represents the questions contained inside the block
QuestionNamen

In the routing, ask the block name:

Name.Ask()

Item Description
Name Name of the block metadata item
.Ask() Ask the questions listed in the block item

As you can see in the following example, blocks are like containers which hold multiple questions.

Metadata (enUS, Question, label)


Example Demos "Now a few demographic questions" block fields
(

HouseHold "Including yourself, how many people currently live in your household?"
long [1 .. 99];

Age "To which of the following age categories do you belong?"


categorical [1..1]
{
Under18 "Under 18",
_18to34 "18 to 34",
_35to54 "35 to 54",
_55plus "55 and over" ,
Refused "Prefer not to Answer" REF
};

Participate "Check here if you wish to participate in future studies on travel."


boolean;
);
End Metadata

Routing
Demos.Ask()
End Routing

95
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals

The previous code will look identical to the page example when viewed in the browser. However, the
metadata itself is very different. The block creates a separate item for blocks, as seen in the metadata
viewer:

Since your questions are now contained within a block, this will also affect how you refer to a question
in a block.

Blockname.Name

96
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page

The following example shows how you would refer to questions in a block within the routing section.

Metadata (enUS, Question, label)


Example AgeGroups "" define
{
Under18 "Under 18",
_18to34 "18 to 34",
_35to54 "35 to 54",
_55plus "55 and over" };

Demos "Now a few demographic questions" block fields


(

HouseHold "Including yourself, how many people currently live in your household?"
long [1 .. 99];

Age "To which of the following age categories do you belong?"


categorical [1..1]
{ use AgeGroups ,
Refused "Prefer not to Answer" REF
};

Participate "Check here if you wish to participate in future studies on travel."


boolean;
);

KidsAtHome "Do you have any children under the age of 18 living in your household?"
categorical [1..1]
{
Yes ,
No
};

End Metadata

Routing
Demos.Ask()

If Demos.household.Response.Value > 1 then


KidsAtHome.Ask()
End if
End Routing

97
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals

Controlling How Page and Block Questions are Displayed


You can control the page or block questions asked on the screen by:

Filtering the page or block


Using a sorting keyword on the page/block

Filtering a Page/Block
Using the same principles we learned with filtering, we can use a QuestionFilter to restrict the
questions shown to certain respondents.

Name.QuestionFilter= Question1, QuestionN

Item Description
Name Name of the grid/loop question
QuestionFilter Property (keyword) to state you are restricting the questions of the page, or
block. This property also applies to grid/loop categories.
question1, Represents questions that will be added to the questionfilter and shown on the
questionN screen.

The following will not show the question asking to participate in future studies if they are already a
member of our panel group.

Metadata (enUS, Question, label)


Example
Membership "Are you currently a member of our panel?"
Categorical [1..1]
{
Yes,
No
};

HouseHold "Including yourself, how many people currently live in your household?"
long [1 .. 99];

Age "To which of the following age categories do you belong?"


categorical [1..1]
{
Under18 "Under 18",
_18to34 "18 to 34",
_35to54 "35 to 54",
_55plus "55 and over"
Refused "Prefer not to Answer" REF
};

98
Survey Programming Fundamentals Chapter 9 Multiple Questions on One Page

Participate "Check here if you wish to participate in future studies on travel."


boolean;

Demos "Now a few demographic questions"


page(
HouseHold,
Age,
Participate
);
End Metadata

Routing(Web)

Membership.Ask()

If Membership={Yes} then Demos.QuestionFilter=Household, Age


Demos.Ask()

End Routing

Sorting a Page/Block
You can control the order of the questions with the same sorting options as shown previously. Simply
apply the sort keyword to the block or page name.

The following example would randomize the questions shown on the screen for the demos page or
block.

Routing(Web)
Example
' Using Demos from the previous examples

Demos.QuestionOrder=OrderConstants.oRandomize

Demos.Ask()

End Routing

99
Chapter 9 Multiple Questions on One Page Survey Programming Fundamentals

Exercise
Open the GroceryBill.mdd file and Save As CH09GroceryBill.mdd. Modify CH09GroceryBill.mdd so that:

GroceryDate and StoreName are on the same page using a PAGE statement
Generic, ItemsBought, and GroceryCost are contained within a BLOCK item
Review the metadata for the block to see how it has changed

100
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids

Chapter 10 Repetitive Questions - Loops & Grids


Many surveys involve the concept of asking the same basic question with different attributes multiple
times. The concept is sometimes called a grid or a loop.

In this chapter we
w will:
n when to usee a grid or a loop in a
Understand
survey

Create metadata
e for grids
d and loops

Review different
f types of
o grids/loops

If your questionnaire contains a series of questions that look similar to this:

Please rate the following travel destinations on your inter st in visiting the location.
Extremely Somewhat
e Somewhat Extremely
t
Interested Interested Neutral Disinterested Disintereste d
Aruba { { { { {
Bermud a { { { { {
Florida { { { { {
Hawaii { { { { {
Fiji { { { { {
Costa Ri ca { { { { {
Thailand { { { { {

This is a good example of when to use the loop/grid metadata item. The properties this question has
that make it a loop/grid are:

All share the same responses (Extremely Interested, Somewhat Interested, etc.)
During analysis, we will want to see the results of each destination separately, but perhaps will
also want to see the results in summary in the format they appear in above.

You will also need to decide if you want to have the appearance of the questions to be exactly as we
see them above (i.e., on the screen all at once), or would we prefer that each question be on a
separate screen (i.e., "Please rate Aruba on your interest in visiting., Please rate Bermuda on your
interest in visiting., etc., ")

101
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals

Categorical Loops/Grids
We will define categorical loop/grids not by the type of questions they display, but by what defines the
number of times you repeat the questions. The first examples will show a list of categories defining
the number of times you will show the question in a loop/grid.

Name "GridText" loop

ID1 "Alt Text1",

IDn "Alt Textn"

} fields

Question1 "LoopText1 {@} ";

Questionn "LoopTextn {@}"

) expand grid;

Item Description
Name Unique identifier for loop/grid
"GridText" Optional text that will be displayed when the questions in the loop are asked
together on one screen.
Loop Keyword to mark a set of repeated questions and define the number of
repetitions required.
ID1 "Alt Text1", Defines the category list that controls the number of repetitions required. You
IDn"Alt Textn" define it in the same way as the category list for a categorical question.
Fields Keyword prior to the questions to be repeated in the loop
Question1, Questions that will be repeated based on the category list (ID1, ID2).
Questionn
LoopText1, Defines an optional label that will be displayed when the questions in the loop
LoopTextn are asked on individual screens.
{@} Represents the current category to display when the questions in the loop are
asked on individual screens.
expand Since mrInterview supports both a hierarchical and a flattened view of the
data, using the expand keyword means that the data is represented in both
formats (bounded).
grid Keyword that allows SPSS Dimensions applications and components to
recognize that the loop is a grid. Example would be printing grids using
mrPaper.
column Optional keyword to change the orientation of the category list to be the
columns of the grid instead of the rows. (Keyword row is the default.) Is
placed on the end of the metadata prior to the semicolon.

102
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids

Here is the syntax for the grid shown at the beginning of this chapter.

Metadata (enUS, Question, label)


Example
InterestinLocation "Please rate the following travel destinations on your interest in
visiting the location." loop
{
Aruba ,
Bermuda,
Florida,
Hawaii,
Fiji,
CostaRica,
Thailand
} fields
(
Rating ""
categorical [1..1]
{
ExtremelyInterested "Extremely Interested",
SomewhatInterested "Somewhat Interested",
Neutral "Neutral ",
SomewhatDisinterested "Somewhat Disinterested",
ExtremelyDisinterested "Extremely Disinterested"
};

) expand grid;

End Metadata

Routing(Web)

InterestinLocation.Ask()

End Routing

103
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals

In the previous example, since we asked the question using the loopname.Ask(), the survey will appear
in this format:

This is what this manual will refer to as a grid format.

If you want to change the orientation so that the destinations are across the top of the
screen, add the keyword column after the grid keyword.

104
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids

If we add text to the Rating question metadata and change the statement in the routing:

Metadata (enUS, Question, label)


Example
InterestinLocation "Please rate the following travel destinations on your interest in
visiting the location." loop
{
Aruba ,
Bermuda ,
Florida,
Hawaii,
Fiji,
CostaRica,
Thailand
} fields
(
Rating "Please rate {@} on your interest in visiting."
categorical [1..1]
{
ExtremelyInterested "Extremely Interested",
SomewhatInterested "Somewhat Interested",
Neutral "Neutral ",
SomewhatDisinterested "Somewhat Disinterested",
ExtremelyDisinterested "Extremely Disinterested"
};

) expand grid;

End Metadata

Routing(Web)

InterestinLocation[..].Ask()

End Routing

105
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals

Then the survey will come up one question at a time on the screen. The first time you will see:

A few things to remember about the previous example:

The main grid text (text prior to the keyword loop) will not show when the questions are asked
on individual screens.
The {@} will show the label of the current category, in this case, the destinations.
The [..] indicates that you want to step through each value in your categorical loop one at a
time.

If the above is not clear, think about how you would display just one of the questions in the
loop: InterestinLocation[{Aruba}].Ask()

For Each loops


An alternative way to write [..] and still have the questions come up individually on the screen would
be using a For Each loop statement.

Dim var

For each var in LoopName

var.Ask()

Next

106
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids

Item Description
Dim Declares a temporary variable to be used within the routing section
var Represents a temporary variable name you create
LoopName Name of our metadata loop/grid
For Each Marks the start and end of a loop. In this case, the loop is doing whats inside
Next the for/next for each question in another element. In this case our
metadata loop/grid. Each time through the For Each/Next , var will be the
individual questions of the loop/grid and will be asked by the var.Ask()
statement.

Here is the previous example written with a For Each/Next loop instead of the [..] syntax. This will
display the same in the browser as the previous example.

Metadata (enUS, Question, label)


Example
InterestinLocation "Please rate the following travel destinations on your interest in
visiting the location." loop
{
Aruba ,
Bermuda ,
Florida,
Hawaii,
Fiji,
CostaRica,
Thailand
} fields
(
Rating "Please rate {@} on your interest in visiting."
categorical [1..1]
{
ExtremelyInterested "Extremely Interested",
SomewhatInterested "Somewhat Interested",
Neutral "Neutral" ,
SomewhatDisinterested "Somewhat Disinterested",
ExtremelyDisinterested "Extremely Disinterested"
};

) expand grid;

End Metadata

107
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals

Routing(Web)
Dim location

For each location in InterestinLocation


location.Ask()
Next

End Routing

To help understand this, when running this code stop on one of the loop questions and
choose the Expressions tab and Evaluate location.QuestionFullName. Or you can choose
the Locals pane and look at the current value of location.

The For Each/Next loop will prove helpful in more complex scenarios.

Categorical Loops with a Numeric Question


Another example will show changing the type of question in the loop. This metadata example displays
numeric questions instead of a categorical scale.

ExpenseCategories define
Example
{ Transportation,

Accomodations,

FoodDrink "Food and Drinks",

OtherMisc "Other Miscellaneous"

};

BusTravelSpent "In the past year, approximately how much did you spend in each
category listed below for business travel?" loop

{ use ExpenseCategories} fields

BusTravel "Amount Spent on Business Travel"

long [0 .. ];

) expand grid;

108
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids

Would display in the browser like this:

You can also have multiple questions within a grid. The following example expands on the last
example to include two columns of numeric boxes on the screen:

Metadata (enUS, Question, label)


Example
ExpenseCategories define
{ Transportation,
Accomodations,
FoodDrink "Food and Drinks",
OtherMisc "Other Miscellaneous"
};

TravelSpent "In the past year, approximately how much did you spend in each category
listed below for business and leisure travel?" loop
{ use ExpenseCategories } fields
(
BusTravel "Business Travel"
long [0 .. ];

LeisureTravel "Leisure Travel"


long [0 .. ];

) expand grid;

Routing

TravelSpent.Ask()

End Routing

109
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals

110
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids

Numeric Loops
Another way to create repetitive questions in a grid/loop is to create a loop in which you set a number
to represent the loop driver.

Name "GridText" loop [n1..n2]

fields

Question1 "LoopText1 {@}";

Question2 "LoopText2 {@}"

) expand grid;

Item Description
Name Unique identifier for loop/grid
"GridText" Optional text that will be displayed when the questions in the loop are asked
together on one screen.
Loop Keyword to mark a set of repeated questions and define the number of
repetitions required.
[n1..n2] Defines the number of times you want the loop to execute.
Fields Keyword prior to the questions to be repeated in the loop
Question1, Questions that will be repeated based on the category list (ID1, ID2).
Questionn
LoopText1, Defines an optional label that will be displayed when the questions in the loop
LoopTextn are asked on individual screens.
{@} Represents the current category to display when the questions in the loop are
asked on individual screens.
Expand Since mrInterview supports both a hierarchical and a flattened view of the
data, using the expand keyword means that the data is represented in both
formats.
Grid Display the question as a grid when the question is printed using mrPaper. No
effect in browser based interviews.

The categories shown in previous loop examples are replaced with numbers. There are various ways to
specify the numbers which will represent the repetitions of the loop.

Description Example Results


Ranges [1..10] Will display the question in the grid/loop 10 times
Single Values [1,5,10] Will display the questions in the grid/loop 3 times, each time
representing one of the numbers listed
Step Values [1..10 step 2] Will display the questions in the grid/loop 5 times, each time
representing an odd number 1 to 9.
Exclusive Values [1..10 ^5] Will display the questions 9 times, eliminating the 5th time.

111
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals

The following will produce a pair of questions asked about the respondents last three trips.

Metadata (enUS, Question, label)


Example
Last3Trips "Please think about the last three times you traveled for business or pleasure
and answer the following questions." loop [1..3] fields
(
BusorLeis "Tell us about Trip # {@}. Was this trip for..."
categorical [1..1]
{
Business ,
Leisure,
Both
};

Accommodations "When you were traveling on Trip # {@}, which of the following types
of accommodations did you stay?"
categorical [1..]
{
Hotel,
Motel ,
BedBreakfast "Bed and Breakfast",
Hostels,
Resorts ,
OtherAccom "Other Accomodations" other
};

) expand grid;

End Metadata

Routing(Web)

Last3Trips[..].Ask()

End Routing

112
Survey Programming Fundamentals Chapter 10 Repetitive Questions Loops & Grids

The first time through the loop you will see:

113
Chapter 10 Repetitive Questions Loops & Grids Survey Programming Fundamentals

Exercise
Create a new metadata file, Meals.mdd for this exercise.

Think back to the last three meals of breakfast, lunch, and dinner that you consumed.

(ASK MEALTIME & MEALORIGIN ABOUT EACH MEAL.)

MealTime Thinking about the last [INSERT MEAL] you had, what time did you eat [INSERT MEAL]?

MealOrigin Was your [INSERT MEAL+

Made at home
Purchased from a restaurant

Calories How many calories do you estimate your last three meals of breakfast, lunch and dinner
contained?

Breakfast

Lunch

Dinner

HealthAttribs Please state your level of agreement with the following statements

Strongly Strongly
Agree Neutral Disagree
Agree Disagree
Breakfast is the most important meal of the day { { { { {
Eating fast food can be healthy { { { { {
I have a wellbalanced diet { { { { {
I dont eat a lot of sugar { { { { {

HealthComm Please add any additional comments you have about the importance of healthy foods
in restaurants.

114
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio

Chapter 11 Debugging Tools within mrStudio


Now that we are starting to learn more complex question types, we need to have some problem
solving skills. mrStudio provides many tools to help you in creating more complex surveys.

In this chapter we
w will:
p you troubleshoot
Review concepts to help h
your scriptt

Create test data within mrStudio


m

Create your
u own macross

Some of the items within mrStudio which may help you in testing your scripts are the ability to:

Have mrStudio produce test data for review.


Set points within your script that the survey will stop the action as you are testing to allow you
to investigate current values.
View the elements of a question, such as its style or controls, to see the current values as you
test your script.

Auto Answer Questionnaire


If you would like to view your skip patterns and view whats happening in your routing at a high level,
then you can have mrStudio automatically answer the questions for you and display the number of
responses each question received.

From the menu, choose the AutoAnswer icon shown below:

115
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals

You will be prompted for the number of interviews you wish to produce and the number of attempts
the system should make per question.

The result will show in the AutoAnswer window as shown below:

This shows that the FriendRelate question only received 2 out of the possible 10 automatically created
responses. When investigated further, this makes sense, as there was a skip pattern around that
question. Other good things to look at in this view would be questions with no responses, which could
mean you forgot to ask the question.

116
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio

Producing Test Data


Besides seeing the summary of answers created, we can also store those results to use as data checks
before the study goes live. With mrStudio, you can write to SPSS .SAV, .XML, Dimensions Data file
(.DDF), and Dimensions RDB database formats.

From the menu choose Tools


Select Write to Database

You can now choose the AutoAnswer icon or Tools Auto Answer Data Generation

You will still be prompted for the number of interviews you wish to produce and the number of
attempts the system should make per question.

117
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals

The first time you run this, you will now see the following screen asking you to choose the
datatype to create.

Choose your datatype and browse and name the new datafile.

If you choose to create a SPSS .SAV file, choose metadata type as none and just specify a
case data location and name.

118
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio

Adding Additional Data Sources


After setting your data source the first time, mrStudio will automatically write to this file each time.
mrStudio allows you to add multiple data sources if you wish to make test data in multiple formats.
View the Metadata Explorer and find the datasources collection. Rightclick on the folder and choose
Add DataSources. You will see the menu to choose the datatype and filename.

Now you will be able to Rightclick on DataSources and choose Change DataSource to choose which
datasource you want to create test data for.

119
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals

Setting Breakpoints

To find out what happens at critical points in your program, you need to stop execution at these points
and look at the contents of questions or temporary variables to see if they contain the correct values.
Points at which mrStudio stops to allow this investigation are called breakpoints.

To set a breakpoint, click on the grey area on the left side of the numbering in your routing section.
This should produce a large dot on that line as shown below:

You can use this feature in many ways. Many people test surveys and when they find a problem, they
want to stop and fix the problem and start retesting at that point.

Set a breakpoint in your routing at the question you want to review


Choose AutoAnswer
When prompted, make sure to choose Number of interviews to be set to 1
This will stop autoanswering at the question in which you set the breakpoint
Now choose F5 to continue out of AutoAnswer mode

This is an easy way to start using breakpoints. As your code becomes more complex, you will use
breakpoints to evaluate your code even more.

120
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio

Troubleshooting Specific Sections of Code


Another helpful feature is to step through the lines of the routing section, so you can pause and
evaluate each action. Then you can see the current values of questions or variables with the
Expressions tab or the locals pane.

To step through code, choose the F10 key or Debug Single Step.

Next, investigate specific question values or properties.

Using the Locals pane (View Locals) you can view previous answers to questions as shown in the
picture below.

In addition, you can see the properties of questions, such as the appropriate styles or proper names for
elements of a question.

121
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals

Using the Expressions tab, you can view or set the values to questions or variables in order to further
test your script. (View Expressions). In the example below, we are setting the value of the
TravelItem question to test the if then routing pattern we have created.

122
Survey Programming Fundamentals Chapter 11 Debugging Tools within mrStudio

Working with Macros


mrStudio contains macros to help you create scripts. You have the ability to add new macros and
modify or delete existing macros.

In mrStudio, choose Tools Macros. This will display the options shown below. Notice the 3 different
areas in which you can work with macros. For Interview Scripting, you should use:

mrScriptBasic: The macros will appear in the routing section


mrMetadataScript: The macros will appear in the metadata section

Updating/Deleting Existing Macros


Choose an existing macro from the list shown in the previous screenshot. Make any changes desired in
the Macro Text or Macro Name areas and choose the Update Macro icon. To delete an existing macro,
choose the macro and select the Delete Macro icon.

Adding Additional Macros


Create the code you wish to make into a macro. Then copy the code and choose Tools Macros.
Choose the appropriate area to place your macro (mrScriptBasic or mrMetadataScript), then copy the
code into the Macro Text window (Ctrl V). Create a unique name for the macro in the Macro Name
area. Then select the Add Macro icon.

123
Chapter 11 Debugging Tools within mrStudio Survey Programming Fundamentals

You can copy macros from one machine to another by copying the file,

C:\Documents and Settings\<your Windows user name>\Application Data\SPSS\


mrStudio\4.5.0.0\MacroDefinitions.xml.

124
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids

Chapter 12 Conditioned Loops and Grids


We have learned to create filtered questions based on answers to previous questions and logic.
Adding filter logic to loops and grids is the same concept.

This chapter looks at loops/grids filtered on:

v
Previous e within the loop
responses o

v
Previous q
e to a simple question
responses
outside
s the loop/grid
g

Previous
v responses
e to a different loop/grids
questions

u
A sublist o
of categories

Previous Respo ses Within the Loop


Suppose you have the following question:

If the response is Never, the respondent should not see the follow up question, Why do you
reference the travel guide, Lonely Planet? If we wish to repeat these pairs of questions for multiple
travel guides, then we must place the questions within a loop. The following loop demonstrates how
to write this logic within the routing section.

125
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals

Metadata (enUS, Question, label)


Example
TravelGuides "Now, some questions about Travel Guides." loop
{
LonelyPlanetBook "Lonely Planet" ,
Fodor "Fodor's",
Frommer "Frommer's"
} fields
(
Read "How often do you read or reference the travel guide, {@}?"
categorical [1..1]
{
Weekly ,
Monthly ,
Yearly,
Rarely ,
Never
};

WhyRead "Why do you reference the travel guide, {@}?"


categorical [1..]
{
Hotel "Advice on Hotels",
Neighborhoods "Information on Neighborhoods" ,
Attractions "Tourist Attractions" , SaveMoney
"Tips on how to save money" , Transportation
"Local travel/transportation" , OtherReason
"Other Reason" other ,
Refused "Prefer not to Answer" REF
};

) expand grid;

End Metadata

Routing(Web)

Dim tguide
For Each tguide In TravelGuides
tguide.Read.ask()
If tguide.Read.Response.Value <> {Never} Then
tguide.WhyRead.Ask()
End If
Next

126
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids

Breaking down the example above:

tguide is a temporary variable that will represent the categories of the loop (the travel guides)
For Each/next loop will loop through each tguide in our loop question, TravelGuides
tguide.Read.Ask() will ask just the question, read for each travel guide
The If statement checks the logic so that if the current value of tguides response to the read
question was not Never, then ask the followup question, WhyRead

Loops/Grids Filtered on Previous Responses Outside the Loop/Grid


In previous examples, we could filter the response list of a question by the responses to previous
questions. We can apply that same principle to the category list of a grid/loop. Instead of filtering the
categories of a question, we will do a QuestionFilter on a loop:

Name.QuestionFilter=categories

Item Description
Name Name of the grid/loop question
QuestionFilter Property (keyword) to state you are restricting the categories of the loop/grid
question
Categories Represents anything that states the categories you wish to display in the
loop/grid. Setting the filter equal to Null will set the filter to all valid categories.

The following is an example of a grid which will only show grid categories that are appropriate/logical
for the respondent.

Metadata(enUS, Question, Label)


Example
ResortTypes "" define
{
Historical,
AmusementPark "Amusement Park" ,
Beach "Beach" ,
Adventure "Adventure"
};

AttendedResort "From the list below, please indicate which types of resorts you have
stayed at."
categorical [1..] {use ResortTypes};

127
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals

RateResortLoop "Of the resorts you have stayed at, please rate them on your overall
satisfaction with your experiences at the resort." loop
{ use ResortTypes } fields
(
RateResort ""
categorical [1..1]
{ VerySatisfied "Very Satisfied",
SomewhatSat "Somewhat Satisfied" ,
SomewhatDisSat "Somewhat Dissatisfied" ,
VeryDissatisfied "Very Dissatisfied"
};

) expand grid;
End Metadata

Routing(Web) AttendedResort.Ask()
RateResortLoop.QuestionFilter=AttendedResort.Response.Value
RateResortLoop.Ask()
End Routing

If you choose:

128
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids

You will only have the responses chosen as the categories of the grid:

Loops/Grids Filtered on Responses to a Different Loop/Grids Questions


Sometimes the filter conditions can become more complex. Lets think about another scenario.
Looking at the grid from the last example:

suppose the followup question was,

Why are you satisfied overall with the [INSERT RESORT TYPE+? This should only be asked of the resort
types they responded very satisfied or somewhat satisfied.

129
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals

To correctly ask this followup, we need to:

Create a loop question containing the text question above to hold the answer separately for
each resort type (a single question would not be sufficient).
Create a QuestionFilter for the loop that holds the text question. This QuestionFilter should
contain only the resorts (categories) in which the respondent rated Very Satisfied or Somewhat
Satisfied in the previous loop.

Metadata (enUS, Question, Label)


Example
ResortTypes "" define
{
Historical,
AmusementPark "Amusement Park" ,
Beach "Beach" ,
Adventure "Adventure"
};

RateResortLoop "Of the resorts you have stayed at, please rate them on your overall
satisfaction with your experiences at the resort." loop
{ use ResortTypes } fields
(
RateResort ""
categorical [1..1]
{ VerySatisfied "Very Satisfied",
SomewhatSat "Somewhat Satisfied" ,
SomewhatDisSat "Somewhat Dissatisfied" ,
VeryDissatisfied "Very Dissatisfied"
};

) expand grid;

WhyLoop "" loop


{
use ResortTypes
} fields
(
WhyVerySat "Why are you satisfied overall with the {@} resort?"
text;

) expand grid;

End Metadata

130
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids

Routing(Web)
RateResortLoop.Ask()

Dim Resort
Dim WhyLoopFilter

WhyLoopFilter = {}
For Each Resort In RateResortLoop
If Resort.RateResort.ContainsAny({VerySatisfied, SomewhatSat}) Then
WhyLoopFilter = WhyLoopFilter + CCategorical(Resort.QuestionName)
End If
Next

WhyLoop.QuestionFilter = WhyLoopFilter
WhyLoop[..].Ask()

End Routing

You must set the variable WhyLoopFilter to {} so that it starts as a filter with nothing in it.

Loops/Grids Filtered on a Sublist of Categories


As we have learned in previous chapters, we can create sublists to make define lists more reusable.
You can also use sublists to create groups to be used as category filters.

Name.QuestionFilter=Name.Categories.sublistname

Item Description
Name Name of the grid/loop question
QuestionFilter Property (keyword) to state you are restricting the categories of the loop/grid
question
Categories Keyword for the categories of the grid/loop
sublistname Name of the sublist you wish to show in the grid/loop

The following example asks if the respondent primarily travels for business, leisure or both. Based on
this response, the followup grid question will display a define list with business travel attributes
(BusinessAttribs), leisure travel attributes (LeisureAttribs) or both lists.

131
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals

Metadata (enUS, Question, Label)


Example
BusinessAttribs define
{
MeetInPerson "I think meeting facetoface improves work communication." ,
WeekendTravel "Traveling on the weekends interferes with my personal time." ,
ArriveEarly "I like to arrive early to prepare for the next day's agenda."
};
LeisureAttribs define
{
ShortDistance"I like to take many short weekend trips vs one long vacation/holiday.",
family "Travel is a great time to reconnect with my family members.",
cost "I often splurge on vacation/holidays, picking the nicest hotels and locations."
};

primarytravel "Do you primarily travel for..."


categorical [1..1]
{
Business ,
Leisure ,
Both
};

TravelAttribs "Rate your agreement with the following statements." loop


{
use BusinessAttribs sublist
ran,
use LeisureAttribs sublist
ran
} ran fields
(
attrib ""
categorical [1..1]
{
SAgree "Strongly Agree" ,
Agree,
Neutral ,
Disagree ,
SDisagree "Strongly Disagree"
};
) expand grid;
End Metadata

The routing section would look like this:

132
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids

Routing(Web)
Example primarytravel.Ask()
Select Case PrimaryTravel.Response.Value
Case {Business}

TravelAttribs.QuestionFilter=TravelAttribs.Categories.BusinessAttribs
Case {Leisure}

TravelAttribs.QuestionFilter=TravelAttribs.Categories.LeisureAttribs

Case Else
TravelAttribs.QuestionFilter= Null
End Select

TravelAttribs.Ask()

End Routing

The code above will display:

Only the Business sublist for the TravelAttribs if they primarily travel for business
Only the Leisure sublist for the TravelAttribs if they primarily travel for leisure
Both lists if they chose Both for the primarytravel question

Breaking down the code above:

The QuestionFilter lines above are set equal to the Question.Categories.sublistname if the
respondent only chose business or leisure.
The QuestionFilter was set to Null when the respondent chose both. Null resets the
QuestionFilter so that all categories are shown. Another alternative is to set the filter to the
questions definedcategories.

Using the sublists as shown above does limit your abilities to sort, as the sublists can be
sorted within themselves, but you cannot sort the two sublists together. If sorting is an
issue and you wish to use a sublist as a filter, see filterbysublist.mdd on your CD for an
advanced function to eliminate the problem. This example dynamically creates a filter from
the categories in a sublist, instead of using the sublist for the filter directly.

133
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals

Exercise
Use the metadata file, Restaurant.mdd. The metadata has been completed; please add the routing
section and logic as stated below.

(Ask the next two questions (Eaten & OftenEat) for each of the restaurant types of:

Deli/Carry Out Restaurants without Seating

Fast Food Restaurants

Family/Casual Dining Restaurants

Upscale Restaurants)

Eaten Have you ever eaten in [INSERT TYPE OF RESTAURANT]?

Yes
No

OftenEat (If Yes) How often do you eat in [INSERT TYPE OF RESTAURANT]?

Daily Weekly
Monthly
Yearly or less

(Ask only if they said Yes to the type of Restaurant in the Eaten Question)

FoodQuality Please rate your overall satisfaction with the quality of food obtained in the following
types of restaurants.

Very Somewhat Somewhat Very


Neutral
Satisfied Satisfied Dissatisfied Dissatisfied
Deli/Carry Out Restaurants without Seating
{ { { { {
Fast Food Restaurant
{ { { { {
Family/Casual Dining Restaurant
{ { { { {
Upscale Restaurant { { { { {

134
Survey Programming Fundamentals Chapter 12 Conditioned Loops and Grids

(If Yes to Fast Food in Eaten Question, ask ChainAware and FastFoodQual.)

ChainAware Which of the following fast food chains have you eaten at?

Wendys
McDonalds
Burger King
Arbys
InNOut Burger
None of these

(Of the fast food chains mentioned in ChainAware)

FastFoodQual Please rate your overall satisfaction with the quality of food obtained in the following
fast food restaurants.

Very Somewhat Somewhat Very


Neutral
Satisfied Satisfied Dissatisfied Dissatisfied
Wendys { { { { {
McDonalds { { { { {
Burger King { { { { {
Arbys { { { { {
InNOut Burger { { { { {

135
Chapter 12 Conditioned Loops and Grids Survey Programming Fundamentals

136
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey

Chapter 13 Controlling the Look of Your Survey


Look and feel can be a crucial element of survey scripting. mrInterview provides great flexibility in
terms of modifying the look of your survey.

In this
t chapter we will learn:
w
Different ways to change the overall
appearancec of your survey

p different looks to your survey


How to apply

How to fffectively use styles


t within our
e script

Overview of the Formatting of a Survey


To fully utilize the capabilities of an mrInterview surveys appearance, you need to understand how the
overall formatting of the survey works. The hierarchy of items that affect the appearance of an
mrInterview survey a e:

1) HTML Templates (including Cascading Style sheets and .xml files). These are special HTML
pages that are applied to your survey.
2) Styles within the script. These are scripting properties added to either the metadata or the
routing section.

For example, if you format a specific question with a style in a way that contradicts what is in the HTML
template, then the question style will override the templates format for that question.

Now that you have a basic understanding of how templates and styles are applied to the survey, lets
take a closer look at each aspect.

Templates
Templates are HTML pages which have special mrInterview tags that represent the different parts of
a survey. Templates control the layout of the mrInterview page separate from the text of your
questionnaire as you created it in the metadata. This allows you the flexibility to create standard
templates for reuse in many projects. You can also use more than one template within a survey.

137
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals

The three main types of templates are:

Layout Template: Defines one page/screen layout. This template is usually created in a way in
which you can apply this to multiple studies if you want them to all have the same basic look.
Also, this does not necessarily mean that you have to create a completely new template file if
you want to vary just one aspect of the layout for a particular part of an interview or for a
different project. If the basic page layout is the same, you can create subtemplates for the
aspects that change.
SubTemplate: A template file that defines the layout of one aspect of the page. For
example, you can create subtemplates for questions (question and response texts), errors,
banners, navigation bars, and grids. The main page layout template (listed in the previous
bullet point) contains a basic tag indicating where the various components belong and the sub
templates define the exact layout for each component. You specify which subtemplates are to
be used by naming them in the routing section of the interview script or in the main layout
template.
Localized Template: Used for organizations that create surveys for people in multiple regions
of the world. Localized templates allow you to set the language of an interview based on the
respondent's browser language, and the language can be changed in the interview script. The
interviewing program passes the language to the HTML Player, which searches for the
appropriate template in that languages folder and then in the project folder.

In addition all three template types can be assigned globally or at a project level. The order in which
mrInterview looks for templates is as follows:

1. Project folder specific language passed as the current interviews language


2. Project folder default language
3. Project folder
4. Global templates folder specific language passed as the current interviews language
5. Global templates folder default language
6. Global templates folder

Because of all the variables listed above, you will want to thoroughly test your scripts in many different
ways to ensure that the proper look is being applied to your survey.

This course will only discuss how to apply the templates, not how to create the templates.
For more information, see the DDL: DDL.chm::/interviewscripting_templates_writing.htm

138
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey

Applying a Template within Your Script.


To apply a template within the routing section:

Routing(Web)

IOM.LayoutTemplate = "templatename.htm"

Name.Ask()

Item Description
IOM.LayoutTemplate Keywords to signify you are adding a template style to the survey from this
point forward in the routing section
templatename.htm The actual name of the template to apply

If a question is tied to a specific template or subtemplate (such as javascript logic to check a specific
question, or a complex question style), you may choose to add the template to the metadata:

Metadata(enUS, Question, Label)

Name "text"

templates(Question = "templatename.htm" ) questiontype

Item Description
Templates(Question=) Keywords to signify you are adding a template style to this specific question in
the metadata
Templatename.htm Represents the actual name of the template to apply
questiontype Represents the questions type (categorical, long, text, etc.) Note that the
template goes before the question type keyword.

139
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals

Below is an example of applying a template to the entire survey.

Example Routing(Web)

IOM.LayoutTemplate= "Card_Blue_TopAndBottomErrors.htm"
InterestinLocation.Ask()
BusTravelSpent.Ask()
TravelSpent.Ask()
HotelChainStayMost.Ask()
HotelChainStayed.Categories.Filter = HotelChainStayed.Categories
HotelChainStayed.Ask()
FavHotelChain.Ask()

End Routing

You can drastically change the appearance of a question with templates. mrStudio displays the
templates as they will appear when activated to mrInterview.

When reviewing your templates, you can choose to see a full browser view as opposed to the
smaller window within mrStudio, by changing the Use Builtin Browser option to False
under Tools Options. However, with this option you cannot use the F5 Auto Answer
feature easily.

Folders
The Dimensions Development Library provides you with example templates to use and modify. These
are included by default in C:\Program Files\SPSS Dimensions\DDL\Scripts\Interview\Templates
folder.

140
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey

Tips for Scriptwriters Regarding Templates


A few things to think about as you are using mrStudio to apply your templates:

If you have templates from previous versions of mrInterview, you need to ensure the
templates are XHTML or perfectly formed HTML. In the toolbar, choose HTML tidy to have
mrStudio try to clean up your code. This may not always work 100%, but is may be worth
seeing what the results are. Make a backup of your template files before attempting HTML
tidy.
Make sure that when you activate the study in mrInterview that you have included any project
specific templates you have been using locally in mrStudio.

Styles
Styles allow us to control the many formatting aspects of survey items from inside our survey script. We
can use styles on such items as questions, categories, labels and navigation controls. There are two
major groups of styles:

Default Styles: Default styles are settings that get applied to an entire group of survey items.
For example, default styles would be used to make changes to all the question text font for
that script.
Question Styles: Question styles are used to format items for specific questions.

In practice you should use default styles to perform the bulk of your formatting with styles. Use
question styles to apply unique or question specific formatting. It is recommended that you declare
your default styles at the top of the routing section of the survey. However, you can change the
settings of the default styles at any time in your survey.

Complete details regarding the available options of the styles object can be found in the
DDL: IOMLib.chm::/IStyle.html

Default Styles
There are six types of default styles and each group has a number of subtypes. For this introductory
course, we will focus only on the main default styles:

Default
Labels
Categories
Grids
Navigation
Questions

While each of these different areas represents a different area for potential formatting you should also
be aware of the interaction between the areas. The style settings from one area will cascade to other
style objects. The following is the order of precedence:

141
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals

1) DefaultStyles.Default
2) DefaultStyles.Label
3) DefaultStyles.Navigation and DefaultStyles.Categories
4) DefaultStyles.Questions
5) DefaultStyles.Questions.Labels
6) DefaultStyles.Question.Categories and DefaultStyles.Grids

For example, if we set the font differently in the default and labels sections, the labels section will be
the setting that is used. Lets review some of the different areas of a survey in which styles can be
applied.

Default
The default style is the style settings that all other styles are derived from. So these settings will form
the basis for all other default style types and/or question style settings.

IOM.DefaultStyles.Default

Example Routing(Web)

IOM.LayoutTemplate= "Card_Blue_TopAndBottomErrors.htm"

IOM.DefaultStyles.Default.Font.Family = "Tahoma"

InterestinLocation.Ask()

End Routing

The example above would set all text to be Tahoma for this study, overriding what has been set in the
template.

142
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey

Categories
The category default styles section is used to apply formatting to categorical responses.

IOM.DefaultStyles.Categories[CategoryStyleTypes.CategoryStyleTypeEnum]

Where the CategoryStyleTypesEnums are as follows:

CategoryStyleTypeEnum Description
csSingle Single response categorical.
csMulti Multiresponse categorical.
csExclusive Exclusive response categorical.
csList Subheading Text.

Example Routing(Web)

IOM.DefaultStyles.Categories[CategoryStyleTypes.csExclusive].Label.Font.Effects = _
FontEffects.feBold=null

ModeofTravel.Ask()

End Routing

The code above will turn all responses marked with the keywords exclusive, DK, REF, or NA to be
unbold.

143
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals

Grid
Default grid styles are used to control the format of grid questions. It allows us to specify formatting
for column/row headings as well as alternating columns/rows.

IOM.DefaultStyles.Grids[GridStyleTypes.GridStyleTypesEnum]

Where the GridStyleTypesEnums are as follows:

GridStyleTypes Enum Description


gsCell The cells of a grid.
gsAltRow The alternating rows of a grid.
gsAltCol The alternating columns of a grid.
gsRowHeader The row headings of a grid.
gsColHeader The column headings of a grid.
gsAltRowHeader The alternate row headings of a grid.
gsAltColHeader The alternate column headings of a grid.

Example Routing(Web)

'Default Grid Formatting


With IOM.DefaultStyles
'Row cell items
.Grids[GridStyleTypes.gsCell].Cell.BorderColor = "black"
.Grids[GridStyleTypes.gsCell].Cell.BorderStyle = BorderStyles.bsSolid
.Grids[GridStyleTypes.gsCell].Cell.BorderWidth = 1
'Alternate cell items
.Grids[GridStyleTypes.gsAltRow].Cell.BgColor = "#D5D5D5;"
'Row Headings
.Grids[GridStyleTypes.gsRowHeader].Cell.BorderColor = "black"
.Grids[GridStyleTypes.gsRowHeader].Cell.BorderStyle=BorderStyles .bsSolid
.Grids[GridStyleTypes.gsRowHeader].Cell.BorderWidth = 1
.Grids[GridStyleTypes.gsRowHeader].Cell.width= "120px"
'Column Headings
.Grids[GridStyleTypes.gsColHeader].Cell.BgColor = "#800000;"
.Grids[GridStyleTypes.gsColHeader].Color = "#FFFFFF;"
.Grids[GridStyleTypes.gsColHeader].Font.Effects = FontEffects.feBold
.Grids[GridStyleTypes.gsColHeader].Cell.BorderColor = "black"
.Grids[GridStyleTypes.gsColHeader].Cell.BorderStyle = BorderStyles.bsSolid
.Grids[GridStyleTypes.gsColHeader].Cell.BorderWidth = 1
.Grids[GridStyleTypes.gsColHeader].VerticalAlign = VerticalAlignments.vaBottom
.Grids[GridStyleTypes.gsColHeader].cell.wrap=true
.Grids[GridStyleTypes.gsColHeader].cell.width= "90px"
'Alternate Row Headings
.Grids[GridStyleTypes.gsAltRowHeader].Cell.BgColor = "#CECECE;"
End With

144
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey

InterestinLocation.Ask()

End Routing

This code has been written in a With/End With block. The With/End With statement allows you to
specify information that will be added to the beginning of each line that starts with an open dot (.)
within the block. If there is not an open dot, then the information on the With line is not added. The
previous code will format all grids within the project with the properties specified. There is no
template applied to the picture below, only the styles specified above.

145
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals

Labels
Label default styles allow us to specify formatting for different types of labels. For example, we may
want all question labels to use a different size font than the category labels.

IOM.DefaultStyles.Labels[LabelStyleTypes.LabelStyleTypesEnum]

Where LabelStyleTypesEnum are:

LabelStyleTypes Enum Description


lsQuestion Style for question labels.
lsCategory Style for category labels.
lsBanner Style for banner labels.
lsError Style for error labels.
lsNavigation Style for navigation labels.
lsTitle Style for title labels.

The code below will make all question text to have a font size of 24.

Example Routing(Web)

IOM.DefaultStyles.Labels[LabelStyleTypes.lsQuestion].Font.Size = 24

AmtSpentYr.Ask()

End Routing

Navigation
Default navigation styles can be used to format the look and feel of the navigation buttons.

IOM.DefaultStyles.Navigation

Example Routing(Web)

IOM.DefaultStyles.Navigation.BgColor = "#0099FF"

AmtSpenYr.Ask()

End Routing

The code above will create a blue background color on the navigation buttons.

146
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey

The number that represents the color is a hexadecimal color value and is commonly used to
create a very specific color. You can find many websites that provide these color codes.
Search for terms like web safe colors.

Questions
Question default styles allow you to define formatting specific to the type of question being displayed.

IOM.DefaultStyles.Questions[QuestionStyleTypes.QuestionStyleTypesEnum]

Where the QuestionStyleTypesEnums are:

QuestionStyleTypes Enum Description


qsInfo Information items.
qsLong Long (integer) questions
qsText Text questions
qsCategorical Categorical Questions
qsDate Date questions
qsDouble Double (real) questions
qsBoolean Boolean questions
qsLoopCategorical Categorical loops.
qsLoopNumeric Numeric loops.
qsCompound Compound questions
qsBlock Block questions
qsPage Multiple question page items.
qsOther Automatic Other Specify questions.

For example the following can be used to make all "other specify" textboxes a certain size.

Example Routing(Web)

IOM.DefaultStyles.Questions[QuestionStyleTypes.qsOther].Style.Width = 220

HotelChainStayed.Ask()

End Routing

147
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals

Question Styles
The same types of styles we discussed as default can be applied at the question level. The use of
question styles should be minimal, for very specific formatting needs. This section will discuss some
common questionspecific formatting needs.

Categorical Questions
With a categorical question you may want to display the available categories in multiple columns or
using a list box or combo box rather than the traditional checkboxes or radio buttons.

The following example will create 2 columns of responses instead of a single column.

Example Routing(Web)

HotelChainStayed.Style.Columns = 2

HotelChainStayed.Ask()

End Routing

The following example will create a dropdown list. Note that the categories have a subheading of
Select One. This is done so that the respondent must choose an answer, since the subheading is not
a valid response.

Metadata (enUS, Question, Label)


Example Souvenirs "Which of the following souvenirs do you prefer to purchase when on holiday
or vacation?"
categorical [1..1]
{
SelectOne "Select One"
{
Clothing ,
Hats,
Postcards ,
SnowGlobes "Snow Globes"
}
};
End Metadata

148
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey

Routing(Web)

Souvenirs.Style.Control.Type = ControlTypes.ctDropList
Souvenirs.Ask()

End Routing

You can also control the column width for the droplist or combo box with:
Name.Style.Width

Text Questions
For a text question you may want to control the width and height of the textbox generated. The
following will modify the width and height of the question.

Example Routing(Web)

WhySouvenir.Style.Width=400
WhySouvenir.Style.Height=50
WhySouvenir.Ask()

End Routing

You can also change the type of textbox that will be created:

To change to a single line format:

TextQ.Style.Control.Type = ControlTypes.ctSingleLineEdit

To mask what is typed in the box with dots instead of the characters:

TextQ.Style.Control.Type = ControlTypes.ctPassword

149
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals

Metadata Styles
When a style is specific to a question, it may be better to apply the style to the question directly in the
metadata. The options available are the same as in the routing, but have a slightly different syntax.
The code below will orient the responses horizontally (orientation = row) and replaces the buttons and
text with an image.

Metadata (enUS, Question, Label)


Example HappyLastTravel "Choose the image below that indicates how happy you were the LAST
time you traveled."
style(Orientation = Row)
categorical [1..1]
{
VeryHappy "Very happy"
style(Image = "VeryHappy.gif", Control(Type = "Button")),

SlightlyHappy "Slightly happy"


style(Image = "SlightlyHappy.gif", Control(Type = "Button")),

NeitherNor "Neither happy nor unhappy"


style(Image = "NeitherNor.gif", Control(Type = "Button")),

SlightlyUnhappy "Slightly unhappy"


style(Image = "SlightlyUnhappy.gif", Control(Type = "Button")),

VeryUnhappy "Very unhappy"


style(Image = "VeryUnhappy.gif", Control(Type = "Button"))
};

End Metadata

The code above will produce the following question:

150
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey

Custom Controls
Custom controls are a type of subtemplate that generates an interactive control that respondents can
use to answer a question. For example, if you have a date question you may want the respondent to
see a calendar. You could have the respondent flip through a calendar and then click on the date to
answer the question.

For an example of a custom control, review the calendar example in the DDL project,
C:\Program Files\SPSS Dimensions\DDL\Scripts\Interview\Projects\NewFeature.mdd

XHTML in Labels
We have seen that templates allow us to control the overall look of a survey page. We can use styles to
format individual labels or other survey items. However, sometime you may need to format just a
single word on a label. This type of granular formatting falls outside of templates and styles. We can
use XHTML within our metadata file to perform this type of formatting.

What is XHTML?
XHTML is a markup language based on HTML. The primary difference is the need for all tags to be well
formed. This means that all tags must have an opening and closing tag.

Here are a few basic tags that may prove useful within your script:

Tag Description
<b>text</b> Bold Tag
<i>text</i> Italic Tag
<u>text</u> Underline
<br /> Carriage Return

151
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals

TravelItem "From the list below, which <b>one</b> item would you most want to bring
Example with you on a leisure trip?"
categorical [1..1]
{
Camera ,
Map,
ComfortableFootwear "Comfortable Footwear",
FriendTravelCompanion "Friend/Travel Companion"
};

It is recommended that you only include XHTML tags when none of the other formatting options
provide a suitable solution. This is due to that fact that these tags can mean additional work when
relating to translation and/or reporting.

Final Thoughts on Formatting


When people are faced with so many places to apply formatting, they may be confused by what
formatting should go where. One issue you should take into consideration when deciding where to
apply specific looks of your survey is system efficiency vs. ease of use. Lets say for example that you
want all the surveys to have a default font of "Tahoma"; where is the best place to declare this? Since
you want this applied to everything, ideally you should put this in the template or associated CSS file
since it is at the highest level. In this way you get the correct font without having to declare anything
in your survey. Also if you later change your style you will not need to update any scripts. (Not to
mention mrInterview will not have to process that style detail.) And you can still use the styles to
override the templates when necessary.

152
Survey Programming Fundamentals Chapter 13 Controlling the Look of Your Survey

Exercise
Open the Meals.mdd file and Save as MealsWithStyle.mdd

Add the template, Verge_Layout.htm file to the document


The Calories grid has numeric responses; make a box size of 50 for those numeric questions.
Change the HealthComm box size to height of 100 and width of 550.

As time allows format all the grids to have the following look:

Hints:

Size of columns = 90px


Color of rating scale text = #BB342B
Color of alternate rows = #B8B8B8
Borders are solid, 1 width, and color of #B8B8B8

153
Chapter 13 Controlling the Look of Your Survey Survey Programming Fundamentals

154
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings

Chapter 14 Text Substitutions and Text Headings


You may need to have text within your survey that changes with the responses given. For instance, if
you want to list how many answers were chosen at a previous question or to have text that reflects a
positive or negative rating to a previous question (Why did you give the product a positive rating?).

In this chapter we
w will:
Display n answer to a previous question in
a the off the survey
text

Displaying answers to previous


r questions
o
within a grrid

Insert textt into the metadata


a that will be
controlled in the routing section

Displaying Responses to Previous Questions


You can display the answers to previous questions in the survey within any of the text in the metadata.

{#Name}

Item Description
Name Name of the
h question that contains the response you want to display

Souvenirs "Which of the following souvenirs do you prefer to purchase when on holiday
Example or vacation?"
categorical [1..1]
{
Clothing ,
Hats,
Postcards,
SnowGlobes "Snow Globes"
} ran;

WhySouvenir "Why do you prefer to purchase {#Souvenirs} when on holiday or vacation?"


text;

155
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals

If Snow Globes was chosen in the Souvenir question previously, the WhySouvenir question will appear
as:

If you are inside a loop and you want to display the item driving the loop, use the {@} sign.

Metadata (enUS, Question, Label)


Example
InterestinLocation "Please rate the following travel destinations on your interest in
visiting the location." loop
{
Aruba ,
Bermuda,
Florida,
Hawaii,
Fiji,
CostaRica "Costa Rica",
Thailand "Thailand"
} fields
(
Rating "Please rate {@} on your interest in visiting."
Categorical [1]
{
ExtremelyInterested "Extremely Interested",
SomewhatInterested "Somewhat Interested",
Neutral ,
SomewhatDisinterested "Somewhat Disinterested" ,
ExtremelyDisinterested "Extremely Disinterested"
};
) expand grid;
End Metadata

156
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings

If the question is within a loop/grid and you need to reference it outside the loop, then the reference is
slightly different. You need to use the root level operator \. in the syntax:

{#\.LoopName[{LoopCategory}].InsideQuestion}

Item Description
Loopname Name of the loop
LoopCategory Specific loop/grid slice you wish to display the answer to
InsideQuestion Question within the loop/grid

The following will display the response to a specific grid slice in the follow up text question.

Metadata (enUS, Question, Label)


Example
InterestInLocation "Please rate the following travel destinations on your interest in
visiting the location." Loop
{
Aruba ,
Bermuda,
Florida,
Hawaii,
Fiji,
CostaRica "Costa Rica",
Thailand "Thailand"
} fields
(
Rating "Please rate {@} on your interest in visiting."
categorical
{
ExtremelyInterested "Extremely Interested",
SomewhatInterested "Somewhat Interested",
Neutral ,
SomewhatDisinterested "Somewhat Disinterested ,
ExtremelyDisinterested "Extremely Disinterested"
};
) expand grid;

WhyAruba "Why did you rate Aruba {#\.InterestinLocation[{Aruba}].Rating}?"


text;

End Metadata

157
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals

Insert Text into the Metadata that will be controlled in the routing section
There will be other times in which you will control the text to be shown instead of redisplaying a
previous answer. To achieve this, you need to use a text insert. There are two parts to creating this
item. Add a marker in the metadata to represent the text you wish to insert, and then create a
reference to this within the routing.

Metadata (enUS, Question, Label)


Name "Text {Marker}" type parameters;

End Metadata

Routing(Web)

Name.Label.Inserts[ "Marker" ].Text = Value

OR

Name.Ask(Value)

End Routing

Item Description
Name Name of the metadata item that contains the placeholder or Marker
Text Text associated with the item
{Marker} or Represents the variable you created to be the placeholder for the text you want
["Marker"] to insert. As shown above, it is referenced differently in the metadata vs. the
routing.
Type Identifies the item for its functionality (categorical questions, text only items,
etc.)
Parameters This varies by item type, but an example would be the responses to a question.
Value Represents the text you want to insert in Marker. We recommend making the
text to be inserted an info item in the metadata for ease of translation.

158
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings

The following example will substitute text for the ExplainChain question based on if the respondent
chose one answer or many answers to the HotelChainStayed question. Notice the text to be
substituted is stored in info items in the metadata. This is a good practice if the study is to be done in
multiple languages.

Metadata (enUS, Question, Label)


Example HotelChainStayed "Choose the hotel chains you have stayed at this past year."
categorical [1..]
{
InterContinental ,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
OtherHotel "Other Hotel Chain" other,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};

ExplainChains "Please give a brief explanation why you chose to stay at {Chain} as
opposed to others in the past year."
text [1..];

OneChain "this chain" info;

Chains "these chains" info;

End Metadata

Routing (Web)

HotelChainStayed.Ask()

If Not(HotelChainStayed.ContainsAny({DontKnow,Refused})) Then
If AnswerCount(HotelChainStayed) = 1 then
ExplainChains.Label.Inserts["Chain"].Text = OneChain.Label
Else
ExplainChains.Label.Inserts["Chain"].Text = Chains.Label
End If

ExplainChains.Ask()
End If

End Routing

159
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals

There is an alternative to the method for text substitution shown above. You can also add the insert
reference into the ask statement. The example below shows the previous insert example, but using
the alternative method.

Metadata (enUS, Question, Label)


Example HotelChainStayed "Choose the hotel chains you have stayed at this past year."
categorical [1..]
{
InterContinental ,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
OtherHotel "Other Hotel Chain" other,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};

ExplainChains "Please give a brief explanation why you chose to stay at {Chain} as
opposed to others in the past year."
text [1..];

OneChain "this chain" info;

Chains "these chains" info;

End Metadata

Routing (Web)

HotelChainStayed.Ask()

If Not(HotelChainStayed.ContainsAny({DontKnow,Refused})) Then
If AnswerCount(HotelChainStayed) = 1 then
ExplainChains.Ask(OneChain.Label)
Else
ExplainChains.Ask(Chains.Label)
End If
End If

End Routing

160
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings

Here is an example that gets rid of the extraneous text that mrInterview places in a text insert for a
previous question when the answer is an other specify. You do not use the standard {#Name}, but
instead create a text insert with a condition to check for the other.

Metadata (enUS, Question, Label)


Example
TypeAccom "At what type of accommodations did you stay?"
categorical [1..1]
{
Hotels ,
Motels,
BedBreakfast "Bed and Breakfasts",
Hostels ,
Resorts ,
OtherAccom "Other Accommodations" other
};

HowFreqStay "How frequently do you stay at {Accom}?"


categorical [1..1]
{
VeryFreqently "Very Frequently" ,
SomewhatFreqently "Somewhat Frequently",
Rarely ,
FirstTime "This was the first time"
};
End Metadata

Routing (Web)

TypeAccom.Ask()

if TypeAccom = {OtherAccom} then

HowFreqStay.Label.Inserts["Accom"]=TypeAccom.OtherAccom
else
HowFreqStay.Label.Inserts["Accom"]=TypeAccom.Response.Label
end if
HowFreqStay.Ask()

End Routing

161
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals

Text Headings
You may wish to include headings that are applied to a single question or multiple screens. This can be
achieved by creating a banner. In the routing section, place the following statement:

To add a new heading:

Name.Banners.AddNew("BannerName", InfoName.Label)

To reuse a banner with different text:

IOM.Banners["BannerName"].Text = NewInfoName.Label

To remove a banner:

Name.Banners.Remove("BannerName")

Item Description
Name Name of the question or page to apply the heading. This can also be IOM to
use the same heading for multiple screens.
BannerName Unique name for the banner. Must follow standard naming conventions.
InfoName.Label, Name of the info item holding the text you wish to display. You can also choose
NewInfoName.Label to place specific text in double quotes within this item.

When adding banners, it is recommended that you place the text in info items instead of directly in the
routing section. This allows your surveys to be easily translated into multiple languages or contexts. In
the example below, we are adding one banner and changing its text during the survey to accommodate
the different sections.

Metadata (enUS, Question, Label)


Example
HotelChainStayed "Choose the hotel chains you have stayed at this past year."
categorical [1..]
{
InterContinental ,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
OtherHotel "Other Hotel Chain" Other,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};

162
Survey Programming Fundamentals Chapter 14 Text Substitutions and Text Headings

FavHotelChain "Of those chains, which one would you most prefer to stay at again?"
categorical [1..1]
{
InterContinental ,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
OtherHotel "Other Hotel Chain" Other,
DontKnow "Dont Remember" DK,
Refused "Prefer not to Answer" REF
};

InterestinLocation "Please rate the following travel destinations on your interest in


visiting the location." loop
{
Aruba,
Bermuda,
Florida,
Hawaii,
Fiji,
CostaRica,
Thailand
} fields
(
Rating "Please rate {@} on your interest in visiting"
categorical [1..1]
{
ExtremelyInterested "Extremely Interested",
SomewhatInterested "Somewhat Interested",
Neutral "Neutral",
SomewhatDisinterested "Somewhat Disinterested ",
ExtremelyDisinterested "Extremely Disinterested"
};

) expand grid;

HotelText "Hotel Questions" info;

DestinationText "Destination Questions" info;

End Metadata

163
Chapter 14 Text Substitutions and Text Headings Survey Programming Fundamentals

Routing (Web)
IOM.DefaultStyles.Labels[LabelStyleTypes.lsBanner].Font.Size = 24

IOM.Banners.AddNew("Header",HotelText.Label)
HotelChainStayed.Ask()
FavHotelChain.Categories.Filter= HotelChainStayed.Response.Value
FavHotelChain.Ask()

IOM.Banners["Header"].Text = DestinationText.Label
Dim location
For each location in InterestinLocation
location.ask()
Next
End Routing

The above example will display different headings for the different screens. We have also added a
default style to increase the font size of the Banner Text as shown below:

164
Survey Programming Fundamentals Chapter 15 Enhancing Survey Flow

Chapter 15 Enhancing Survey Flow


To obtain accurate data, by default mrInterview requires a response to each question. At times, you
may want to either preset information into questions or allow respondents to not answer the
question and continue with the survey.

In this chapter we
w will:
t initial answers
Preassign the e to questions.

Understand d the property that allows respondents


o
to not give an answer to a question
q

Allow for an
n answer to be tthe default response

As stated above, mrInterview requires a response to each question. To override this option, you must
do 2 things:

Set the MustAnswer property to False


Provide mrInterview with a default answer when the respondent does not choose a response.

Technically, there is still an answer for each question when you look at your data, however the
respondent will not have to respond to every question when it isnt necessary. A good use of this
feature would be a text question for optional comments. If the respondent did not have a comment,
they could simply choose the Next button to continue with the survey while mrInterview will record
the response as the predetermined default.

165
Chapter 15 Enhancing Survey Flow Survey Programming Fundamentals

Must Answer
The MustAnswer property can be applied at the IOM level, or on a question, page or block level.

Routing(Web)

Name.MustAnswer=False

The first statement would only apply to a specific question. The IOM statement above would prepare
all questions in the study to potentially not give an answer.

If mrInterview is not provided with a valid default answer, then the question will need to be
answered by the respondent before going to the next question. The exception for this is a
categorical question in which the minimum is not stated (example [..5]).

Default Answers
Default Answers can either be directly assigned by the programmer or use the preassigned default
value of No Answer. You can specify default answers in the metadata or routing sections.

In Metadata section:
Name "text" questiontype

DefaultAnswer(response);

Or Routing section:

Name.Response.Default=response

Item Description
Name Represents the question name
response Represents a valid response to the question (valid number for long questions,
category name for categorical questions, etc.)

166
Survey Programming Fundamentals Chapter 15 Enhancing Survey Flow

The following is an example of adding default responses in the metadata.

TravelSpent "In the past year, approximately how many much did you spend in each
Example category listed below for business and leisure travel?" loop
{
Transportation,
Accomodations,
FoodDrink "Food and Drinks",
OtherMisc "Other Miscellaneous"
} fields
(
BusTravel "Business Travel"
long [0 .. ] defaultanswer(0);

LeisureTravel "Leisure Travel"


long [0 .. ] defaultanswer(0)
) expand grid;

The result will not change with the addition of the defaults:

However if any cell is left blank, the default answer of zero will be entered instead of mrInterview
issuing an error message of Missing Answer(s).

167
Chapter 15 Enhancing Survey Flow Survey Programming Fundamentals

You can even set default values for categorical questions:

Metadata (enUS, Question, Label)


Example
Age "To which of the following age categories do you belong?"
categorical [1..1]
{
Under18 "Under 18",
_18to34 "18 to 34",
_35to54 "35 to 54",
_55plus "55 and over",
Refused "Prefer not to Answer" REF
} defaultanswer ( {Refused} );

End Metadata

In the above example if the respondent doesnt answer the question, when they click the Next button
the answer will be recorded as Refused.

Another way to set this default would be in the routing section:

Routing(Web)
Example
Age.Response.Default={Refused}

Age.Ask()

End Routing

To use defaults options, the default answer must be set to a valid response for the question.

168
Survey Programming Fundamentals Chapter 15 Enhancing Survey Flow

Hidden default responses


The keyword NA is the assumed value for the property defaultanswer. If you have:

The MustAnswer=False
A response assigned to the keyword NA
No defaultanswer response specified

Then the No Answer response will be hidden on the screen and if the respondent does not answer the
question and goes to the next screen, the No Answer response will be automatically chosen for that
question.

Metadata (enUS, Question, Label)


Example AddComments "Please provide us with any additional comments."

text

codes( { NoAnswer "No Comments" NA } );

End Metadata

Routing(Web)

AddComments.MustAnswer=False

AddComments.Ask()

End Routing

The screen displays:

As you can see above, there is not a No Comments reply on the screen due to the presence of the
MustAnswer=False and the lack of a DefaultAnswer specified.

169
Chapter 15 Enhancing Survey Flow Survey Programming Fundamentals

Initial Response
Instead of assigning default values when the respondent does not answer a question, you could have
an answer already assigned to the question when it is first shown to the respondent. This could be
used for large grids in which every response may not be applicable to the respondent. This is called an
initialanswer and is applied in the same way as the defaultanswer.

TravelSpent "In the past year, approximately how many much did you spend in each
Example category listed below for business and leisure travel?" loop
{
Transportation "Transportation",
Accomodations "Accomodations",
FoodDrink "Food and Drinks",
OtherMisc "Other Miscellaneous"
} fields
(
BusTravel "Business Travel"
long [0 .. ] initialanswer(0);

LeisureTravel "Leisure Travel"


long [0 .. ] initialanswer(0)

) expand grid;

This would be what the screen would look like when the respondent first sees the question:

170
Survey Programming Fundamentals Chapter 15 Enhancing Survey Flow

The code in the routing section to set the initial value for this complex question type would be:

Metadata (enUS, Question, Label)


Example
TravelSpent "In the past year, approximately how many much did you spend in each
category listed below for business and leisure travel?" loop
{
Transportation "Transportation",
Accomodations "Accomodations",
FoodDrink "Food and Drinks",
OtherMisc "Other Miscellaneous"
} fields
(
BusTravel "Business Travel"
long [0 .. ];

LeisureTravel "Leisure Travel"


long [0 .. ]

) expand grid;

End Metadata

Routing(Web)

TravelSpent[..].BusTravel.Response.Initial=0
TravelSpent[..].LeisureTravel.Response.Initial=0
TravelSpent.Ask()

End Routing

Initial value will only be set the first time the respondent is shown the question, meaning if
they use the previous button to go back to questions, their answers will not be reset again
if they have changed the values. If you would like to always reset the values, then use the
QuestionName.Response.Value = response.

171
Chapter 15 Enhancing Survey Flow Survey Programming Fundamentals

Exercise
Open mealswithstyle.mdd file and make the following modifications.

Make HealthComm allow the respondent to move past the question without answering
Give the HealthAttribs loop initial values of Neutral
Add the following question after the HealthAttribs grid:
FastFoodComments Please elaborate on why you [AGREE/DISAGREE] with the statement
Eating fast food can be healthy.

Prefer not to Answer

Respondents who chose Neutral for the attribute Eating fast food can be healthy
should not be asked the FastFoodComments question.
For the insert AGREE OR DISAGREE, insert the word agree if the respondent chose
Strongly Agree or Agree for the Eating fast food can be healthy attribute; insert
disagree if the respondent chose Strongly Disagree or Disagree.
(Hint: If you need help determining how to reference one attribute within a grid
outside the grid, refer to the information item on page 106.)

172
Survey Programming Fundamentals Chapter 16 Customizing the Standard Error Messages

Chapter 16 Customizing the Standard Error Messages


There may be times when the standard error messages are not descriptive enough for a specific
question, or your organization has standards for the error text that are different than the defaults. You
can control the text of the standard error messages.

In this chapter we
w will:
o
Learn the keywords associated with he
standard error messagess

Customizee the text of he error messages


within your
u script for a specific questi on

r message or all
Change he standard error
surveys

Each standard error message has a name associated with it and is listed in the table below.

Message Name Message Text When isplayed


MissingAnswer w
Missing answer(s). The respondent clicks Next without answering the
question, and the script does not specify a default
answer. Also applies when the respondent does e
not enter answers in all cells of a grid.
NotNumeric Answer '{ANSWER}' is not The response cannot be converted into a valid
numeric. long (integer) or double (decimal), as appropriate.
NotInteger Answer '{ANSWER}' is not The response is a numeric value, but is not an
a
an integer value. integer value.
NotDate Answer '{ANSWER}' is not a The response cannot be converted into a valid
valid date. date.
n
NotInRange Answer '{ANSWER}' is not The response does not fall within the range
A
in range '{RANGE}'. specified for the qu estion.
NotSingleAnswer Only one answer is More than one response was chosen from a single
allowed. choice response list.
TooFewAnswers
A There are too few answers, The number
m of responses chosen from a multiple
at least {MINANSWERS}
N aare choice list is less than the minim um number
required. required for the question.

173
Chapter 16 Customizing the Standard Error Messages Survey Program

Message Name Message Text When displayed


TooManyAnswers There are too many answers, The number of responses chosen from
only {MAXANSWERS} are a multiple choice list is greater than the
allowed. maximum number allowed for the
question.
CannotCombine Answer '{ANSWER}' More than one response was selected,
({CATEGORY}) cannot be one of which was marked as exclusive.
combined with other answers.
OtherNotSelected Answer '{ANSWER}' The 'Other' response box has text filled
({CATEGORY}) has a response in, but the Other response has not
but is not selected. been selected.
InvalidText Answer '{ANSWER}' is not valid. A text response is not in the format
specified in the question; for example,
not a valid telephone number.
TooLittleText The answer does not have The number of characters in a text
enough text, current length is response is less than the minimum
'{LENGTH}', minimum is specified in the question.
'{MINLENGTH}'.
TooMuchText The answer has too much text, The number of characters in a text
current length is '{LENGTH}', response is greater that the maximum
maximum is '{MAXLENGTH}'. specified in the question.
PlayerNavigationDisabled You have used the browser The respondent used the browser's
buttons, please use the navigation buttons when the project
Next/Previous buttons below. does not allow this.

The above table is listed in the DDL at this link:


DDL.chm::/interviewscripting_errors_standard.htm

You can change the messages associated with the errors in 3 ways:

Globally for all mrInterview projects


For all questions within a metadata file
For a specific question

174
Survey Programming Fundamentals Chapter 16 Customizing the Standard Error Messages

Global changes to error messages


To change the wording of error messages globally for all projects, they are contained in the
StandardTexts.mdd file on the mrInterview server. Please note that this file holds the translations for
the error messages as well. If you produce multilingual studies, you will need to translate the new
messages to any additional languages necessary.

Error messages changes for a specific metadata file


To replace the error message text for the whole script, include a StandardTexts block with an Errors
block in the metadata as shown below.

StandardTexts block fields


(
Errors block fields
(
MessageName1 "Text 1" info;
MessageNamen "Textn" info;
...
);
);

Item Description
MessageName1, Name of the standard message as shown in the table previously.
MessageNamen
Text1, Textn Represents the replacement message text

The following example will change the default error message Missing Answer(s) for all questions
within this survey.

Metadata(enUS, Question, Label)


Example StandardTexts "StandardTexts" block fields
(
Errors "Errors" block fields
(
Missinganswer "Please answer the question."
info;

);

);

End Metadata

175
Chapter 16 Customizing the Standard Error Messages Survey Program

If a respondent did not choose an answer for any question within the survey, they would see:

Error messages changes for a specific question


Changing the error message for a specific question is very similar to the method for every question
within the survey. The difference is that the StandardText block must be added to a helper field
attached to the question:

Metadata(enUS, Question, Label)

QuestionName "text" questiontype


helperfields (
StandardTexts "StandardTexts" block fields
(
Errors "Errors" block fields
(
MessageName1 "Text 1" info;
MessageNamen "Text n" info;
...
);
);
);

Item Description
helperfields Keyword used to store additional information for a field/question
MessageName1, Name of the standard error message.
MessageNamen
Text1, Textn Represents the replacement message text

176
Survey Programming Fundamentals Chapter 16 Customizing the Standard Error Messages

Customizing the error message


You can customize the wording of the message by using some of the substitution markers listed in the
table below. Enclose the markers in curly brackets when inserting into the error text.

Substitution Marker Description


ANSWER The respondent's answer.
RANGE The valid answer range for the question as defined in the metadata section.
QUESTION The question name.
QUESTION_NUMBER The question number.
LENGTH The length of the response text.
MINLENGTH The minimum length for a text response.
MAXLENGTH The maximum length for a text response.
MINANSWERS The minimum number of answers that must be chosen from a multiple choice
list.
MAXANSWERS The maximum number of answers that may be chosen from a multiple choice
list.
CATEGORY The text of a single multiple choice response.
ERROR The error message associated with an internal error.

This example will make the respondents error message clearer in its meaning.

DaysTravelYr "On average how many days per year do you travel for business or leisure?"
Example long [0 .. 365]
helperfields (
StandardTexts "StandardTexts" block fields
(
Errors "Errors" block fields
(
NotInRange "{ANSWER} is more than the number of days in a year. Please try
again."
info;
);
);
);

177
Chapter 16 Customizing the Standard Error Messages Survey Program

When the respondents answer is out of the range, it will display a new error message:

178
Survey Programming Fundamentals Chapter 17 Functions & Subroutines

Chapter 17 Functions & Subroutines


With Dimensions Scripting (and other programming languages), you can create reuseable code that
will help you to do certain actions, such as validate question logic or specific formatting issues.

In this chapter we
w will:
n
Define Functions and ubroutines

w to write Functions and


Learn how
Subroutines in Dimensions
o Scripting

p of Functions and Subroutines


See examples u
in Dimensions Scripting

Definition of Functions and Subroutines


A function or subroutine is a section of code within a script which performs a specific task and is
relatively independent of the remaining script. These are terms that are common to other
programming languages, not specific to Dimensions Scripting.

There are several advantages to using functions or subroutines, including:

Reducing the duplication of code in a program


Enabling reuse of code across multiple scripts
Decomposing complex problems into simpler pieces (this makes them easier to maintain and
add/subtract functionality as needed)
Improved readability of a program

The parts of a function or subroutine may include:

A body of code to be executed when the subroutine is called


Parameters that are passed to the subroutine from the point where it is called
A value that is returned to the point where the call occurs (function only)

Lets look at some very basic examples to understand the concept of functions and subroutines.

179
Chapter 17 Functions & Subroutines Survey Programming Fundamentals

Subroutine
To define a subroutine:

Sub Name(var1, var2, varN)

Statements

End Sub

To call (use) a subroutine:

Name(parameter1, parameter2, parameterN)

Item Description
Sub Marks the start and end of a subroutine
End Sub
Name Represents a unique name given to the subroutine
Statements Represents any statements to be executed within the subroutine
var1, var2, varN Represents the name of variables that are passed to the subroutine from the
point where it is called. The variables together are called the argument list.
parameter1, Represents the actual parameters that are passed to the subroutine. The
parameter2, order of these parameters will match up with the variables on the subroutine
parameter3 (example: parameter1 is the information that will be inserted in the
subroutine represented as var1)

Subroutine Example
Depending on the specific look of your surveys, you may want to control the column widths of a grid at
a default level for all grids, or have individual control. If you need individual control, it would be nice to
have a way to indicate the specifics per grid on a single line in the script. We can create a subroutine
to help us with this.

Suppose you had two grids in your study that after the default styles were applied, they looked like
this:

180
Survey Programming Fundamentals Chapter 17 Functions & Subroutines

Looking at the grids, they might look better with some specific styles applied to them. As we learned in
the style section, you could specify the style for each grid (AirlineRating and InterestinLocation) in the
routing section:

Routing(Web) AirlineRating.Categories[..].Label.Style.Cell.Width =
Example "300px" AirlineRating[0].Item[0].Categories[..].Label.Style.Cell.Width
= "70px" AirlineRating[0].Item[0].Categories[..].Label.Style.Cell.Wrap
= true AirlineRating.Ask()

InterestinLocation.Categories[..].Label.Style.Cell.Width = "120px"
InterestinLocation[0].Item[0].Categories[..].Label.Style.Cell.Width = "90px"
InterestinLocation[0].Item[0].Categories[..].Label.Style.Cell.Wrap = true
InterestinLocation.Ask()
End Routing

181
Chapter 17 Functions & Subroutines Survey Programming Fundamentals

The previous code would produce the following look:

Now we might say that this code could be useful in many studies. As you can see, we are repeating the
same basic text each time, just changing the values of the style properties and the question it applies
to. This repetitiveness makes it a candidate for a subroutine.

First, create the subroutines structure and give it a name that is easily recognizable:

Sub GridStyle1()

End Sub

182
Survey Programming Fundamentals Chapter 17 Functions & Subroutines

Then, ask yourself what will change each time about the lines of code; the question name and the
values of the styles will change each time, so they need to be replaced with a variable to represent
those items:

Sub GridStyle1 (QuestionName, ColHeadWid, ColWid, ColWrap)

End Sub

QuestionName, ColHeadWid, ColWid, and ColWrap are similar to temporary variables, so


the names can be anything you like.

Next, add the code. Beginners may find it helpful to add the code for one question without the
substitutions then make the changes to that code with the parameters.

Sub GridStyle1 (QuestionName, ColHeadWid, ColWid, ColWrap)

AirlineRating.Categories[..].Label.Style.Cell.Width = "300px"
AirlineRating[0].Item[0].Categories[..].Label.Style.Cell.Width = "70px"
AirlineRating[0].Item[0].Categories[..].Label.Style.Cell.Wrap = true

End Sub

Looking at the above example we will need to change AirlineRating, 300px, 70px, and true to
match the variable names we defined on the first line of the subroutine:

Sub GridStyle1 (QuestionName, ColHeadWid, ColWid, ColWrap)

QuestionName.Categories[..].Label.Style.Cell.Width = ColHeadWid
QuestionName [0].Item[0].Categories[..].Label.Style.Cell.Width = ColWid
QuestionName [0].Item[0].Categories[..].Label.Style.Cell.Wrap = ColWrap

End Sub

183
Chapter 17 Functions & Subroutines Survey Programming Fundamentals

The above subroutine alone does nothing. You need to Call the subroutine and specify the parameter
information for a specific action. Here is the completed subroutine example:

Routing(Web)
Example GridStyle1(AirlineRating,"300px" , "70px" ,true)
AirlineRating.Ask()

GridStyle1(InterestinLocation, "120px" , "90px" ,true)


InterestinLocation.Ask()

Sub GridStyle1 (QuestionName, ColHeadWid, ColWid, ColWrap)


QuestionName.Categories[..].Label.Style.Cell.Width = ColHeadWid
QuestionName [0].Item[0].Categories[..].Label.Style.Cell.Width = ColWid
QuestionName [0].Item[0].Categories[..].Label.Style.Cell.Wrap = ColWrap

End Sub

End Routing

Function
As stated earlier in this chapter, a function differs from a subroutine in that it can pass a value back to
where the call originated. In the syntax below, you will see it is very similar to the subroutine, but now
you may set a value equal to the function name to pass back and use within your script.

Function Name(var1, var2, varN)

Statements

Name = value

End Function

To call (use) a function:

Name(parameter1, parameter2, parameterN)

184
Survey Programming Fundamentals Chapter 17 Functions & Subroutines

Item Description
Function Marks the start and end of a function
End Function
Name Represents a unique name given to the function
Statements Represents any statements to be executed within the function
var1, var2, varN Represents the name of variables that are passed to the function from the
point where it is called. The variables together are called the argument list.
Value A value that is returned to the point where the function call occurred
(Optional)
parameter1, Represents the actual parameters that are passed to the function. The order
parameter2, of these parameters will match up with the variables on the function
parameter3 (example: parameter1 is the information that will be inserted in the function
represented as var1)

185
Chapter 17 Functions & Subroutines Survey Programming Fundamentals

Suppose we had a shared list of travel agencies that had 30 categories:

Metadata(enUS, Question, Label)


Example Agencylst "" define
{
Agency1 "Travel Agency 1",
Agency2 "Travel Agency 2",
Agency3 "Travel Agency 3",
Agency4 "Travel Agency 4",

Agency30 "Travel Agency 30"
};

AgencyHeardOf "Which of the following travel agencies have you heard of?"
categorical
{
use AgencyLst
};

'Create a filter for AgencyUse to be the responses of AgencyHeardOf


AgencyUse "Of those you were aware of, which travel agencies would you consider using
to book your travel?"
categorical
{
use AgencyLst
};
End Metadata

Routing(Web)
agencyheardof.Style.Columns=3
agencyheardof.Ask()

agencyuse.Categories.Filter=agencyheardof
agencyuse.Ask()

End Routing

And you wanted to force the style of the number of columns for the AgencyUse question to have no
more than 10 categories in each column. Since the categories of the question AgencyUse are
dependent on the response to AgencyHeardOf, we will need to find out the number of categories
chosen in AgencyHeardof, and divide by 10 to see how many columns we need using the AnswerCount
Dimensions Function we learned in

186
Survey Programming Fundamentals Chapter 17 Functions & Subroutines

Basic Routing Logic, page 60. Since dividing our number of responses by 10 may not result in a whole
number, we will also use a builtin function, int(), which returns the integer portion of a number.

Routing(Web)
Example agencyheardof.Style.Columns=3
agencyheardof.Ask()
agencyuse.Categories.Filter=agencyheardof

Dim Actual, IntegerValue, DecimalValue


Actual = CDouble(AgencyHeardof.AnswerCount())/10
IntegerValue = int(AgencyHeardof.AnswerCount()/10)
DecimalValue = Actual IntegerValue

If DecimalValue > 0 Then


agencyuse.Style.Columns = IntegerValue + 1
Else
agencyuse.Style.Columns = IntegerValue
End If
AgencyUse.Ask()

End Routing

Since this may be an action we would want to do on other questions or in other studies, it might be
advantageous to create a function instead. The function below does just that. It was created in a
similar way to the subroutine.

Routing(Web)
Example agencyheardof.Style.Columns=3
agencyheardof.Ask()
agencyuse.Categories.Filter=agencyheardof
agencyuse.Style.Columns=ForceCols(agencyheardof)
agencyuse.Ask()

Function ForceCols(filterQ)
Dim Actual, IntegerValue, DecimalValue
Actual = CDouble(filterQ.AnswerCount())/10
IntegerValue = int(filterQ.AnswerCount()/10)
DecimalValue = Actual IntegerValue

If DecimalValue > 0 then


ForceCols = IntegerValue + 1
Else
ForceCols = IntegerValue
End If
End Function
End Routing

187
Chapter 17 Functions & Subroutines Survey Programming Fundamentals

You can see that the function is set up very much the same as the subroutine, in that it has a name
(ForceCols) and has a parameter (filterQ). The difference is that after the function is completed, it is
set to a value. The values can be anything.

Exercise
Open the reusable.mdd file. Make the following routing section code more reuseable with the
concepts learned in this chapter. It would be helpful to have a piece of reusable code that would
allow you to easily specify the number of response columns, column width, and question text color for
specific questions.

Routing(Web)

PrimaryTravel.Style.columns = 3

PrimaryTravel.Style.Width = 300

PrimaryTravel.Label.Style.Color= "#0000FF"

PrimaryTravel.Ask()

CountryVisited.Style.Columns=2

CountryVisited.Style.Width = 600

CountryVisited.Label.Style.Color= "#00FF00"

CountryVisited.Ask()

End Routing

188
Survey Programming Fundamentals Chapter 18 Validation

Chapter 18 Validation
In the last chapter we discussed the concepts of subroutines and functions. Dimensions scripting has a
unique function that allows you to easily validate logic in questions. We will also look at additional
concepts that will help us validate the logic of the survey.

In this chapter we
w will:
Validate a text question to follow a pattern
t

n how to add errors for custom


Understand t
logic

Create custom
s logic withh the use of
Dimensions
n validation functions

Validating Text Question Patterns


You can include statements within the metadata that will check a text field to see if it matches a
specific pattern. Regular Expressions allow you to do create very complicated match algorithms with a
small amount of code.

Name "Text" text

Validation(" expression");

Item Desc iption


Name Metadata item name
"Text" Text associated with the item
text Question
t type. Must be text t o add a regular
a expression
Validation Property keyword to allow you to add a regular expression
expression
o Regular Expressionn syntax

189
Chapter 18 Validation Survey Programming Fundamentals

Test your expressions thoroughly, as there are many variations to regular expressions, too numerous
to place in this manual. Here are a few to help you understand the examples below.

Symbol Description
\w Matches any word character (az, AZ, 09)
\W Matches any nonword character.
\d Matches any decimal digit. Equivalent to \p{Nd} for Unicode and *09+ for nonUnicode,
ECMAScript behavior.
\D Matches any nondigit. Equivalent to \P{Nd} for Unicode and *^09] for nonUnicode,
ECMAScript behavior.

The DDL does reference regular expressions: DDL.chm::/aliasmap_regularexpressions.htm


however, there are also many references on the web as well, such as:
http://en.wikipedia.org/wiki/Regular_expressions and
http://regexlib.com/cheatsheet.aspx .

The following example will check the length of the phone number and also if it follows the specific
pattern with 2 dashes.

Example
Phone "Please enter your 10digit phone number with dashes:"
text [7..20]
validation("\d,3-\d{3}\d{4}");

The regular expression above shows you want 3 decimal digits (numbers) a dash, 3 more numbers a
dash and 4 numbers.

190
Survey Programming Fundamentals Chapter 18 Validation

The next example is more flexible, allowing you to check an email address to ensure it contains an @
sign.

Email "Email:"
Example text [5..100]
helperfields (
StandardTexts "" block fields
(
Errors "" block fields
(
InvalidText "You must enter a valid email address with an @ and period. "
info;
);
);
) validation("[.\w]+\@[.\w+**.\w]+\.*.\w]*");

This expression ensures the respondent answered a dash, period or any word character (az), then a
mandatory @ sign, followed by a dash, period or any word character.

191
Chapter 18 Validation Survey Programming Fundamentals

Checking Custom Logic


There are many times you will need to do logic checks within your survey that are not covered by the
standard error messages. The most efficient way to achieve this is through custom validation. The
concept is a special type of function that is tied directly to a question.

Function functionname(Question, IOM, Attempt)

Statements

functionname = True

Statements

functionname = False

End Function

Item Description
Function Defines the start and end of the function
End Function
functionname Represents the unique name given to the function
Question Parameter that represents the question you are attaching to the function (this
will always be Question)
IOM Parameter for the Interview Object Model (This will always be IOM)
Attempt Parameter for the number of current custom validation attempts (This will
always be Attempt, if used, but it is an optional parameter). Could be used to
set the number of times the function should attempt to receive a True value.
Statements Represents the Dimensions scripting statements to do any action and return a
value, such as check logic
True Values that the Dimensions custom validation function must pass back. These
False special functions must set the functionname to true or false

192
Survey Programming Fundamentals Chapter 18 Validation

To set the validation function to use for a question, use the following statement in the routing section
somewhere prior to asking the question:

Routing(Web)

Name.Validation.Function = functionname

Name.Ask()

End Routing

Item Description
Name Name of the question you wish to validate
Validation.Function Properties to set the validation function for the question.
functionname Represents the unique name given to the function

There are a few things to note about creating custom validation functions:

To reference another metadata item (besides the question you are validating) inside the
function, you need to reference the question with IOM.Questions.QuestionName.
The function must return either a True (logic is correct, move on to the next question) or False
value (logic is not correct, issue an error message if the number of attempts has not been met).
They can only have the parameters Question, IOM, and Attempt. If you want to include more
variable information into the function, one way to achieve this is to add custom properties in
the metadata of the question you wish to validate. (More to come on this subject.)

Adding custom errors


In the next examples, we will be creating customized logic that may require you to have the respondent
reanswer the question. To do that action, you need to add your own error message. You can create
errors that have the same properties as the standard error messages. In the routing section you would
add:

Name.Errors.AddNew("errorname", errortext.label)

Item Description
Name Name of the question you want to apply an error message to
Errors.AddNew States you want to add a new error to the standard set of error messages
errorname Represents the unique name given to the error message
errortext Represents the info item created to hold the text for the error message. You can
just add text in double quotes in the routing section for this, but it is highly
recommended to make the info item.
label Will show the label of the info item as the error message text

193
Chapter 18 Validation Survey Programming Fundamentals

You define the error message you want to use as an info item in the metadata section. This
is important for multilingual projects because it makes the message text available for
translation.

The example below is a categorical grid that displays a column of numeric boxes to enter information
that should add to 100%.

Metadata(enUS, Question, Label)


Example Activities define
{
Train "On a train/train station",
Airplane "In an airplane/airport",
Vehicle "In a Vehicle driving or riding",
Subway "Subway System",
Walk "Walking",
OtherMode "Other"
};

PercActivity "Thinking of your travel over the last year, what percentage of your time
was spent using the following modes of transportation? The total should add to 100%."
loop
{
use Activities
} fields
(
QPercent "Percentage"
style(
Width = "30px"
)
long [0 .. 100]
initialanswer(0 );

) expand grid;

ErrorGridAddto100 "Please check your responses. Responses should add up to 100."


info;

End Metadata

194
Survey Programming Fundamentals Chapter 18 Validation

In the routing section, we will create the special Dimensions validation function to make sure our grid
adds to 100% as shown below.

Routing(Web)
Example IOM.LayoutTemplate = "Card_Blue_TopAndBottomErrors.htm"

PercActivity.Validation.Function = "ValidateGrid100"
PercActivity.Ask()

Function ValidateGrid100(Question, IOM,Attempt)


Dim category
Dim total

If attempt <= 3 Then

For Each category in Question


total = total + category.Item[0].Response.Value
Next

If total <> 100 Then

Question.Errors.AddNew("ErrorGrid",
IOM.Questions.ErrorGridAddto100.Label)

ValidateGrid100 = False

Else

ValidateGrid100 = True

End If

End If
End Function

End Routing

195
Chapter 18 Validation Survey Programming Fundamentals

Lets change the scenario slightly. What if you wanted to modify the question, so that the question
prior to this was:

Thinking of your travel over the last year, approximately how many hours did you spend using some
type of transportation?

This will involve modifying our previous example to be able to reference that questions response
within the function.

Metadata(enUS, Question, Label)


Example
HrsTravelMode "Thinking of your travel over the last year, approximately how many
hours did you spend using some type of transportation?"
long [0..8760];

HrsActivity "Thinking of your travel over the last year, how many hours of your time was
spent using the following modes of transportation? The total should add to
{#HrsTravelMode}." loop
{
use Activities
} fields
(
QHours "Hours"
style(
Width = "30px"
)
long [0 .. ]
initialanswer(0 );

) expand grid;

ErrorGridAddtohrs "Please check your responses. Responses should add up to


{#HrsTravelMode}."
info;

End Metadata

196
Survey Programming Fundamentals Chapter 18 Validation

Again, the routing section is where the validation happens. Notice the reference to the additional
question with the IOM.Questions preceding it.

Routing(Web)
Example
IOM.LayoutTemplate = "Card_Blue_TopAndBottomErrors.htm"

HrsTravelMode.Ask()

HrsActivity.Validation.Function = "ValidateGridEqualDependentQ"
HrsActivity.Ask()

Function ValidateGridEqualDependentQ (Question, IOM,Attempt)


Dim category
Dim total

If attempt <= 3 Then

For Each category in Question


total = total + category.Item[0].Response.Value
Next

If total <> IOM.Questions.HrsTravelMode Then

Question.Errors.AddNew("ErrorGrid", IOM.Questions.
ErrorGridAddtohrs.Label)

ValidateGridEqualDependentQ = False

Else

ValidateGridEqualDependentQ = True

End If

End if

End Function

End Routing

197
Chapter 18 Validation Survey Programming Fundamentals

The above works nicely, however it is very specific to the question. The line:

If total <> IOM.Questions.HrsTravelMode Then

Would have to be changed every time it is used for a different question, which is not a good practice.

As stated above, one of the biggest differences between standard functions and custom validation
functions is that currently you cannot add any additional parameters. This limits the flexibility of
custom validation functions. One way that you could pass parameters into a function to make it more
reusable is by placing custom properties in the metadata.

Adding custom properties to metadata


Custom properties can be any additional information attached to a metadata item. One basic way to
add custom properties is in the metadata section:

Name "text" [property] type

Item Description
Name Name of the question in the metadata section
"text" Text of the question
[property] Represents any information you want stored in the metadata associated with the
metadata item
type Represents the metadata item type (categorical, long, etc.). Notice the custom
properties are prior to this.

Custom properties are an advanced concept, but an important one to remember as you progress with
your Dimensions Scripting learning. Lets add a custom property to our previous example so that we
do not have to make our function so specific to these sets of questions. Below in bold you will notice
the addition of custom properties that adds the name of the question we want to use in the function
to compare to the sum of our grid.

198
Survey Programming Fundamentals Chapter 18 Validation

Metadata(enUS, Question, Label)


Example
HrsTravelMode "Thinking of your travel over the last year, approximately how many
hours did you spend using some type of transportation? "
long [0..8760];

HrsActivity "Thinking of your travel over the last year, how many hours of your time was
spent using the following modes of transportation? The total should add to
{#HrsTravelMode}."
[ dependentQ = "HrsTravelMode" ]
loop
{
use Activities
} fields
(
QHours "Hours"
style(
Width = "30px"
)
long [0 .. ]
initialanswer(0 );

) expand grid;

ErrorGridAddtohrs "Please check your responses. Responses should add up to


{#HrsTravelMode}."
info;

End Metadata

199
Chapter 18 Validation Survey Programming Fundamentals

In the routing you will see the change to the comparison line. Notice the addition of the comments to
identify what is needed for the function.

Routing(Web)
Example
IOM.LayoutTemplate = "Card_Blue_TopAndBottomErrors.htm"

HrsTravelMode.Ask()

HrsActivity.Validation.Function = "ValidateGridEqualDependentQ"
HrsActivity.Ask()

Function ValidateGridEqualDependentQ (Question, IOM,Attempt)


Dim category
Dim total

If attempt <= 3 Then

For Each category in Question


total = total + category.Item[0].Response
Next

If total <> IOM.Questions[Question.Properties["dependentQ"]] Then

Question.Errors.AddNew("ErrorGrid", IOM.Questions.
ErrorGridAddtohrs.Label)

ValidateGridEqualDependentQ = False

Else

ValidateGridEqualDependentQ = True

End If

End if

End Function

End Routing

Now this function can be reused in different projects. You can see how a library of custom validations
will speed the programming process over time.

200
Survey Programming Fundamentals Chapter 19 Compound Questions

Chapter 19 Compound Questions


The compound type helps you to achieve a special look to your questionnaire when you wish to display
multiple questions on the same screen horizontally. These questions must have the common
denominator of a shared list of categories. This is traditionally used in paperbased surveys, but can
also be done for webbased studies.

This chapter covers:


o
The definittion of a compound
p questionn

Validating compound questions


u

Differences
e between loops
o and compound
o
questions

Defining Compound Questions


In essence, a compound is simply multiple questions (including grids) which all share a common list of
categories. Think of a compound question as a container for other questions you wish to display on
the same page horizontally. The syntax for a compound is as follows:

CompoundName "Text" compound

{ Categories } fields

Question1;

QuestionN;

);

Item Description
CompoundName
n Unique
n name for the compoundo metadata item
"Text" Optional Text to display across the top of the screen of the compound question
compoundn Keyword
e to cr eate a compound metadata item
categories Represents the categories for which the questions and loops are to be asked.
Y u may use a shared list here if you wish.
fields h the compound item
Precedes the questions within
Question1, Categorical questions and categorical loops that you want to display side by side.
QuestionN

201
Chapter 19 Compound Questions Survey Programming Fundamentals

Suppose we want to create the following look for our survey:

You will notice in the above example that all the questions on the page share a list of airlines. The next
example will show how this can be created as a compound question.

202
Survey Programming Fundamentals Chapter 19 Compound Questions

Metadata(enUS, Question, Label)


Example Airlines "" define
{
United,
Delta ,
BritishAirways "British Airways" ,
Luftansa "Luftansa"
};

AirlineQ "Please answer the following questions about the airlines listed." compound
{
use Airlines
} fields
(
FlownBefore "Flown Previously"
Categorical [1..];
Trips6MoLoop "# of Trips Past 6 Months" loop fields
(
trips ""
long [0 .. 400];

) expand grid;
SatisLoop "Overall, how satisfied are you with each Airline?" loop fields
(
RateAirline "RateAirline"
categorical [1..1]
{
VerySatisfied "Very Satisfied",
SomewhatSat "Somewhat Satisfied",
SomewhatDisSat "Somewhat Dissatisfied",
VeryDissatisfied "Very Dissatisfied"
};

) expand grid;
);
End Metadata

Routing(Web)

AirlineQ.Ask()

End Routing

203
Chapter 19 Compound Questions Survey Programming Fundamentals

The questions inside of the compound are missing items you might expect to see. For example the
FlownBefore question has no responses, and the two loops have no iteration elements. This is
because all the questions inside of a compound will make reference to the shared categories from the
first section of the compound.

The compound can be created without omitting these elements, but for the sake of
efficiency you will want to use the method shown above.

Validating a compound question


Validating compound questions can prove challenging for beginner programmers. However, with the
skills taught in the previous sections of validations, you are on your way to validating complex
compound questions as well. Here is a simplified version of the example above. This example only
includes the questions FlownBefore and Trips6Mo_Loop.

Metadata(enUS, Question, Label)


Example Airlines define
{
United,
Delta,
BritishAirways "British Airways ,
Luftansa
};

AirlineQ "Please answer the following questions about the airlines listed." compound
{ use Airlines
} fields
(
FlownBefore "Flown Previously"
Categorical [1..];
Trips6MoLoop "# of Trips Past 6 Months" loop fields
(
trips ""
long [0 .. 400]
codes(
{
NoAnswer " " NA
} );
) expand grid;
);

CompoundError "Missing answers, please try again."


info;
End Metadata

204
Survey Programming Fundamentals Chapter 19 Compound Questions

The logic you will need to check for will be:

If FlownBefore is chosen, then Trips6MoLoop must be answered


If FlownBefore is not chosen, then Trips6MoLoop must be null

The following validation function creates those logic checks. By referencing the questions inside the
compound by their position (0 = FlownBefore, 1 = Trips6MoLoop), it makes the Function more reusable
for other similar scenarios.

Routing(Web)
Example IOM.LayoutTemplate= "Card_Blue_TopandBottomErrors.htm"

AirlineQ.MustAnswer=False
AirlineQ.Validation.Function="ValidateSimpleCompound"
AirlineQ.Ask()

Function ValidateSimpleCompound(Question,IOM,Attempt)
ValidateSimpleCompound = True
Dim Cat
For Each Cat In Question.Categories

If (Question.Item[0].ContainsAny(Cat) And Question.Item[1].Item[Cat].Item[0] = Null ) _


Or (NOT (Question.item[0].ContainsAny(Cat)) And _
Question.Item[1].Item[Cat].Item[0] Is Not Null) Then
ValidateSimpleCompound = False
End If
Next

If ValidateSimpleCompound = False Then


Question.Errors.AddNew("CompoundError",IOM.Questions.CompoundError.Label)
End If

End Function

End Routing

205
Chapter 19 Compound Questions Survey Programming Fundamentals

Compound vs. Loop


You may have noticed similarities between compound questions and loops that have multiple different
types of questions. There are a few main differences between compounds and loops to be aware of:

You cannot drop the similar category lists from the questions in a loop as you can with a
compound
Validation of a compound question is very different that for a grid

206
Survey Programming Fundamentals Chapter 20 Working with Sample

Chapter 20 Working with Sample


mrInterview allows you to access information you have about your potential respondents and use this
to enhance the survey experience and/or data. One scenarios for using the additional information
would be to customize the interview screens based on who is currently taking the interview.

In this chapter we
w will:
n
Retrieve information from the sample table
into the Dimensions Script

Send information
r from the Dimensionss
script to the sample table

Use a test sample record


d locally in mrStudio
S
to check your Dimensions
n script

Using sample management allows you the option to bring additional information about the
respondents for use during the interview either by:

Displaying information held in the table to the respondent (Hello, Bob. Thank you for
participating.)
Creating a question to hold the sample information so it is easily analyzed with the
respondents answers.

To reference information stored in the sample table about the current respondent:

IOM.SampleRecord.Item[" sampleField "]

Item Description
SampleField
i Re presents the name
n of the field in the SQL
Q database that holds th einformation
yo u wish to retrieve.

207
Chapter 20 Working with Sample Survey Programming Fundamentals

Here is an example of pulling information from a sample record into the text of a question. We are
assuming the projects sample table has a field named TAgency that holds the Travel Agencies used
by the people in the sample.

Metadata(enUS, Question, Label)


Example
VerifyTravelAgent "Our records indicate you have used the travel agency {Agency} in the
past, is this correct?"
categorical
{
Yes,
No
};

End Metadata

Routing(Web)
VerifyTravelAgent.Label.Inserts["Agency"].Text=IOM.SampleRecord.Item["TAgency"]
VerifyTravelAgent.Ask()
End Routing

If a specific respondents travel agency was Travel Agency XYZ, then their question will appear as
shown below:

208
Survey Programming Fundamentals Chapter 20 Working with Sample

The next example does not display the respondents information, but rather stores it in a question for
analysis purposes.

Metadata(enUS, Question, Label)


Example
Region "Stores the region where they live."
text;

End Metadata
Routing(Web)

Region.Response.Value = IOM.SampleRecord.Item["SRegion"]

End Routing

You can also put information collected or derived in the script into a sample field.

Metadata(enUS, Question, Label)


Example
ReceiveTravelInfo "Check here if you wish to receive an email regarding travel safety."
boolean;

End Metadata

Routing(Web)
ReceiveTravelInfo.Ask()
IOM.SampleRecord.Item["WantsEmail"] = ReceiveTravelInfo.Response.Value
End Routing

The above example will store a True or False in the sample field, providing you have a sample field
called WantsEmail.

Testing sample information within mrStudio


You can easily test to see if you are correctly pulling your sample information into the script. mrStudio
allows you to create a test sample record. To do this:

Access the file:

C:\Program Files\SPSS Dimensions\mrStudio\4.0.0.0\Interview\DefaultSample.xsu.

209
Chapter 20 Working with Sample Survey Programming Fundamentals

This is an XML document which mrStudio reads as a sample record by default. The default file is shown
below:

210
Survey Programming Fundamentals Chapter 20 Working with Sample

Item Description
<SampleRecord ID=ID1> Marks the beginning and end of the samplerecord. Can only create
</SampleRecord> a single record for testing within mrStudio.
<Samplefields> Marks the beginning and end of the sample fields for the record.
</SampleFields>
<SampleField> Marks the beginning and end of a sample field.
</SampleField>
<name> Tags to surround the name of the sample field
</name>
<type> Tags to surround the type of field. SQL field types are used. Smallint
</type> = 2; Int = 3; Datetime = 7; Char, Text, Ntext, or NVarchar = 8; Bit = 11
<value> Tags to surround the value you want the sample field to have.
</value>

You have the ability to create your own files and add additional Sample fields as shown below:

211
Chapter 20 Working with Sample Survey Programming Fundamentals

In order to access the sample information, make sure that under

Tools Options Sample Management Record

you are referencing the correct .xsu file.

The example below will assume you are using the modified TravelSample.xsu with the additional field
for region.

Metadata(enUS, Question, Label)


Example
Region "Stores the region where they live." text;

VerifyTravelAgent "Our records indicate you have used the travel agency {Agency} in the
past, is this correct?"
categorical
{
Yes,
No
};

End Metadata

Routing(Web)

Region.Response.Value = IOM.SampleRecord.Item["SRegion"]
VerifyTravelAgent.Label.Inserts["Agency"].Text=IOM.SampleRecord.Item["TAgency"]
VerifyTravelAgent.Ask()

End Routing
As you can see in the screenshot above, you can easily check your references to sample fields within
the text of your survey (Such as Agency XYZ), but when you are accessing the locals pane, you can also
see that the region has been correctly added to the question, Region.

212
Survey Programming Fundamentals Chapter 20 Working with Sample

Alternative to Sample Management to pass information into the survey


If you are not using sample management, you can send out separate URL links to respondents that
speak different languages. Then embed a parameter in the URL that will be passed into the script to
set the language. mrInterview can pass parameters on the URL using the names I.User1 through
I.User9. Then you can do the same things with these parameters that we did with sample
management variables.

URL to send out:


Example http://www.servername.com/scripts/mrIWeb.dll?I.Project=myproj&I.User1=DEU

In the script:
Routing(Web)
IOM.Language = IOM.Info.User1
End Routing
The above example would set the language to German (DEU) for the interview.

213
Chapter 20 Working with Sample Survey Programming Fundamentals

214
Survey Programming Fundamentals Chapter 21 Working with Quotas

Chapter 21 Working with Quotas


Quotas are a system for controlling the number of respondents interviewed matching predefined
criteria. For example, we may be asked to interview 1000 respondents with the requirements that 500
are male and 500 are female.

In
n this chapter will cover:
An overview
e of the quota process

How to heck and respond to quotas in


n the
c ecction
routing
s

Checking and
a changing quotas
q online

Defining Survey Quotas


To setup a quota we need three items:

The question the quota will be based on scripted in your metadata section.
The targets for the quota.
The type of quota

Lets look at a simple example of making a quota based on the respondents gender.

Targets
Male 500
Gender
Female 500

In our metadata section we should have a question for gender:

Metadata(enUS, Question, Label)


Example Gender "Are you..."
categorical [1..1]
{
Male ,
Female
};
End Metadata

215
Chapter 21 Working with Quotas Survey Programming Fundamentals

Once you have saved the metadata file, you can create your quota targets by selecting Tools Quotas
or choosing the quota button from the Interview Options toolbar:

You will see the quota tool as shown in the picture below.

On the left of the screen you will see a list of the questions in the survey. Drag and drop the Gender
question onto the quota matrix.

216
Survey Programming Fundamentals Chapter 21 Working with Quotas

We can now see the two gender categories with a grey box to the right of each:

Next, doubleclick on one of the grey boxes to set the targets:

217
Chapter 21 Working with Quotas Survey Programming Fundamentals

Here we can set the target and quota type for the cell.

Type Description
Normal A normal quota will report quota full when the quota count of the completed and
pending interviews is equal to the target.
Allow Over Allow over will report quota full when the quota count of completes is equal to the
target. Note, this does not include the pending and as such you potentially can go over
quota.
Counter A counter quota is really not a quota at all. The system will not stop respondents from
completing interviews once the limit is reached. This type of quota is used for
information purposes only.

Once you have set the target and type for each quota cell we need to name the quota matrix. Well call
this example QuotaGender.

Now Save. This will create a file type with a .mqd extension.

Checking Quotas
Now that we have quota limits defined, we need to add logic to our routing section that tells the
section to check on the quota. Before we do that, lets add an extra item to our metadata. We are
creating a scenario where respondents will be turned away from the survey based on their responses.
Lets add a message to use for informing the respondent what has happened.

Metadata(enUS, Question, Label)


Example Gender "Are you..."
categorical [1..1]
{
Male ,
Female
};

OverQuota "I'm sorry, the quota is full." info;

End Metadata

In the routing section, we will start by defining a temporary variable to hold our quota check and ask
our quota question.

218
Survey Programming Fundamentals Chapter 21 Working with Quotas

Routing(Web)
Example
Dim Quota_Pend_Result

Gender.Ask()

End Routing

You must make sure that you always check a quota after the respondent has answered.

Next add the quota check:

Routing(Web)
Example
Dim Quota_Pend_Result

Gender.Ask()

Quota_Pend_Result = QuotaEngine.QuotaGroups["QuotaGender"].Pend()

End Routing

As you can see you must reference the name you gave the quota matrix. In this way you can create
multiple quota matrixes and check them at different points of the survey. The temporary variable
Quota_Pend_Result stores the results of the attempted quota pend. Now we need to check those
results and respond accordingly.

219
Chapter 21 Working with Quotas Survey Programming Fundamentals

Routing(Web)
Example
Dim Quota_Pend_Result

Gender.Ask()

Quota_Pend_Result = QuotaEngine.QuotaGroups["QuotaGender"].Pend()

If Not(IsSet(Quota_Pend_Result, QuotaResultConstants.qrWasPended)) Then

IOM.Texts.InterviewStopped = OverQuota.Label

IOM.Terminate(Signals.sigOverQuota)

End If

End Routing

The If statement is checking to see if the Pend() attempt resulted in the success of one or more quota
cells. If this was not the case, then the respondent has failed the quota check. We will set the
InterviewStopped text to the message we defined in an info item in our metadata section. Then we
terminate the interview, flagging the respondent as over quota.

220
Survey Programming Fundamentals Chapter 21 Working with Quotas

Quotas In mrStudio
If you try running this in mrStudio now, you will get an error message by default. One choice is to skip
over the code when running inside of mrStudio by adding a check for when the script is in Debug
mode.

Routing(Web)
Example
Dim Quota_Pend_Result

Gender.Ask()

If Not IOM.Info.IsDebug Then

Quota_Pend_Result = QuotaEngine.QuotaGroups["QuotaGender"].Pend()

If Not (IsSet(Quota_Pend_Result, QuotaResultConstants.qrWasPended)) Then

IOM.Texts.InterviewStopped = OverQuota.Label

IOM.Terminate(Signals.sigOverQuota)

End If

End If

End Routing

IOM.Info.IsDebug will be True whenever the survey is running inside mrStudio.

mrStudio v.4.5 and above does have the capability to simulate quotas. Note you must
have either Microsoft SQL Server 2000 or 2005, including the free SQL Server 2005 Express
Edition and Microsoft SQL Server Desktop Engine (MSDE) to use this feature. See the DDL
for more detail: DDL.chm::/mrstudio_testing_quotas.htm

221
Chapter 21 Working with Quotas Survey Programming Fundamentals

Activation with Quotas


Now that the quotas are created, you need upload the .mqd file and activate the study with special
options for quotas. You can do this directly from mrStudio using Tools Activate, or through
DimensionNet.

For instructions on Activating quotas within DimensionNet, see the DDL:


DDL.chm::/quota_dimnet.htm

Viewing & Changing Quotas


You can view and change quota information online using the DimensionNet Quotas activity.

Each quota matrix in your survey will be a button on the left hand side of the activity page:

222
Survey Programming Fundamentals Chapter 21 Working with Quotas

Selecting a quota group will display the current quota counts:

You also may see a dropdown list that allows you to change additional quota information.

Type Description
Do Not Edit View only mode.
Targets Allows you to modify the targets for each quota cell.
All Allows you to modify the target, complete, pending and type for each quota cell.

223
Chapter 21 Working with Quotas Survey Programming Fundamentals

When the Targets option is selected textboxes will appear. You can raise or lower the cell targets. Once
you have entered the new correct targets click the Update button.

224
Survey Programming Fundamentals Chapter 21 Working with Quotas

When the All selection is chosen you can edit the targets, complete count, pending count as well as
change between Normal, OverQuota and Counter quota types.

225
Chapter 21 Working with Quotas Survey Programming Fundamentals

226
Survey Programming Fundamentals Chapter 22 Creating MultiLingual Projects

Chapter 22 Creating Multi-Lingual Projects


When implementing studies in different languages, Dimensions allows you to create a survey in a base
language, and then easily add languages to the metadata file. The chapter will review the process of
multilingual studies, focusing on the specific tasks for the survey programmer.

In this
t chapter we will cover:
An overview e
e of how to execute e in
a survey
multiple languages
a

Setting thee language ithin the script


w

Tips for reeating multilingual projects

Overview of Translating Studies in Dimensions


When a project will be run in multiple languages, the basic steps are:

Create the survey .mdd file in a base language.


Use mrTranslate to add translations to the metadata file.
Upload and activate the revised .mdd file to the project.
Be sure that the ErrorMessage.mdd file has the error messages translated for the languages
you will have in your project.

Once you have a metadata file, you can add the translations through the product, mrTranslate.
mrTranslate reads the metadata file and presents the text of your survey in a format similar to a
spreadsheet. Then you can add additional languages as columns in mrTranslate .

For detailed information on using mrTranslate, see the Users Guide in the DDL:
mrTranslate.chm::/mrtranslate overview.htm

227
Chapter 22 Creating MultiLingual Projects Survey Programming Fundamentals

Then save the metadata file and now it will contain the additional languages. Note that when you re
open the metadata file in mrStudio, you will not see the additional languages within the text of the file,
but they are in the metadata file. To verify additional languages are in the metadata using mrStudio:

Choose the Metadata Explorer


Open the Languages

Setting the language within the script


To use the multilingual functionality within mrInterview, you need to set the IOM.Language. You
could accomplish this in many ways. Here are a few common methods:

Create a question in which the respondent chooses the language.


Have the language stored in a sample field and retrieve the information and set the language
for the respondent.

Ask a question to collect and set the language


When you do not know the preferred language of your respondent, a simple introductory question can
be asked to collect the language.

228
Survey Programming Fundamentals Chapter 22 Creating MultiLingual Projects

Metadata(enUS, Question, Label)


Example LanguageQ "Choose the language for this survey:"
categorical [1..1]
{
ENU "English",
DEU "German",
ESN "Spanish"
};

End Metadata

Routing(Web)
LanguageQ.Ask()
IOM.Language = LanguageQ.Categories.[LanguageQ].Name
End Routing

Note that in the example above, the names of the responses (ENU, DEU, ESN) must be the 3digit
Microsoft language codes.

If the script has the translations added, you will be able to see the languages changes within mrStudio
as you run the survey.

To find a full list of the language codes, see the DDL: UserGuide.chm::/Intug
mrscriptmetadata_languages_3char.htm

Set language from a sample field variable


If you already know the preferred language and you are using sample management, a field can be set
in the sample table to hold the 3digit language code. The following example assumes your sample
table has a field called SLanguage.

Routing(Web)
Example
IOM.Language = IOM.SampleRecord.Item["SLanguage"]

End Routing

229
Chapter 22 Creating MultiLingual Projects Survey Programming Fundamentals

Tips for creating multi-lingual projects


Creating the scripts for multilingual studies does not need to be difficult as long as you follow a few
simple rules:

If the templates contain text that needs to be translated, use localized templates for each
language so that the proper text is shown.
Verify the ErrorMessage.mdd file has the error messages for the languages you will be using.
Always reference info items in the routing section for any text, such as custom error messages
or text inserts. Text in the routing section is not seen by mrTranslate, only the metadata
section.

230
Survey Programming Fundamentals Chapter 23 Additional information for Analysis

Chapter 23 Additional information for Analysis


This section shows how the Dimensions scripting language is not only for creating interviews, but also
for analysis purposes. This section adds options to your interview script that will speed the analysis
process by adding common statistics and summary information, such as top box scores and alternate
text for analysis.

In this
t chapter we will
w cover:
Adding a lternate text forr reporting purposes
r

Adding speecial statistics into the interview


v
script

Creating faactor scores for


o use with statistics
t

Alternate Text for Analysis


Many organizations will alter the text of the questions that were asked in a survey for reporting or
analysis purposes. The most common method is to change from question formats to statements
(Example: What is your gender? becomes Respondent Gender). The alternate text is called an
Analysis context. You can add this information in a few different ways. Two common ways are
mrTranslate and mrStudio to view and add analysis context. Using mrTranslate will allow individuals
who are unfamiliar with Dimensions scripting to add the alternate text, as mrTranslate masks the
actual code with its interface. Since this is a scripting course, we will focus on adding analysis context
with mrStudio.

Adding Analysis Context with mrStudio


Open the View menu
Select Contexts
Choose Analysis

231
Chapter 23 Additional information for Analysis Survey Programming Fundamentals

You will now see a blank spot by all text in the metadata labeled ANALYSIS:. You can place the
alternate text in double quotes as shown in the picture below:

Factors
If you wish to add statistical elements, such as a mean or standard deviation, to your categorical
questions, then you need to add a multiplier to each response choice. Even if you do not add the
statistical elements, factors can also be helpful to end users of the data creating cross tabulations with
mrTables or mrStudio.

Name "Text" categorical [min..max]

{ID1 "AltText1" factor(value),

IDn "AltTextn" factor(value) };

Text Description
factor Keyword to identify you wish to add a multiplier to the response for statistical purposes
value Represents the numeric value you wish to assign to the response for statistics.

232
Survey Programming Fundamentals Chapter 23 Additional information for Analysis

This example shows you how to specify values for each age range for statistics in use with other
Dimensions products, such as mrTables, Desktop Reporter, or mrStudio with tables scripting.

Metadata(enUS, Question, Label)


Example
Age "To which of the following age categories do you belong?"
categorical [1..1]
{
Under18 "Under 18" factor(18),
_18to34 "18 to 34" factor(26),
_35to54 "35 to 54" factor(45),
_55plus "55 and over" factor(55),
Refused "Prefer not to Answer" REF
};
End Metadata

Creating Question Items for Analysis


You can also add analysis elements to the questions to speed the availability of topline and final
results. We will discuss two different methods for adding elements for Analysis, ElementTypes and
Axis Expressions.

ElementTypes are not seen during interviewing only in analysis, such as using mrTables or
creating cross tabulations with mrStudio. They are a single line of information, such as a
summary item or mean score.
Axis expressions are also not seen during interviewing, but are usually more than a single line
of analysis results. An example would be adding a predetermined range of categories to a long
or double type question for analysis purposes.

233
Chapter 23 Additional information for Analysis Survey Programming Fundamentals

ElementTypes
You use the optional elementtype keyword to create a special element in metadata for use in analysis.

Name "Text" type

{ID1 "AltText1,

IDn "AltTextn",

IDElement "AltTextElement" elementtype (typevalue)

};

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
Type Identifies the question type (categorical, long, etc.)
ID1, IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.
IDElement Unique identifying name for the special element. Rules for this name are the
same as the name of the question.
AltTextElement Text to represent the special element
elementtype Keyword that indicates you will be specifying using a special element
typevalue Represents the keywords listed in the next table to state the type of special
element you need

Below is a table with a few common analysis elements, represented by type_value in the syntax
example above.

Text Description
AnalysisCategory An element that is used only for analysis. You can use this value for categories
that you do not want to appear in interviews. An example would be creating a
TopBox or BottomBox score.
AnalysisMean An analysis element that is used to show the mean value of a variable.
AnalysisStdDev An analysis element that is used to show the standard deviation of a variable.
AnalysisStdErr An analysis element that is used to show the standard error of a variable.

234
Survey Programming Fundamentals Chapter 23 Additional information for Analysis

To find a full list of Analysis Elements, see the DDL:


DDL.chm::/mrscriptmetadata_categorical.htm

To use the types listed, most require additional properties. Here is the previous example where the
mean value has been added to the age question. Notice the additional parameters required for a
mean with categories.

Metadata(enUS, Question, Label)


Example Age "To which of the following age categories do you belong?"
Categorical [1..1]
{
Under18 "Under 18" factor(18),
_18to34 "18 to 34" factor(26),
_35to54 "35 to 54" factor(45),
_55plus "55 and over" factor(55),
Refused "Prefer not to Answer" REF,
Mean "Mean Score" [
CalculationType = "Mean",
HasNoData = true,
ExcludedFromSummaries = true
]
elementtype(AnalysisMean)
};
End Metadata

Another helpful element type is the AnalysisCategory. This allows you to create additional elements in
questions that are not seen during the interview, only in analysis. The following define list will provide
you with a Top and Bottom Box Score for each question using the list in the analysis.

Metadata(enUS, Question, Label)


Example Rating5Pt define
{ Top2 "Positive Scores" elementtype(AnalysisCategory) expression("@ * {VS, SS}"),
VS "Very Satisfied",
SS "Somewhat Satisfied" ,
Neutral ,
Bot2 "Negative Scores" elementtype(AnalysisCategory) expression("@ * {SDS, VDS}"),
SDS "Somewhat Dissatisfied" ,
VDS "Very Dissatisfied"
};
End Metadata

235
Chapter 23 Additional information for Analysis Survey Programming Fundamentals

In the previous example the @ represents any question the define is used with. If you wish
to use a combining element directly in a question without a define list, the expression
would be "qname * {VS, SS}"

Axis Expressions
Another way to speed tabulation processes would be to create analysis items called axis expressions.
These can create many different types of analysis items, a common one in interview scripts would be
categorical ranges on numeric questions.

The axis expressions are dynamically created statements attached to the metadata questions. The
syntax is very similar to what you would do in a data management script.

Name "Text" type

{ID1 "AltText1,

IDn "AltTextn"}

axis ("axis_spec");

Item Description
Name Unique identifier for the item within your questionnaire. They must start with a
letter or underscore ( _ ) and contain only alphanumeric characters or the
symbols @, $, #, or _
"Text" Text associated with the item (considered the label in the object model).
Type Identifies the question type (categorical, long, etc.)
ID1, IDn Unique identifying name for the response. This needs to be unique per
question, not metadata file. Rules for the response names are the same as the
name of the question.
AltText1, Optional text to show the respondent instead of the name of the question. This
AltTextn will apply when the name of the question is not the same as the text you wish to
show the respondent.
axis Keyword to represent elements will be added that will only be seen in analysis
axis_spec Represents many different syntax that creates elements to be seen in analysis

236
Survey Programming Fundamentals Chapter 23 Additional information for Analysis

The following example will collect a long question type during the interview, but easily allow people
doing analysis to view the preset ranges of answers and a mean value.

Metadata(enUS, Question, Label)


Example
HouseHold "Including yourself, how many people currently live in your household?"
long [1 .. 20]
axis("{ _1 'One' expression('Household = 1'),
_2to3 '23' expression('Household >=2 and Household <=3'),
_4to6 '46' expression('Household >=4 and Household <=6'),
_7plus '7 and over' expression('Household >=7'),
mean 'Mean' mean(household)}");

End Metadata

Tips creating analysis elements


Adding analysis elements can prove beneficial for speeding the time for analysis setup. A few things to
remember:

These items can be added after live data collection, so dont worry if you dont have all the
analysis information up front.
The metadata syntax check will only be looking for syntax mistakes, not if your logic actually
works. Make sure to create test data and have someone check the analysis fields for accuracy.

Summary
This chapter has just introduced the analysis concepts and by no means has shown all the possibilities.
As your knowledge of Dimensions scripting grows, you will see how all parts of Dimensions scripting
(interviewing, data management and tabulation) are connected. That knowledge will allow you to use
the power of Dimensions Scripting to its fullest potential and do some amazing projects. You are now
on the verge of doing great things with this powerful language. Remember to think out of the box and
try new ways to do things, as this language has so many facets and capabilities.

237
Chapter 23 Additional information for Analysis Survey Programming Fundamentals

238

You might also like