Vous êtes sur la page 1sur 248

d

SurveyProgramming

Fundamentals

SurveyProgrammingFundamentals
Copyright2007byVergeConsulting,Inc.
Allrightsreserved.Nopartofthisworkmaybereproducedortransmittedinanyformormyany
means,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageor
retrievalsystem,withoutpriorwrittenpermissionofVergeConsulting.
Trademarkednamesmayappearinthisbook.Ratherthanuseatrademarksymbolwithevery
occurrenceofatrademarkname,weusethenamesonlyinaneditorialfashionandtothebenefitof
thetrademarkowner,withnointentionofinfringementofthetrademark.
ForadditionalinformationpleasecontactVergeConsultingdirectlyat4146SherelLane,Cincinnati,OH
45209.Phone5132823762,fax8668229333orvisithttp://www.VergeConsulting.com.
Theinformationinthisbookisdistributedonanasisbasis,withoutwarranty.Althoughevery
precautionhasbeentakeninthepreparationofthiswork,neithertheauthor(s)norVergeConsulting
shallhaveanyliabilitytoanypersonorentitywithrespecttoanylossordamagecausedorallegedto
becauseddirectlyorindirectlybytheinformationcontainedinthiswork.

Version:

SPF12(Dimensions4.5)

SurveyProgrammingFundamentals

TableofContents

TableofContents
Chapter1 IntroductiontoSurveyProgramming.....................................................................................1
TheBigPicture........................................................................................................................................1
WhatisSurveyDesignAbout?............................................................................................................2
TheSurveyProcess.................................................................................................................................2
DimensionsScriptingOverview..............................................................................................................2
InterviewObjectModel..........................................................................................................................2
ObjectOrientedProgramming...............................................................................................................3
WhatisObjectOrientedProgramming?............................................................................................3
DimensionsDevelopmentLibraryOverview..........................................................................................3
NavigatingtheDDL.............................................................................................................................4
Examples.............................................................................................................................................4
DDLLinks.............................................................................................................................................5
WhatismrStudio?..................................................................................................................................6
WhatsNext?...........................................................................................................................................7
Chapter2 ConstructingQuestions...........................................................................................................9
MetadataItemsFormat..........................................................................................................................9
InformationItems.................................................................................................................................10
NumericQuestions...............................................................................................................................11
MinimumandMaximumParameterOptions...................................................................................12
TextQuestions......................................................................................................................................12
Categorical............................................................................................................................................14
ParameterOptionsRestrictingtheNumberofResponsestobeChosen......................................14
Date.......................................................................................................................................................17
Boolean.................................................................................................................................................19
Chapter3 CreatinganmrStudioInterviewScript..................................................................................21
OpeningmrStudio.................................................................................................................................21
OverviewofToolbars/Shortcuts...........................................................................................................23
FormattingToolbars.........................................................................................................................23
ViewToolbar.....................................................................................................................................24
InterviewOptionsToolbar................................................................................................................25

TableofContents

SurveyProgrammingFundamentals

TipsforCreatingMetadata...................................................................................................................25
ViewingandTestingtheSurveyinmrStudio........................................................................................26
Exercise.................................................................................................................................................28
Chapter4 SpecialResponsesandOptions............................................................................................31
SingleResponseChoicesinMultipleSelectionQuestions...................................................................31
SpecialResponseswithCategoricalQuestions.....................................................................................34
CategoricalResponseswithNonCategoricalQuestions......................................................................36
CollectingOtherTextResponsesinCategoricalQuestions..................................................................38
Subheading...........................................................................................................................................39
Exercise.................................................................................................................................................42
Chapter5 BasicRoutingLogic................................................................................................................45
AskingQuestions...................................................................................................................................47
ReadOnlyItems....................................................................................................................................49
ConditionalStatements........................................................................................................................50
IfThenElse..................................................................................................................................50
SelectCase............................................................................................................................................52
Goto......................................................................................................................................................55
LogicalExpressions...............................................................................................................................56
NumericQuestions...........................................................................................................................56
BooleanQuestions............................................................................................................................57
TextQuestions..................................................................................................................................57
CategoricalQuestions.......................................................................................................................58
LogicalOperators..............................................................................................................................60
TipsforRoutingSectionSyntax............................................................................................................62
AddingErrorHandling...........................................................................................................................63
Exercise.................................................................................................................................................64
Chapter6 SharedLists...........................................................................................................................67
CreatingSubheadingswithSharedLists...............................................................................................69
Chapter7 SortingCategoricalResponseLists.......................................................................................73
SortinginMetadata..............................................................................................................................74
RoutingSectionSorting........................................................................................................................75
NotSortingSpecificResponses.............................................................................................................75
II

SurveyProgrammingFundamentals

TableofContents

KeepingSpecificCategoriesGroupedTogether...................................................................................77
Exercise.................................................................................................................................................78
Chapter8 RestrictingResponses...........................................................................................................79
FilterCategories....................................................................................................................................79
LimitingNumericQuestionRangesBasedonLogic..............................................................................86
Exercise.................................................................................................................................................88
Chapter9 MultipleQuestionsonOnePage..........................................................................................91
Page.......................................................................................................................................................92
Block......................................................................................................................................................94
ControllingHowPageandBlockQuestionsareDisplayed...................................................................98
FilteringaPage/Block.......................................................................................................................98
SortingaPage/Block.........................................................................................................................99
Exercise...............................................................................................................................................100
Chapter10

RepetitiveQuestionsLoops&Grids.............................................................................101

CategoricalLoops/Grids......................................................................................................................102
ForEachloops.................................................................................................................................106
CategoricalLoopswithaNumericQuestion..................................................................................108
NumericLoops....................................................................................................................................111
Exercise...............................................................................................................................................114
Chapter11

DebuggingToolswithinmrStudio...................................................................................115

AutoAnswerQuestionnaire...............................................................................................................115
ProducingTestData............................................................................................................................117
AddingAdditionalDataSources.....................................................................................................119
SettingBreakpoints.............................................................................................................................120
TroubleshootingSpecificSectionsofCode.........................................................................................121
WorkingwithMacros..........................................................................................................................123
Updating/DeletingExistingMacros................................................................................................123
AddingAdditionalMacros..............................................................................................................123
Chapter12

ConditionedLoopsandGrids..........................................................................................125

PreviousResponsesWithintheLoop.................................................................................................125
Loops/GridsFilteredonPreviousResponsesOutsidetheLoop/Grid................................................127
Loops/GridsFilteredonResponsestoaDifferentLoop/GridsQuestions.........................................129

III

TableofContents

SurveyProgrammingFundamentals

Loops/GridsFilteredonaSublistofCategories..................................................................................131
Exercise...............................................................................................................................................134
Chapter13

ControllingtheLookofYourSurvey...............................................................................137

OverviewoftheFormattingofaSurvey.............................................................................................137
Templates...........................................................................................................................................137
ApplyingaTemplatewithinYourScript.........................................................................................139
Folders............................................................................................................................................140
TipsforScriptwritersRegardingTemplates....................................................................................141
Styles...................................................................................................................................................141
DefaultStyles......................................................................................................................................141
Default............................................................................................................................................142
Categories.......................................................................................................................................143
Grid.................................................................................................................................................144
Labels..............................................................................................................................................146
Navigation.......................................................................................................................................146
Questions........................................................................................................................................147
QuestionStyles...................................................................................................................................148
CategoricalQuestions.....................................................................................................................148
TextQuestions................................................................................................................................149
MetadataStyles..................................................................................................................................150
CustomControls.................................................................................................................................151
XHTMLinLabels..................................................................................................................................151
WhatisXHTML?..............................................................................................................................151
FinalThoughtsonFormatting.............................................................................................................152
Exercise...............................................................................................................................................153
Chapter14

TextSubstitutionsandTextHeadings.............................................................................155

DisplayingResponsestoPreviousQuestions.....................................................................................155
InsertTextintotheMetadatathatwillbecontrolledintheroutingsection.....................................158
TextHeadings......................................................................................................................................162
Chapter15

EnhancingSurveyFlow...................................................................................................165

MustAnswer.......................................................................................................................................166
DefaultAnswers..................................................................................................................................166
IV

SurveyProgrammingFundamentals

TableofContents

Hiddendefaultresponses...............................................................................................................169
InitialResponse...................................................................................................................................170
Exercise...............................................................................................................................................172
Chapter16

CustomizingtheStandardErrorMessages.....................................................................173

Globalchangestoerrormessages......................................................................................................175
Errormessageschangesforaspecificmetadatafile..........................................................................175
Errormessageschangesforaspecificquestion.................................................................................176
Customizingtheerrormessage..........................................................................................................177
Chapter17

Functions&Subroutines.................................................................................................179

DefinitionofFunctionsandSubroutines............................................................................................179
Subroutine......................................................................................................................................180
SubroutineExample............................................................................................................................180
Function..........................................................................................................................................184
Exercise...............................................................................................................................................188
Chapter18

Validation........................................................................................................................189

ValidatingTextQuestionPatterns......................................................................................................189
CheckingCustomLogic.......................................................................................................................192
Addingcustomerrors.........................................................................................................................193
Addingcustompropertiestometadata.........................................................................................198
Chapter19

CompoundQuestions.....................................................................................................201

DefiningCompoundQuestions...........................................................................................................201
Validatingacompoundquestion........................................................................................................204
Compoundvs.Loop............................................................................................................................206
Chapter20

WorkingwithSample......................................................................................................207

TestingsampleinformationwithinmrStudio.....................................................................................209
AlternativetoSampleManagementtopassinformationintothesurvey.........................................213
Chapter21

WorkingwithQuotas......................................................................................................215

DefiningSurveyQuotas......................................................................................................................215
CheckingQuotas.................................................................................................................................218
QuotasInmrStudio.........................................................................................................................221
ActivationwithQuotas.......................................................................................................................222
Viewing&ChangingQuotas...............................................................................................................222

TableofContents
Chapter22

SurveyProgrammingFundamentals

CreatingMultiLingualProjects.......................................................................................227

OverviewofTranslatingStudiesinDimensions..................................................................................227
Settingthelanguagewithinthescript................................................................................................228
Askaquestiontocollectandsetthelanguage..................................................................................228
Setlanguagefromasamplefieldvariable..........................................................................................229
Tipsforcreatingmultilingualprojects...............................................................................................230
Chapter23

AdditionalinformationforAnalysis................................................................................231

AlternateTextforAnalysis..................................................................................................................231
AddingAnalysisContextwithmrStudio.........................................................................................231
Factors.................................................................................................................................................232
CreatingQuestionItemsforAnalysis..................................................................................................233
ElementTypes..................................................................................................................................234
AxisExpressions..............................................................................................................................236
Tipscreatinganalysiselements..........................................................................................................239
Summary.............................................................................................................................................239

VI

SurveyPrrogrammingFundamentalls

Chapte
er1

Chapter1Introd
ductiontoSurrveyProgram
mming

Inttroductio
ontoSurv
veyProgra
amming

ThiscourrseisdesignedtoprovideafirmfoundaationinunderstandingtheeDimensionsScripting
languagee,specificallythetaskofprrogrammingssurveys.

Thischap
T
pterwillcontain::
Anovervieewoftheinterviewprocess

Adefinitio
onofDimensionsscripting
Anintrodu
uctiontodocum
mentationand
d
mrStudio

TheBig
gPicture
Theoverallprocessoffrunningasu
urveycanbeggroupedintothreemaincategories.

Design:Creattingthesurveeyinstrumenttandthequeestionsassociatedwithit
D
C
Collect:Colle
ecttheinform
mationrequireedofthesurvveyinstrumen
nt
R
Report:Analy
yzetheresulttsandreportthefindingso
oftheresearch

Foreachstagethereaaredifferentttoolswecanuse.ForDimeensionsthisccouldlooklikee

C
Collect
t
mrStudio
BuildA
Activity
mrPap
per
Author
mrTranslate

mrInterview
mrD
Dialer
mrSScan

Design

SSPSS
R
Reporter
m
mrTables
m
mrStudio
C
Clementine

Report

Chapter1IntroductiontoSurveyProgramming

SurveyProgrammingFundamentals

WhatisSurveyDesignAbout?
Herearesomeofthetasksinvolvedinsurveydesign:

Creatingaqualitysurveyinstrument
Programmingsurveycontentandlogic
Surveytesting(Qualitycontrol)
Transferringtheprojecttodatacollectionservers(Activation)
Surveytranslation
Sampleintegration
Definingquotas

TheSurveyProcess
Thehistoricprocessforthesurveyprocesshasattimesbeentedious.Therearealotofrepetitive
tasksthattaketimeandmoney.Dimensionsischangingthatparadigm.Dimensionsscriptingallows
userstoincorporatemoreautomationandreusablecodeintheprocess.Dimensionsscriptingisone
unifiedlanguageforsurveydesign,collectionandreporting,sothereislessrepetitionandamore
streamlinedprocess.

DimensionsScriptingOverview
WhenworkinginmrStudiowewillbeusingDimensionsScripting.Therearetwolanguagesin
Dimensionsscripting.
Language
mrScriptBasic

Description
AprogramminglanguagethatisbasedonMicrosoftVBScript.

mrScriptMetadata

ProprietaryDimensionssyntaxusedtodefinesurveyquestions/
metadata.

Whenprogrammingsurveyswewillmakeuseofbothlanguages.mrScriptMetadatawillbeusedto
createthequestionforoursurvey.mrScriptBasicwillcontrolwhenandifweaskthosequestions.

InterviewObjectModel
TheInterviewObjectModel,typicallyreferredtoasIOM,isthefoundationofsurveyprogrammingin
Dimensions.IOMdefines,forDimensions,whatthecomponentsofasurveyareandwhatactionswe
cantakewitheachcomponent.

SurveyProgrammingFundamentals

Chapter1IntroductiontoSurveyProgramming

ObjectOrientedProgramming
WhenprogrammingasurveyinDimensionsyouwillbeusingobjectorientedprogramming(OOP).
WhatisObjectOrientedProgramming?
Abasicdefinitionwouldreadsomethinglike:Atypeofprogramminginwhichprogrammersdefinenot
justthedatatypeofadatastructure,butalsothetypesofoperations(functions)thatcanbeapplied
tothedatastructure.Inthiswaythedatastructurebecomesanobjectthatincludesbothdataand
functionality.
IfyouhavenotbeenexposedtoOOPinthepast,theconceptsandterminologycanseemconfusingat
times.However,don'tgetcaughtupintheterminology.Ifyouunderstandtheconceptofcreatinga
questionnaire,thenyoucanlearnthecontentofthismanual.
ThinkaboutOOPintermsofasurvey.Specifically,let'slookatasurveyquestionasanobject.A
questionhasquestiontext,potentialresponses,aswellasmanyotherpossibleitems.Theseareinfact
thedatastructure,whatcanmakeuppartofaquestion.Atthesametimeaquestionwillrequire
functionality,suchasaskingthequestionorfilteringtheresponses.Thesepotentialactionswould
makeuptheoperationsthatcanbeappliedtothedatastructure.Ifthismakessensetoyou,thenyou
areonyourwaytograspingtheconceptsofOOP.(Ifitdoesnt,thisconceptwillmakemoresenseas
youcontinueyourlearning.)

DimensionsDevelopmentLibraryOverview
CommonlyreferredtoastheDDL,theDimensionsDevelopmentLibraryisacollectionofresources.It
consistsofextensivetechnicaldocumentationaswellasawidevarietyofexamplecode.

Chapter1IntroductiontoSurveyProgramming

SurveyProgrammingFundamentals

YoucanaccesstheDDLthroughtheHelpContentsmenuchoiceinmrStudio,orthrough:
StartProgramsSPSSDimensionsDimensionsDevelopmentLibraryDocumentation4.5

NavigatingtheDDL
TherearemanydifferentwaystonavigatearoundtheDDL.
Tab
Contents

Index
Search
Favorites

Description
AlltheDDLtopicsarrangedinatableofcontents.Youcanusethisviewlikelooking
throughabook.Itisalsohelpfulforidentifyingtopicsrelatedtoapageyouare
currentlyreading.
TheindexisanalphabeticallistofkeywordcontainedintheDDL.Usethisview
whenyouknowthekeywordandwanttoquicklyfindtopicsrelatedtoit.
AfulltextsearchoftheDDL.Youcansearchonasingleword,combinationof
wordsandphrases.
Createalistoftopicsyouhavefoundvaluable.

AlltheDimensionsproductdocumentationiscontainedintheDDL,sofindingspecifictopics
isaskillinitselfandwilltaketimetodevelop.

Forthiscourse,agoodplacetostartisintheContentstab:
mrStudioInterviewScriptingGettingStarted

Examples
WhenyouinstalledtheDDLyoualsoinstalledmanyexamplesfiles.Thedefaultpathforthese
examplesis:
C:\ProgramFiles\SPSSDimensions\DDL\

Specificallyforsurveyprogrammingyoushouldbeawareof:
C:\ProgramFiles\SPSSDimensions\DDL\Scripts\Interview

Theseexampleprojectswillproveveryvaluabletogiveyounewideasforprogramming.

SurveyProgrammingFundamentals

Chapter1IntroductiontoSurveyProgramming

DDLLinks
ThroughoutthesematerialsyouwillseelinkspointingyoutotheDDLforadditionalinformationona
topic.Thesearejumplinksandwilllooklike:

FormoreinformationontheInterviewobjectmodel,seetheDDLdiagram:
IOMLib.chm::/interview_Object_Model.html

Tousealink,rightclickonthetitlebarintheDDL:

SelecttheJumptoURLmenuitem.

Chapter1IntroductiontoSurveyProgramming

SurveyProgrammingFundamentals

Enter(orcopyandpaste)thelinkintotheJumptothisURL:textbox.ThenclickOK.

Thiswilltakeyoutothepagerequested.Youcanalsodothereverse,andcopythecurrentURLshown
aboveandsharewithothers.

WhatismrStudio?
mrStudioisadesktopprogramthatassistsprogrammerswithcreatingscripts.Itscorecomponentisan
integrateddevelopmentenvironment(IDE)thatallowsyoutocreate,edit,runanddebugDimensions
scripts.
Forsurveyprogrammers,oneofthebigstrengthsistheabilitytorunsurveysdirectlyinsidemrStudio,
withouttheneedforaserver.Youcancreate,testanddebugasurveydirectlyonyourmachine.

SurveyProgrammingFundamentals

Chapter1IntroductiontoSurveyProgramming

SinceyouwillbeusingmrStudiothroughoutthiscourse,letsstartwithabriefoverviewofthe
toolbars:
Toolbar

Description
File:Usedtocreate,open,saveandprintfiles.

Edit:Cut,copy,paste,undoandredo,find.

View:Controlswhichtabsareshowingin
mrStudio.
Debug:Usedtostart,stop,pauseandmove
throughascript.
Formatting:Indentations,commenting,
macrosandoptions.
Workspace:Createandmanageworkspaces.

InterviewOptions:routingcontextoptions,
activation,quotas,andmetadatatools.

YouwillgettoseemanyfeaturesofmrStudioasyoumovethroughthistraining.

WhatsNext?
SonowyouhavebeenintroducedtoDimensionsScripting,objectorientedprogramming,the
DimensionsDevelopmentLibrary,andmrStudio.ThismanualwillfocusonusingmrStudiotocreate
surveysfordatacollectionwithmrInterview.Wewillstartwithbasicquestionsandquicklymoveinto
advancedconceptstohelpyoucreatemorecomplexsurveys.

Chapter1IntroductiontoSurveyProgramming

SurveyProgrammingFundamentals

SurveyPrrogrammingFundamentalls

Chapte
er2

Chaapter2ConsttructingQuesstions

Constructin
ngQuestio
ons

Thecoreofasurveyissthequestion
ns.Inthischapter,wewillbuildourkn
nowledgeofccreatingquestions
withinmrStudio.

Inthischapterw
wewill:
Createbaasicquestionss
Createam
metadatafileeinmrStudio
ViewandtestasurveyywithinmrStudio

Metada
ataItemsF
Format
Metadataaitemsfollow
wadistinctpaatternyouwiillseeasweccompletethisschapter:
N
Name"Text"
typeparame
eters;
Item
Name

"Text"
Type
Parameters
Semicolo
on

Desscription
Uniiqueidentifierfortheitem
mwithinyourquestionnairre.Theymuststartwitha
lettterorundersccore(_)andcontainonlyyalphanumericcharacterssorthe
sym
mbols@,$,#,,or_
Texxtassociatedw
withtheitem
m(consideredthelabelinttheobjectmo
odel).
Identifiestheiteemforitsfuncctionality(cattegoricalquestions,texto
onlyitems,
etc.)
The
eseareoption
nalandvaryb
byitemtype.Anexamplewouldbetheeresponses
toaaquestion.
Bettweeneachiteminthemeetadatasectio
onthereisassemicolon.

ermanyofth
hedifferenttyypesofquesttions.
Thenextsectionscove

Chapter2
2Constructin
ngQuestions

SurveeyProgramm
mingFundameentals

Inform
mationItem
ms
Tocreateeanopeningpagewithanintroduction
norhaveapaagewithgraphicsoropeningtextwitho
out
questions,youneedtocreateanin
nformationitem.Thesynttaxisasfollow
ws:

N
Name"Text"
info;
Item
Name

Desscription
Uniiqueidentifierfortheitem
mwithinyourquestionnairre.Theymuststartwitha
lettterorundersccore(_)andcontainonlyyalphanumericcharacterssorthe
sym
mbols@,$,#,,or_
Texxtassociatedw
withtheitem
m(consideredthelabelinttheobjectmo
odel).
Keyywordtocreaateatextonlyyitem.Thisisthedefaulttypeifitisno
otspecified.
Bettweeneachiteminthemeetadatasectio
onthereisassemicolon.

"Text"
info
Semicolo
on

Example

Intro""Pleaseparticcipateinourrresearchabou
uttravel.You
uranswersw
willhelpustobetter
undersstandthetravvelneedsofcconsumers."
info;

Theintro
oductionwilld
displayinmrIInterviewlikeethis:

10

SurveyProgrammingFundamentals

Chapter2ConstructingQuestions

NumericQuestions
Tocollectnumericdatafromyourrespondents,useoneofthefollowingitemtypes:
Name"Text"long[min..max];
Name"Text"double[min..max];

Item
Name

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_.
Textassociatedwiththeitem(consideredthelabelintheobjectmodel).
Wholenumbersonly(nodecimals).Therangeisfrom2,147,483,648to
2,147,483,647.
Decimalnumbers.64bitfloatingpointnumberwithatleast15digitsof
precision,intherange1.79769313486232E308to4.94065645841247E324for
negativevalues;4.94065645841247E324to1.79769313486232E308for
positive.
Optionalparameters.Controlstheminimumandmaximumvaluesthe
respondentcanenter.Automaticallyissuesanerrormessageiftheamount
enteredisbelowtheminimumorabovethemaximum.

"Text"
long
double

[Min..Max]

Thefollowingexamplewilldisplayboxesfortherespondenttofillinwithanumericresponse.
DaysTravelYr"Onaveragehowmanydaysperyeardoyoutravelforbusinessorleisure?"
Example

long[0..365];

AmtSpentAccom"Whatpricedidyoupayforyourlastovernightaccommodations?"
double[0..3999.99];

11

Chapter2ConstructingQuestions

SurveyProgrammingFundamentals

Thebrowserwilldisplayaboxandtherespondentcanfillinamountsoftheirchoice,asshownbelow:

MinimumandMaximumParameterOptions
Whenspecifyingtheminimumandmaximumsfornumericquestions,[min..max],youhavemany
optionstocollectthenumericdatanecessary.
Item
[1..]
[..]
[1..100,^50]
[1,3,5]
[1..10,50..100]

Description
Minimumamountwithoutspecifyingamaximum
Nominimumsormaximums(willallownegativenumbers)
Numberafter^symbolareexcludedfromtherange.
Commasdenotesinglevaluesorbreakingranges.

TextQuestions
Whenyouwanttocreateaquestionthatcollectsanytypeoftextinformation,useatexttype.
Name"Text"text[min..max];
Item
Name

"Text"
text
[Min..Max]

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
Textassociatedwiththeitem(consideredthelabelintheobjectmodel).
Keywordtoenteranycharactersinthequestion.Allowsupto4000characters.
Optionalparameters.Controlstheminimumandmaximumcharactersallowed
forthequestion.

Hereisasimpleexampleofanopenendedquestion.

12

SurveyProgrammingFundamentals

Chapter2ConstructingQuestions

BestVacation"Pleasetellusaboutyourbestvacationexperience."
Example

text[1..];

Willdisplaylikethepicturebelow:

Ifyoustatethemaximumat40orless,youwillseealineinsteadofabox.Youalso
havefullcontroloftheboxsizewithstyles,coveredintheControllingtheLookofYour
Surveysection.

13

Chapter2ConstructingQuestions

SurveyProgrammingFundamentals

Categorical
Tocreateaquestionwhichoffersalistofoptionstochoosefromisconsideredacategoricaltype
question.
Name"Text"categorical[min..max]
{ID1"AltText1",
IDn"AltTextn"};
Item
Name

"Text"
categorical
[Min..Max]

{}
ID1,IDn

AltText1,
AltTextn

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
Textassociatedwiththeitem(consideredthelabelintheobjectmodel).
Keywordtocreateaquestionwithcategoriesforresponsechoices.
Optionalparameters.Controlstheminimumandmaximumamountof
categoriesthatcanbechosenbyarespondent.Defaultisopentoanyamount
ofchoices.Automaticallyissuesanerrormessageifthenumberofresponses
chosenisbelowtheminimumorabovethemaximum.
Indicatesthestartofthecategoriesyouwishtherespondenttochoosefromfor
thequestion
Uniqueidentifyingnamefortheresponse.Thisneedstobeuniqueper
question,notmetadatafile.Rulesfortheresponsenamesarethesameasthe
nameofthequestion.
Optionaltexttoshowtherespondentinsteadofthenameofthequestion.This
willapplywhenthenameofthequestionisnotthesameasthetextyouwishto
showtherespondent.

ParameterOptionsRestrictingtheNumberofResponsestobeChosen
Asstatedabove,theminimumandmaximumoptionsprovidethenumberofresponsesthatcanbe
answeredforaspecificquestion.Therearesomevariationsinsyntaxtoconsider.
Item
[1]

[1..]

[1..3]
[..]

14

Description
Whenonlyonenumberisspecifiedintheminimum/maximumparameter,itis
assumedthatthisnumberisboththeMinimumANDmaximumamount.
Exampleshownallowsforasingleresponsetobechosenforthequestion.Is
thesameastyping[1..1]
Allowsformultiplecategoriestobechosen(multipleresponsequestion).Not
statingamaximumamountallowseaseofupdatingthequestionwithadditional
responsesasneeded.
Statestheminimumamountofcategoriestobechosenis1andthemaximumis
3.UsefulforquestionswhichaskforresponsesAnsweruptoXcategories.
Nominimumsormaximums(thisisthedefault)

SurveyProgrammingFundamentals

Chapter2ConstructingQuestions

Beawarethatnotstatingaminimumnumberofanswerswillallowtherespondenttomoveforwardin
thesurveywithoutprovidingaresponse.Allowingnoanswerinthiswayprovidesnomethodto
determineiftherespondentwaspresentedthisquestion.Thedatafortherespondentwillsimply
containablank.

Laterinthecoursewewilllearnhowtoallowfortherespondenttonotansweraquestion,yet
havethedatastoreavalueshowingthattherespondentwasexposedtothequestion.

Example

TravelItem"Fromthelistbelow,whichoneitemwouldyoumostwanttobringwithyou
onaleisuretrip?"
categorical[1..1]

{
Camera,
Map,
ComfortableFootwear"ComfortableFootwear",
FriendTravelCompanion"Friend/TravelCompanion"
};

Createsasinglecategoricalquestionwithradiobuttons:

15

Chapter2ConstructingQuestions

SurveyProgrammingFundamentals

CountryVisited"Whichofthefollowingcountrieshaveyouvisited?"
Example

categorical[1..]
{
Antarctica,

Africa,
Asia,
Australia,
Europe,
NorthAmerica"NorthAmerica",
SouthAmerica"SouthAmerica"
};

Noteintheexamplesabove,alternatelabelsarenotrequiredwhenthetextyouwantto
displayisalsoalegallabelname.

Thecheckboxesindicatethatmorethanoneresponsecanbegivenasstatedinthesyntaxas[1..].

16

SurveyProgrammingFundamentals

Chapter2ConstructingQuestions

Date
Whenrequestingadatefromtherespondent,itiseasiertocollectadatetypeversusmultiplelong
typefields.
Name"Text"date["min".."max"];
Item
Name

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
"Text"
Textassociatedwiththeitem(consideredthelabelintheobjectmodel).
date
Keywordtoenteradateandtimefield.Canenterdatesandtimesoroneorthe
other.Takesmanydifferentdateformats(Seebelow).
["Min".."Max"] Optionalparameters.Controlstheminimumandmaximumdaterangeallowed
forthequestion.Notetheadditionofthedoublequotesaroundthemin/max.

Keypointsregardingdates:

Theformatforthedateisveryflexible.Some(notall)oftheformatstakenare:
o DDMonthNameYYY(7April2007)
o DDShortMonthNameYYY(7Apr2007)
o YYYY/MM/DD(2007/04/07)
o MM/DD/YY(04/07/07)
Ifyouleaveoffcertainportionsofthedate/timefield,itwillmakeassumptions.Anexample
wouldbeifyouwerecollectingonlymonthandyearandenterApril2007,mrInterviewwill
recordthedateasApril1,2007.Ifatimeisnotchosen,itassumesthecurrenttime.
Whenyouruntheinterviewyoumayentertimesin12houror24hourformat;forexample,
2:30pmor14:30.IfyoudonotspecifyAMorPM,itwillassumea24hourclock.
Metadatalanguagecontrolstheformatofthedatetaken.Anexamplewouldbetryingto
enteraUKEnglishdateofdd/mm/yywhenthemetatdatalanguagesdonotcontainEnglish
UK,onlyEnglishUS.Inthiscase,thedatewouldbetransformedtotheEnglishUSversionof
mm/dd/yy.

Ifyouwantmorecontroloverthedatefield,createacustomcontrol,suchastheexample
calendar.htmintheDDL:DDL.chm::/interviewscripting_templates_custom_writing.htm.

17

Chapter2ConstructingQuestions

SurveyProgrammingFundamentals

Example

LastTripDate"Whatwasthedateyouleftforyourlasttrip?"
date;

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

TheresultoftheLastTripdatequestionwouldlooklikethis:

18

SurveyProgrammingFundamentals

Chapter2ConstructingQuestions

Boolean
Booleantypequestionsrecordatrueorfalsevalue.Inwebsurveys,thistypeisaneasywaytoprovide
asinglecheckboxresponse.
Name"Text"boolean;
Item
Name

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
Textassociatedwiththeitem(consideredthelabelintheobjectmodel).
Keywordtocreateatrue/falsequestion.Createsacheckboxonwebsurveys.
CheckingtheboxisaTrueresponseandleavingitemptyisfalse.

"Text"
boolean

YoucanaddcategoriestoaBooleanquestiontosimulateacategoricalquestion.Besure
ifyouusethisoptionthatyouwillonlyhave2responses,neveranymore.

HereisanexampleofaBooleanquestionandwhatitwilllooklikeinthebrowser:
ReceiveTravelInfo"Checkhereifyouwishtoreceiveanemailregardingtravelsafety."
Example

boolean;

19

Chapter2ConstructingQuestions

20

SurveyProgrammingFundamentals

SurveyPrrogrammingFundamentalls

Chapte
er3

Chap
pter3Creatin
nganmrStudioInterviewSScript

Cre
eatingan
nmrStudio
oIntervie
ewScript
t

Nowthattyouknowho
owtocreatesomebasicq
questiontypes,letsstartu
usingmrStudiiotocreateand
testoursscript.WewiillusemrStud
diotocreatettheDimensio
onScriptingfo
oroursurveys.

Thischa
T
apterwillcover:
HowtocreeateanmrStud
diometadataffile
Overviewo
ofmrStudioan
ndthetoolbarssand
menus
HowtotesstyoursurveywithmrStudio
o

Openin
ngmrStud
dio
YouwillffindmrStudio
oat:
StartP
ProgramsSP
PSSDimensio
onsmrStudio.

21

Chapter3CreatinganmrStudioInterviewScript

SurveyProgrammingFundamentals

UnderFileNewFileyouwillseethedifferenttypesoffilesyoucancreateinmrStudio.

ForthiscoursewewillbecreatingaMetadataFile(.mdd).Underfilenamefillinafilenameforyour
projectandchooseOpen.NowyouarereadytostarttypingthecodediscussedinChapter2intothe
metadatasection.

Ifyouneedhelpatfirst,ControlMdisplaysthelistofquestiontypesthatyoucanchoose
oneandhavethestructureofthequestiontostartwith.Themacroscanbeaniceplace
tostartwhenyoudontwanttogobacktotheDDLormanualforsyntaxquestions.

22

SurveyProgrammingFundamentals

Chapter3CreatinganmrStudioInterviewScript

OverviewofToolbars/Shortcuts
mrStudiohasmanytoolstohelpyouwiththecreationofyourscript.Letsreviewthedifferent
toolbarsandpartsofthemrStudioscreen.

FormattingToolbars
TheformattingtoolbarsprovidebasicbutneedededitingskillsinmrStudio.
FileToolbar:Usedtocreate,opensaveandprintfiles.

EditToolbar:Cut,copy,paste,undo,redoandfind.

FormattingToolbar:Indentations,commenting,macrosandoptions.

Indentingleftorrighticons.Indentingwillbecomeaveryimportantaspectofyourscript
writingintheroutingsection.Itwillhelpmakeyourcodeeasytofollow.
CommentandUncommentSelectionicons.ThecommentsinDimensionsScriptingare
indicatedbyasinglequotemarkandwillturnthecommentedtextgreen.Byhighlightinglarge
blocksoftext,youcancommentanduncommentthesectionseasilywiththetoolbaricons
above.
ThemacrosiconallowsyoutoaccessthepredefinedsyntaxformrStudio.Youalsohavethe
abilitytoaddyourownmacrosaswell.

Notethatyoucancopymacrodefinitionsfromonemachinetoanotherbycopyingthefile
MacroDefinitions.xmlfromthedefaultmrStudiodirectory.

23

Chapter3CreatinganmrStudioInterviewScript

SurveyProgrammingFundamentals

ViewToolbar
ThistoolbarcontrolswhichtabsareshowinginmrStudio.Dependingonwhatyouaretryingto
accomplish,youwillwanttoshowdifferentaspectsofmrStudio.

Fornow,letsstartwithtwohelpfulaspects,MetadataExplorerandthelocalspane.

MetadataExplorer
Asyoucreateyourmetadata,youcanopentheMetadataviewertoseeatreeviewversionofyour
script:

TheiconsshowninthisviewerareusedthroughoutallDimensionsproductstorepresentthequestion
types.

24

SurveyProgrammingFundamentals

Chapter3CreatinganmrStudioInterviewScript

Locals
Asyourunasurvey,thelocalsallowsyoutoseeyourresponsestothequestionsasshownbelow.

Inaddition,thelocalspanewillprovideextremelyhelpfulinthiscourseasyoustarttounderstandthe
questionsasobjects,asyoucanseethedifferentpropertiesofthequestions.

InterviewOptionsToolbar
TheInterviewOptionstoolbargivesyouaccesstomrStudiotasks.

Fromlefttorighttheoptionsare:

Addingroutingcontexts
Removingroutingcontexts
Metadatatool1
Metadatatool2
HTMLtidy(triestoimproveyourHTMLcodeinyourtemplatestobeperfectlyformed)
Creatingquotas(openstheQuotaToolApplication)
ActivationofthesurveytomrInterview

TipsforCreatingMetadata
WewilldiscussthemrStudioenvironmentandthetoolsprovidedtohelpyoucreateyourscripts
throughoutthemanual.Hereareafewtipstogetyoustarted:

Allkeywordsarecolorcodedinblue.Alltextwithindoublequotesisalsocolorcoded.
Whentroubleshootingsyntaxerrors,lookfortheappropriatecolorcodingtohelpyoufindthe
problems.
Savefrequently,asyourmetadatawillbecheckedforsyntaxerrorswhenyousave.
Errormessageswillstatethelinenumbersassociatedwithit.Noticethelinenumbersonthe
leftsideofyourcodeinmrStudiotohelpyouwiththis.

25

Chapter3CreatinganmrStudioInterviewScript

SurveyProgrammingFundamentals

Aftersavingandclosingthedocument,mrStudioreformatsyourmetadataintoastandardized
format.Thetermusedforthisisrehydration.Beawareofthissoyoudontspendadditional
timeonproperformattinginthemetadatasection.

ViewingandTestingtheSurveyinmrStudio
Whenyouhavesavedsothatyouknowallerrorsaregone,youarereadytoviewtheresultsofyour
script.Clickthestartbuttononthetoolbar:

OnthebrowsertabinmrStudio(ifyoucannotseethebrowsertab,fromthemenuchooseView
Browser)youwillbeabletoseetheinterviewasitwillappearwhenitisactivatedinmrInterview.

26

SurveyProgrammingFundamentals

Chapter3CreatinganmrStudioInterviewScript

Laterinthiscoursewewilladdformattingandtemplatestoenhancethelookofthe
interview;thesewillalsobeviewableinthemrStudiobrowserwindow.

Youcanchoosetoanswerthequestionsyourself,oryoucanchooseF5toletmrStudioautomatically
answerthequestionsonthescreenforyou.(Thiswillprovehelpfullaterwhentestingsurveyswith
largegridquestions).
Theinterviewwillcomplete,butifyouwishtointerruptthescript,clickontheStopbuttoninthe
browserwindow,ortheStop(squareicon)inthetoolbar.

Asyoucansee,therearemanyfeaturesinmrStudiotohelpyoucreateyourinterviewscripts.Some
featuresyouwilluseimmediately,suchasthelocaltestingofsurveysandtheautoanswering
questionswithF5.Others,suchascreatingmacrosandviewingthelocalspaneinformationwillcome
laterinyourlearning.

27

Chapter3CreatinganmrStudioInterviewScript

SurveyProgrammingFundamentals

Exercise
OpenmrStudioandcreateametadatafilecalledGroceryBill.mdd.Completethefollowingquestions
inthisdocument,thentestthesurveywithinmrStudio.
GroceryIntro Asyouagreedtopreviously,pleasehaveyourlastgrocerybillavailableforreferencefor
thisnextsectionofthesurvey.

GroceryDate Lookingatyourlastgrocerybill,whatdatedidyougotothestore?

StoreName

Whatwasthenameofthestoreinwhichyoushopped?

Walmart
Safeway
Kroger
Albertsons
AholdUSA
Delhaize
Publix
WinnDixie

ItemTypes

Whichofthefollowingcategoriesofgroceriesdidyoupurchaseonthisshoppingtrip?

Cheese/OliveBar
SaladBar
DeliItems
Meat/Seafood
Produce
CannedGoods
Pasta/Grains

Generic

Onthisparticularshoppingtrip,didyoupurchaseanygenericbranditems?

Yes
No

28

SurveyProgrammingFundamentals

Chapter3CreatinganmrStudioInterviewScript

ItemsBought Howmanyitemsdidyoubuy?

GroceryCost Exactlyhowmuchdidyouspend?

PurposeTrip Brieflydescribethereasonforyourtriptothegrocerystoreonthatparticularday.

AgreeContact Pleasechecktheboxbelowifyouagreetoallowustocontactyoulaterifwehave
additionalquestionsregardingyourtriptothegrocerystore.

29

Chapter3CreatinganmrStudioInterviewScript

30

SurveyProgrammingFundamentals

SurveyPrrogrammingFundamentalls

Chapte
er4

Chapter4 SpecialRespo
onsesandOp
ptions

SpecialResp
ponsesan
ndOption
ns

InChapteer2wecoverredbasicquestionsyntax.Thischapterrwillexpandontheconceeptsofthat
chapteraandaddaddittionaloptionsstoenhancethosequestio
ontypes.

Intthischap
pterwew
willcoveer:
Specialkeyywordstoprovvideadditionall
functionality
Collectingspecifictextreesponseswhen
n
ntchoosesother
responden
Creatingsu
ubheadingstoimprovethe
appearancceofcategoricalquestions

nMultiple
eSelection
nQuestion
ns
SingleResponseChoicesin
Withmultipleselectio
oncategoricallquestions,yyoumaywantttohavecerttainresponsesthatcannottbe
chosenin
ncombination
nwithanyottherresponsee.Inorderforthatlogicto
ohappen,you
umustindicate
thattherresponsesho
ouldbeasingleselectchoiiceusingthekeyword,excclusive.
N
Name"Text"
"categorical[[min..max]
{
{ID1"AltText1
1",
IIDn"AltTextn
n"exclusive}};

31

Chapter4SpecialResponsesandOptions
Item
Name

SurveyProgrammingFundamentals

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
Textassociatedwiththeitem(consideredthelabelintheobjectmodel).
Keywordtocreateaquestionwithcategoriesforresponsechoices.Question
typemustbecategoricaltousetheexclusivekeyword.
Optionalparameters.Controlstheminimumandmaximumamountof
categoriesthatcanbechosenbyarespondent.Defaultisopentoanyamount
ofchoices.Automaticallyissuesanerrormessageifthenumberofresponses
chosenisbelowtheminimumorabovethemaximum.
Indicatesthestartofthecategoriesyouwishtherespondenttochoosefrom
Uniqueidentifyingnamefortheresponse.Thisneedstobeuniqueper
question,notmetadatafile.Rulesfortheresponsenamesarethesameasthe
nameofthequestion.
Optionaltexttoshowtherespondentinsteadofthenameofthequestion.This
willapplywhenthenameofthequestionisnotthesameasthetextyouwishto
showtherespondent.
Makesaspecificresponsetheonlychoicethatcanbechoseninamultiple
selectionquestion.Keywordisplacedafterthecategorynameandalternate
text(ifpresent).

"Text"
categorical
[min..max]

{}
ID1,IDn

AltText1,
AltTextn
exclusive

AirlinesFlown"Inthepastyear,whichofthefollowingairlineshaveyouusedfortravel?"
Example

categorical[1..]
{

American,
Delta,
United,
OtherAirline"Otherairline",
NeverFlown"Neverflownbefore"exclusive
};

32

SurveyProgrammingFundamentals

Chapter4SpecialResponsesandOptions

IftherespondenttriestochoosetheresponseNeverflownbeforeandanyotherresponse,the
followingerrorwillappear:

Exclusiveresponsesshowupinboldbydefault.Thiscanbeoverwrittenbytemplatesor
styles,whichwillbediscussedinChapter13.

33

Chapter4SpecialResponsesandOptions

SurveyProgrammingFundamentals

SpecialResponseswithCategoricalQuestions
Therearespecialkeywordswhichrepresentsomecommonresponsestointerviews,NoAnswer,Dont
Know,andRefusedtoAnswer.
Name"Text"categorical
{ID1"AltText1",
ID2"AltText2",
IDn"AltTextn"Keyword};
Item
Name

"Text"
categorical
{}
ID1,ID2,IDn

AltText1,
AltText2,
AltTextn
Keyword

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
Textassociatedwiththeitem(consideredthelabelintheobjectmodel).
Keywordtocreateaquestionwithcategoriesforresponsechoices.
Indicatesthestartofthespecialresponsecategoriesyouwishtherespondentto
choosefromforthequestion
Uniqueidentifyingnamefortheresponse.Thisneedstobeuniqueper
question,notmetadatafile.Rulesfortheresponsenamesarethesameasthe
nameofthequestion.
Optionaltexttoshowtherespondentinsteadofthenameofthequestion.This
willapplywhenthenameofthequestionisnotthesameasthetextyouwishto
showtherespondent.
RepresentsoneofthekeywordsNA(NoAnswer),DK(DontKnow),orREF
(Refused)

Benefitsforusingthesekeywords:

34

Theresponseisautomaticallysettobeexclusiveandfixedinthepositioninwhichitwastyped
whenthecategoryorderischanged.
WhenusingtheCATI(ComputerAidedTelephoneInterviewing)option,thesekeywordshave
shortcutkeysfortheeaseofusefortheinterviewers
Theseresponsescanbeidentifiedinasystematicway,whichmakesiteasiertoreference
thesequestiontypeswhencreatingsubroutinesorfunctions.

SurveyProgrammingFundamentals

Chapter4SpecialResponsesandOptions

Example

HotelChainStayed"Choosethehotelchainsyouhavestayedatthispastyear."
categorical[1..]
{

InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow"DontRemember"DK,
Refused"PrefernottoAnswer"REF
};

Youcanusethekeywordsasthenamesfortheresponses;howeverafterrehydrationthenameswill
showasadash().

35

Chapter4SpecialResponsesandOptions

SurveyProgrammingFundamentals

CategoricalResponseswithNonCategoricalQuestions
Youcanaddcategoricalresponsestoquestiontypesthatarenumeric,text,ordate.Thespecial
keywordoptionsofNA,DKandREFaretypicallyusedinthisscenario,asthiscanprovevaluableto
providerespondentswithawaytoindicatetheydontknoworprefernottoanswerthequestion.
Name"Text"qtype[min..max]
codes(
{ID1"AltText1"Keyword,
IDn"AltTextn"Keyword}
);
Item
Name

"Text"
Qtype
[Min..Max]
codes
{}
ID1,IDn

AltText1,
AltTextn
Keyword

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
Textassociatedwiththeitem(consideredthelabelintheobjectmodel).
Representsthenoncategoricalquestiontypesoflong,double,textordate.
Optionalparameters.Controlstheminimumandmaximumvaluesthatcanbe
chosenbyarespondent.
Keywordtoindicateyouareaddingspecialresponsecategoriestoanon
categoricalquestion.
Indicatesthestartofthespecialresponsecategoriesyouwishtherespondentto
choosefromforthequestion
Uniqueidentifyingnamefortheresponse.Thisneedstobeuniqueper
question,notmetadatafile.Rulesfortheresponsenamesarethesameasthe
nameofthequestion.
Optionaltexttoshowtherespondentinsteadofthenameofthequestion.This
willapplywhenthenameofthequestionisnotthesameasthetextyouwishto
showtherespondent.
RepresentsoneofthekeywordsNA(NoAnswer),DK(DontKnow),orREF
(Refused).Thiskeywordisoptional.

36

SurveyProgrammingFundamentals

Chapter4SpecialResponsesandOptions

AmtSpentYr"Whatpricedidyoupayforyourlastairlineflight?"
Example

double[0..3999.99]
codes(

{
dontknow"Dontremember"DK,
Refused"Prefernottoanswer"REF
}
);

Thiscodewouldcreatecheckboxesbelowthenumericresponseboxasshownbelow:

37

Chapter4SpecialResponsesandOptions

SurveyProgrammingFundamentals

CollectingOtherTextResponsesinCategoricalQuestions
Theotherkeywordallowstherespondenttoenterananswerthatisnotonthecategorylist.
Name"Text"categorical
{ID1"AltText1",
IDn"AltTextn"other};
Item
Name

"Text"
categorical
{}
ID1,ID2

AltText1,
AltText2
other

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
Textassociatedwiththeitem(consideredthelabelintheobjectmodel).
Keywordtocreateaquestionwithcategoriesforresponsechoices.
Indicatesthestartofthecategoriesyouwishtherespondenttochoosefromfor
thequestion
Uniqueidentifyingnamefortheresponse.Thisneedstobeuniqueper
question,notmetadatafile.Rulesfortheresponsenamesarethesameasthe
nameofthequestion.
Optionaltexttoshowtherespondentinsteadofthenameofthequestion.This
willapplywhenthenameofthequestionisnotthesameasthetextyouwishto
showtherespondent.
Keywordtocreateatextboxontheresponsetocollectadditionalinformation.

HotelChainStayed"Choosethehotelchainsyouhavestayedatthispastyear."
Example

categorical[1..]
{InterContinental,

Cendant,
Marriott,
Accor,
Choice,
Hilton,
OtherHotel"OtherHotelChain"other,
DontKnow"DontRemember"DK,
Refused"PrefernottoAnswer"REF};

38

SurveyProgrammingFundamentals

Chapter4SpecialResponsesandOptions

Thiswillcreateatextboxtocollectthespecificnameofanyhotelchainsnotlisted.

Youcanhavemultipleotherspecifyresponsesperquestion.

Subheading
Youcancreatetextonlyitemstodescribeagroupofresponsesbycreatingsubheadings.

Name"Text"categorical
{
Subhead1"SubText1"

ID1"AltText1",

ID2"AltText2"

},
Subheadn"SubTextn"

ID3"AltText3",

IDn"AltTextn"

}
};

39

Chapter4SpecialResponsesandOptions

SurveyProgrammingFundamentals

Item
Name

"Text"
categorical
{}
Subhead1,
Subheadn
SubheadText1,
SubheadTextn
ID1,ID2,IDn

AltText1,
AltText2,
AltTextn

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
Textassociatedwiththeitem(consideredthelabelintheobjectmodel).
Keywordtocreateaquestionwithcategoriesforresponsechoices.
Indicatesthestartofthesubheadingsandcategories
NameforSubheadingitem
RepresentsalternatetextfortheSubheadings.
Uniqueidentifyingnamefortheresponse.Thisneedstobeuniqueper
question,notmetadatafile.Rulesfortheresponsenamesarethesameasthe
nameofthequestion.
Optionaltexttoshowtherespondentinsteadofthenameofthequestion.This
willapplywhenthenameofthequestionisnotthesameasthetextyouwishto
showtherespondent.

Example

TravelHelp"Haveyouusedanyofthefollowingtohelpyouwithyourtravel
arrangements?"
categorical[1..]
{
TravelBooks"TravelBooks"
{
LonelyPlanetBook"LonelyPlanet",
Fodor"Fodor's",
Frommer"Frommer's"
},
Websites"Websites"
{
Expedia"Expedia",
Orbitz"Orbitz",
Govt"GovernmentWebsites"
}
};

40

SurveyProgrammingFundamentals

Chapter4SpecialResponsesandOptions

Thepreviouscodewillcreatethefollowingquestioninthebrowser:

41

Chapter4SpecialResponsesandOptions

SurveyProgrammingFundamentals

Exercise
Updatethefirstexercise(GroceryBill.mdd)withthefollowingadditionsthatarehighlightedbelow:
GroceryIntro Asyouagreedtopreviously,pleasehaveyourlastgrocerybillavailableforreferencefor
thisnextsectionofthesurvey.

GroceryDate Lookingatyourlastgrocerybill,whatdatedidyougotothestore?

StoreName

Whatwasthenameofthestoreinwhichyoushopped?

Walmart
Safeway
Kroger
Albertsons
AholdUSA
Delhaize
Publix
WinnDixie
Other(Specify)______________

ItemTypes

Whichofthefollowingcategoriesofgroceriesdidyoupurchaseonthisshoppingtrip?
PreparedFoods

Cheese/OliveBar

SaladBar

DeliItems
NonPreparedFoods

Meat/Seafood

Produce

CannedGoods

Pasta/Grains
NoneofThese

Generic

Onthisparticularshoppingtrip,didyoupurchaseanygenericbranditems?

Yes
No
DontRemember

42

SurveyProgrammingFundamentals
ItemsBought

Chapter4SpecialResponsesandOptions

Howmanyitemsdidyoubuy?

GroceryCost Exactlyhowmuchdidyouspend?

PrefernottoAnswer

PurposeTrip Brieflydescribethereasonforyourtriptothegrocerystoreonthatparticularday.

AgreeContact Pleasechecktheboxbelowifyouagreetoallowustocontactyoulaterifwehave
additionalquestionsregardingyourtriptothegrocerystore.

43

Chapter4SpecialResponsesandOptions

44

SurveyProgrammingFundamentals

SurveyPrrogrammingFundamentalls

Chapte
er5

Chapter5B
BasicRoutingLogic

Ba
asicRoutin
ngLogic

Sofar,wehaveonlyccreatedthem
metadataporttionofoursurvey.Thischapterfocusessonhowto
controlth
heflowofthe
esurveyquesstions.

Thisch
hapterco
overs:
Understan
nding,adding,reemovingroutingg
context
Changingtheorderofyou
urquestions

Addingskiplogic/routingtoyoursurvey
Understan
ndingDimension
nsFunctionsanduse
withlogicstatements

Herearesomeofthemanythingstheroutingsectionallowssyoutodo:

Controlwhatquestionsareeasked
C
T
Theorderofq
questions
A
Addcondition
nalstatementtsaboutquesstionstoconttrolif/howtheeyareasked
A
Allowsasingl
emetadatafiilewithdifferrentroutingsforeaseofch
hangestomu
ultimodesurvveys

mddfileassh
hownbelow:
Toaccessstheroutingsection,clickkontheWebtabinyour.m

45

Chapter5BasicRoutingLogic

SurveyProgrammingFundamentals

Youcanaddadditionalroutingstoyourquestionnaire.Thiswouldbenecessaryforsurveysfielded
withmultiplecollectionmethods,suchasweb,paperscanning,andtelephoneinterviewing.You
wouldalsoneedtoaddroutingifyouoriginallycreatedyourmetadatausingeithermrInterivewsBuild
activityortheaccessoryWordCapture,astheycreateapaperroutingthatisreadonly.
Toaddanadditionalrouting:

Tools
AddRoutingContext

46

SurveyProgrammingFundamentals

Chapter5BasicRoutingLogic

Youwillbepromptedforanamefortherouting.
Toremovearoutingcontext,clickonthetabofthecontextyouwishtoremoveandchoose
ToolsRemoveRoutingContextasseeninthediagramabove.
Whensettingupyourrouting,hereareafewthingstoremember:

Thereisnorehydrationoftheroutingsection,soformatcounts.UseTabstoindentandmake
yourcodeeasytoread.
Savingdoesnotchecktheroutingsyntax;onlywhenyoustartthesurveywillyouseethe
runtimeproblems.

AskingQuestions
Allwehavedonesofariscreatemetadataandrunthesurveytoreviewthequestions.mrStudiowill
runallthequestionsinthemetadataifthereisnothingintheroutingsection.Thisisnotapractical
option,asalmostallscriptshavesomerouting.Additionally,mrInterviewwillnotrunascriptwithout
havingaproperroutingsection.Themainitemsinyourroutingarestatementstoaskthequestions.
Name.Ask()
Item
Name
.Ask()

Description
Metadataitemname
Displaysandasksthequestion

Wewillneedtocreate.Ask()statementsforeachquestioninoursurvey.Toquicklyaskallthe
questionsinyourmetadata,

ViewtheMetadataExplorer
ClickontheFieldsfolder
RightclicktochooseCopyasAsk
Pasteintheroutingsection

47

Chapter5BasicRoutingLogic

SurveyProgrammingFundamentals

ByexpandingtheFieldsfolder,youcanpickandchoosespecificquestionstocopyas.Ask
statements.

48

SurveyProgrammingFundamentals

Chapter5BasicRoutingLogic

ReadOnlyItems
Thereisawaytoshowthequestionandcurrentresponseforaquestionwithouttheabilitytochange
theresponse:
Name.Show()

Item
Name
.Show()

Description
Metadataitemname
Displaysthequestionanditscurrentresponseinreadonlyformat

When.Show()isusedwithaquestion,thechoicesaregrayedoutandyouareonlyabletoseethe
currentresponseforthequestionasshownbelow.

.Show()canalsobeusedwithinfoitems;thereisnodifferenceusinga.Show()or.Askwith
aninfoitem.

49

Chapter5BasicRoutingLogic

SurveyProgrammingFundamentals

ConditionalStatements
Nowthatwehaveaskedallthequestions,letslookintowaystodetermineifarespondentshouldbe
askedcertainquestions.Thisisusuallycalledroutingorskippatterns.Therearetwoconditionalitems
wewillreviewtohelpuscreatetheroutingforoursurveys.

IfThenElse
SelectCase

IfThenElse
Ifthenelseisaconditionalstatementwhichwillcomparetwoormorestatementsandtestthe
results.Iftheresultsaretrue,thethenactionsaretaken;ifnot,theelseactionsaretaken.The
syntaxinDimensionsscriptingis:
IfconditionThen

Actions

Endif
Forsimpleconditionsitcanallbestatedonasingleline:
IfconditionThenAction

Additionally,youcouldaddtheoptionsforElseifand/orElse:
IfconditionThen

Actions

ElseIfconditionThen

Actions

Else

Actions

EndIf

50

SurveyProgrammingFundamentals

Chapter5BasicRoutingLogic

Nowletslookatsomeexamplesoftheseconditionalstatements.Todothis,wewillneedto
understandthesyntaxforsomeoftheActionsyoucoulduseintheconditionalstatements.One
actiontouseintheroutingsectionistestingtheresponsetoapreviousquestion.Wewilllookat
manywaystodothisthroughoutthemanual.Forthisconditionalsection,hereissomebasic
information.
Name.Response.Value=conditionorresponse
Item
Name
.Response.Value
Conditionor
response

Description
Representsthemetadataitemname
Propertytoreferencethenamedquestionscurrentresponsevalue
Anyconditiontorepresentapossibleresponseforthenamedquestion,or
specifyanactualresponse

Inthenextexample,wehavethefollowingquestionsasshowninthemetadata:
Metadata(enUS,Question,Label)
Example

TravelItem"Fromthelistbelow,whichoneitemwouldyoumostwanttobringwithyou
onaleisuretrip?"
categorical[1..1]
{
Camera,
Map,
ComfortableFootwear"ComfortableFootwear",
FriendTravelCompanion"Friend/TravelCompanion"
};

'IfFriend/TravelCompanionischoseninTravelItem,askFriendRelate
FriendRelate"Whatistherelationshipofthatpersontoyou?"
text;

'IfCameraischoseninTravelItem,askTravelItemCost
TravelItemCost"Howmuchwouldyouexpecttopayforthecamera?"
Double[0..5000];

EndMetadata

51

Chapter5BasicRoutingLogic

SurveyProgrammingFundamentals

Thelogicforthequestionsis,iftheanswertotheTravelItemquestionisFriend/TravelCompanion,
thenasktheFriendRelatequestion.Thelogicisachievedinthefollowingroutingsectionwiththeuse
ofanIfThenstatement:
Routing(Web)
Example

TravelItem.Ask()
IfTravelItem.Response.Value={FriendTravelCompanion}Then
FriendRelate.Ask()
EndIf
IfTravelItem.Response.Value={Camera}Then
TravelItemCost.Ask()
EndIf
EndRouting

Ifthequestioniscategorical,youwillneedtorefertotheNameoftheresponse(notthelabelthatis
showntotherespondent)andenclosethisincurlybracketsasshownintheaboveexample.

SelectCase
SelectCasestatementsworksimilartoanIfThenstatement.SelectCasestatementsallowyouto
createconditionalactionsbasedonaquestiontypethatcanonlyhaveasinglevalue(single
categorical,numeric,Boolean).
SelectCaseName.Response.Value
CaseResponse1
Actions1
CaseResponseN
ActionsN
...
[CaseElse
ActionsN]
EndSelect

52

SurveyProgrammingFundamentals
Item
SelectCase
EndSelect

Chapter5BasicRoutingLogic

Description
MarkstheStartandendoftheselectcasestatement

Name.Response.Value Questionanditsresponsethatyouaretesting
CaseResponse1,Case Representsresponsestoaquestionorexpressionsthatgroupresponsesto
Response2
thequestion.

Actions1,Actions2
Representoneormorestatementstobeexecutedifthequestion'sresponse
matchestheresponseforthecurrentCasestatement.

CaseElse
Representsoneormorestatementstobeexecutedforrespondentswhofail
ActionsN
allthepreviousCasetests

Thecasestatementcanbeusefulwhenyouhavemanyresponsestotestsinceyouonlyspecifythe
questionnameonce.Thefollowingshowsthepreviousexampleforanifthenstatement,nowwith
theselectcasesyntax.

Example

Metadata(enUS,Question,Label)
TravelItem"Fromthelistbelow,whichoneitemwouldyoumostwanttobringwithyou
onaleisuretrip?"
categorical[1..1]
{
Camera,
Map,
Comfortablefootwear"ComfortableFootwear",
FriendTravelCompanion"Friend/TravelCompanion"
};

'IfFriend/TravelCompanionischoseninTravelItem,askFriendRelate
FriendRelate"Whatistherelationshipofthatpersontoyou?"
text;

'IfCameraischoseninTravelItem,askTravelItemCost
TravelItemCost"Howmuchwouldyouexpecttopayforthatitem?"
Double[0..5000];

EndMetadata

53

Chapter5BasicRoutingLogic

SurveyProgrammingFundamentals

Routing(Web)
TravelItem.Ask()

SelectCaseTravelItem.Response.Value
Case{FriendTravelCompanion}
FriendRelate.Ask()
Case{Camera}
TravelItemCost.Ask()
EndSelect
EndRouting

TohavemrStudiocreatethecasestatementforyou,viewthemetadataexplorer,then
choosethequestioninwhichyouwillbebasingtheselectstatement.Choosethequestions
categoriesfolderandrightclicktochooseCopyasSelectstatement.Youcanthenpastea
shelloftheselectstatementwiththequestionscategoriesasastartingpoint.

54

SurveyProgrammingFundamentals

Chapter5BasicRoutingLogic

Goto
Intheexamplesabove,wehavebeencreatingourroutingbasedongoodprogrammingpracticesin
whichyounestquestionswithinconditionalstatements.Themethodsshownthusfarcanhelpmake
yourcodeeasytofollowanddebug.Sometimes,however,itmaybehelpfultoskiparoundstatements
intheroutingsection.TheGotokeywordcanallowyoutodothiswhencombinedwithaconditional
statement.
GotolineLabel

lineLabel:
Item
Goto
Linelabel
:

Description
Keywordindicatingthescriptshouldskiptothelinelabelindicated
Representsalinelabelofyourchoice.Thenamingconventionforlinelabelsfollows
thepatternofallnamesinthemetadata.Thesearenotseenbytherespondent.
Neededtoindicatethisisthelinelabelitem.

Asanexample,supposeweaskediftherespondenttravelsforbusiness.Thenthereareaseriesof
questionsaboutbusinesstravel,andaseriesofquestionsabouttravelforpleasure.Wecanuseagoto
andlinelabelstoachievetheroutingnecessary.

Routing(Web)
Example

TravelforBusiness.Ask()
IfTravelforBusiness.Response.Value={No}thengotoPleasureSection

DaysPerYrBusinessTravel.Ask()
InternationalBusiness.Ask()

PleasureSection:
TravelforPleasure.Ask()

EndRouting

55

Chapter5BasicRoutingLogic

SurveyProgrammingFundamentals

LogicalExpressions
Intheprevioussection,welookedatsomeverysimplelogicalexpressions,suchas
QuestionName.Response.Value=response.Wewillcoveradditionaloptionsforcreatingexpressions.
NumericQuestions
Fortestingnumericquestions(longordouble),usethemathoperatorslistedinthetablebelow.
Item
=
<>
<
<=
>
>=

Example

Description
Equalto
Unequalto
Lessthan
Lessthanorequalto
Greaterthan
Greaterthanorequalto

Metadata(enUS,Question,Label)

AmtSpentAccom"Whatpricedidyoupayforyourlastovernightaccommodations?"
double[0..3999.99];

'IfAmtSpentAccomis$150orgreater,askTypeAccomquestion
TypeAccom"Atwhattypeofaccommodationsdidyoustay?"categorical[1..1]
{Hotel,
Motel,
BedBreakfast"BedandBreakfast",
Hostels,
Resorts,
OtherAccom"OtherAccommodations"other};
EndMetadata

Routing(Web)

AmtSpentAccom.Ask()

IfAmtSpentAccom.Response.Value>=150Then

TypeAccom.Ask()

EndIf

EndRouting

56

SurveyProgrammingFundamentals

Chapter5BasicRoutingLogic

BooleanQuestions
BooleanquestionshavevaluesofTrueorFalse,sotheycaneasilybecheckedwithasimplestatement:
Name.Response.Value=condition
Item
Name

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
Response.Value Currentresponsetothequestionidentifiedbynameabove
condition
True(checkboxwaschecked)orFalse(checkboxwasleftempty)

TextQuestions
Withtextquestionsyoucantestwhethertheresponsematchesapattern.Theexpressionformatis:
NameLike"pattern"
Item
Name

like
pattern

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
Keywordtoindicateyouaretryingtomatchatestpattern
Representsthetextwithwhichtheresponseistobecompared.Anunderscore
(_)inthetextmatchesanysinglecharacter,andapercentsign(%)matchesany
numberofcharacters,includingzero

Thefollowingcodecheckstextquestionstoseeifitcontainstheword,Luftansa.Ifitdoes,thenit
followsupwithanotherquestion.

Example

Metadata(enUS,Question,Label)
BestAirTravel"Explainyourbestexperiencewithairtravel.Pleasementionyour
destinations,airportsandairline."
text;

TimesWithLuftansa"AndhowmanytimesoverthepastyearhaveyouflownLuftansa?"
long[0..365];
EndMetadata

Routing(Web)
BestAirTravel.Ask()
IfBestAirTravel.Response.ValueLike"%Luftansa%"Then
TimesWithLuftansa.Ask()
EndIf
EndRouting

57

Chapter5BasicRoutingLogic

SurveyProgrammingFundamentals

CategoricalQuestions
Forsingleresponsecategoricalquestions,youmayfindsimpleexpressionstosuffice,suchas
Name.Response.Value={Yes}.However,thingswillgetcomplex,andyoullneedtheDimensions
functionstomakemoreadvancedlogicstatements.
DimensionsfunctionsforcategoricalresponseswerecreatedspecificallyforDimensionsscripting.We
willcover3basicfunctionsforroutingpurposes,ContainsAll,ContainsAnyandAnswerCount.

Forafulllistoffunctions,seeDDL.chm::/funclib_overview.htm

ContainsAll
Identifieswhetheracategorylistcontainsallofthecategoriesinagivenlist.Andconditionforan
individualquestion.
Name.ContainsAll({ID1,IDn},parameter)
Item
Name
ContainsAll

Description
Representsthequestionname
Dimensionsfunctiontestingwhetheralistofcategoriesareallcontainedinthe
namedquestion.(Andcondition)

ID1,IDn

Uniqueidentifyingnamefortheresponse.

parameter

Representsanoptionalparameter.Iftheparameterissettotrue,thenthe
functionwillbetrueonlyiftheresponsecontainsallofthecategoriesandno
others(exclusive).Iftheparameterissettofalse(default),thenthefunction
willbetrueiftheresponsecontainsalloftheresponseslisted,regardlessof
otherresponseschosenfromthequestion.

Example

CountryVisited.ContainsAll({NorthAmerica,SouthAmerica})

ThisstatementwouldbetrueifarespondentchosebothNorthAmericaandSouthAmericainthe
CountryVisitedquestion,regardlessofotherresponseschosenfromthequestion.

58

SurveyProgrammingFundamentals

Chapter5BasicRoutingLogic

Example

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

ThisstatementwouldbetrueifarespondentchosebothNorthAmericaandSouthAmericaANDdid
notchooseanyotherresponsesinCountryVisited.

ContainsAny
Identifieswhetheracategorylistcontainsoneormorecategoriesinagivenlist.Orconditionforan
individualquestion.
Name.ContainsAny({ID1,IDn},true)
Item
Name
ContainsAny

Description
Representsthequestionname
Dimensionsfunctiontestingwhetheranyofthelistofcategoriesarecontained
inthenamedquestion.(Orcondition)

ID1,IDn

Uniqueidentifyingnamefortheresponse.

True

Representsanoptionalparameter.Iftheparameterissettotrue,thenthe
functionwillbetrueonlyiftheresponsecontainsanyofthecategoriesandno
others(exclusive).Iftheparameterissettofalse(default),thenthefunction
willbetrueiftheresponsecontainsanyoftheresponseslisted,regardlessof
otherresponseschosenfromthequestion.

Example

CountryVisited.ContainsAny({NorthAmerica,SouthAmerica})

TheabovestatementwouldbetrueforrespondentschoosingNorthAmerica,SouthAmerica,orboth.

59

Chapter5BasicRoutingLogic

SurveyProgrammingFundamentals

AnswerCount
ThefunctionAnswerCountcountsthenumberofmentionschosenforaspecificcategoricalquestion.
Name.AnswerCount()
Item
Name
AnswerCount

Description
Representsthequestionname
Dimensionsfunctionreturninghowmanyresponseshavebeenchoseninthe
namedcategoricalquestion.

Itreturnsanumericvalue,soyouwouldusenumericoperatorstotesttheresultofthefunction.
IfCountryVisited.AnswerCount()>3then
Example

WhySoMany.Ask()
Endif

Theexampleabovestatesthatifthenumberofanswersmentionedinthecategoricalquestion,
CountryVisited,isgreaterthan3,thenaskthefollowupquestion.

LogicalOperators
YoucanalsousethelogicaloperatorsofNot,And,Or,andXortocreatemorecomplexrouting
conditions.
NOT
Itisusedtonegateexpressions.Itsrecommendedtoenclosetheitemtonegateinparenthesisas
shownbelow.

Example

Not(TravelHelp.ContainsAny({Expedia}))

TheabovewouldbetrueiftherespondentdidnotanswerExpediafortheTravelHelpquestion.

60

SurveyProgrammingFundamentals

Chapter5BasicRoutingLogic

AND
Returnstruewhenbothpartsoftheexpressionaretrue.

Example

DaysTravelYr>5AndTravelHelp.ContainsAny({Expedia})

Theabovewillbetrueiftherespondenttraveledmorethan5daysandusedExpedia.

OR
Returnstruewheneitherorbothpartsoftheexpressionaretrue.

Example

DaysTravelYr>5OrTravelHelp.ContainsAny({Expedia})

Theabovewillbetrueiftherespondenttraveledmorethan5daysorusedExpedia.

XOR
Returnstruewhenonepart(butnotbothparts)oftheexpressionaretrue.

Example

DaysTravelYr>5XorTravelHelp.ContainsAny({Expedia})

Theabovewillbetrueiftherespondenttraveledmorethan5daysanddidnotuseExpedia,orifthe
respondenttraveled5daysorlessanddiduseExpedia.

61

Chapter5BasicRoutingLogic

SurveyProgrammingFundamentals

Somefindxorconfusing,butitcansavesomesyntax.Thefollowingstatementistheequivalentofthe
previousxorstatement:

Example

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

Asyoucanseewhencreatingcomplexconditionswithcombinationsofand,or,andnotstatements,
putparenthesisaroundthingsyouwantevaluatedtogether.

IfyouneedtorefertothespecialresponsesDK,REF,NAinanoncategoricalquestion,you
needtorefertoitasQuestionName.Response.Coded={ID},whereIDistheIDofthespecial
response.

TipsforRoutingSectionSyntax
Therearenumerouswaystowritethesyntaxwithintheroutingsection.Herearesomehintstohelp
youtotakefulluseoftheScriptAssistwithinmrStudio.

CtrlQtoseethefulllistofquestionsinyourmetadata
CtrlRwilldisplaytheresponsesforaQuestionlisted
RightclickonaquestionnameintheroutingsectionandchooseGotoDefinitionwhichwill
takeyoutothatquestioninthemetadatasection
Choosetheperiod(.)toseevalidchoicesforyourstatement

Thismaynotalwayswork,astherearemultiplewaystowritethestatements.Youwill
noticetheScriptAssistmaynotalwaysprovidetheproperchoices.Agoodexamplewould
beDimensionsfunctions,suchasContainsAny.Themethodusedinthischapter,
Name.ContainsAny({Response}),doesnotprovidescriptassistance.Thefullydocumented
way,ContainsAny(Name.Response.Value,{Response}),willshowparametersneeded.

62

SurveyProgrammingFundamentals

Chapter5BasicRoutingLogic

AddingErrorHandling
Anotherimportantaspectoftheroutingsectionistheabilitytosenderrormessagestoboththe
respondentandthemrInterviewloggingwhenthereisaproblemwiththescript.Errorhandlingallows
thesystemtogracefullyhandleerrorsthatoccur,asopposedtoagenericerrormessagesthatwillnot
provideappropriateinformationtofixtheproblemandpossiblyconfuserespondents.Thecodecan
bestandardizedandplacedineveryscript.Belowisasimpleexampletouseasastartingpoint.

Example

Routing(Web)
'Errorhandler
IfNotIOM.Info.IsDebugThenOnErrorGotoDefaultErrHandler
GotoStartOfScript

DefaultErrHandler:
Dimerrmsg,numerror
errmsg="Scripterroratline"+CText(Err.LineNumber)+","+Err.Description
IOM.Log(errmsg,LogLevels.LOGLEVEL_ERROR)
IfIOM.Info.IsTestThen
IOM.Banners.AddNew("ScriptErrMsg"+CText(numerror),errmsg)
numerror=numerror+1
EndIf
ResumeNext

StartOfScript:
'Enderrorhandler

EndRouting

Breakingdowntheexampleabove:

TheIOM.Info.IsDebugpreventstheerrorhandlerbeingenabledifthescriptisbeingrunin
mrStudio.
OnErrorGotoDefaultHandlersendsallerrostotheerrorhandler.Whenanerroroccurs,the
errorhandlerwritestheerrormessageandthelinenumbertothelogfile,IVW*.tmp.
IOM.Info.IsTestdisplaysthemessageonthetopofthecurrentpage.
TheResumeNextlineallowstheinterviewtocontinueafteranerror.

63

Chapter5BasicRoutingLogic

SurveyProgrammingFundamentals

Exercise
Usethemetadatafile,Routing.mddasyourstartingpoint.Completetheroutingsectionand
routing/skippatternsshownbelow.

CookAtHome Doyouevercookfoodathome?

Yes
No(SkiptoItemsOwned)

CookMealWk Howmanymealsperweekdoyoucookathome?__________

PeopleCookFor Doyounormallycookforanyofthefollowingatyourhome?Checkallthatapply.

Spouse/OtherAdultsinthehousehold
Childreninthehousehold
NonHouseholdMemberAdults
NonHouseholdMemberChildren
OnlyforMyself

(IfCookMealWkisgreaterthanorequalto5andPeopleCookForquestionhasadults,askWine)
Wine

Doyoueverservewinewiththemealsyouservetoothers?

Yes
No

(IfPeopleCookForisbothChildreninHHandNonHouseholdMemberChildren,askAllergyKids)
AllergyKids

Doanyofthechildrenyoumakemealsforhavefoodallergies?

Yes
No

64

SurveyProgrammingFundamentals
PrepTime

Chapter5BasicRoutingLogic

Onaverage,howmuchtimedoyoudevotetopreparingasinglemeal?

30minutesorless
3190minutes
Over90minutes
Dontknow

(IfPrepTimeis30minutesorless,askMealStrategy)
MealStrategy Pleaselistsomeofyourstrategiesforpreparingmealssoquickly.

(IfPrepTimeis3190minutes,askAmtPrep)
AmtPrep

Doyoufeelthatyourpreparationtimeformealsis

Tooshort
Toolong
Justright
DontKnow

(IfPrepTimeisOver90minutes,askPrepDescrip)
PrepDescrip

Doyoutakeover90minutestopreparemealsmainlybecauseof

Theamountofentreescreated
Thecomplexityofthedishes
Thenumberofinterruptionsduringtheprocess
Other(specify)______________
DontKnow

65

Chapter5BasicRoutingLogic
ItemsOwned

SurveyProgrammingFundamentals

Whichofthefollowingkitchenwareitemsdoyouown?

BreadMaker
FoodProcessor
StandMixer
Wok
FonduePot
NoneofThese

(Ifrespondentowns3ormorekitchenitemsinItemsOwned,askUseItems)
UseItems

Doyouusesome/alltheitemsmentionedpreviously

Daily
Weekly
Monthly
Yearly
Never

(IfCookAtHomeisNo,andUseItemsnotequaltoNever,askWhatUseFor)
WhatUseFor

Pleaseexplainwhatyouuseyourkitchenitemsforifyoudonotcookathome.

66

SurveyPrrogrammingFundamentalls

Chapte
er6

Chap
pter6Shared
dLists

SharedListss

Whencreeatingasurve
ey,youmayrrepeatthesameresponsessquestionaftterquestion.Usingasharred
listwillallowyoutocrreatetheresp
ponselistoncceanduseitmanytimes. Inaddition,iifchangesneed
tobemadetoyourre
esponselist,yyouhaveonecentrallocationtomaketthechangesttoupdatemany
questionsatonce.

Thisch
hapterco
overs:
Creatingareuseableressponselist

Includingssubheadingsin
nalist
Dealingwiithidenticalresponsetextintwo
ormorelissts

Creatingasharedlistisverysimilartoaddingcaategoriestoaacategoricalq
question.
LListName"Text"define
{
{ID1"AltText1
1",
IDn"AltTextn
n"};
Item
ListName
e

"Text"
Define
{}
ID1,IDn

AltText1,,
AltTextn

Desscription
Uniiqueidentifierforthesharredlistinthemetadata.TTheymuststartwitha
lettterorundersccore(_)andcontainonlyyalphanumericcharacterssorthe
sym
mbols@,$,#,,or_
Opttionaltextwh
henlistisusedasasublist.
Keyywordtocreaateasharedliist
Indicatesthestaartofthecateegoriesforthedefinelist
Uniiqueidentifyingnameforttheresponse.Thisneedstobeuniqueper
que
estion,notmeetadatafile.Rulesfortheresponsenamesarethessameasthe
nam
meofthequeestion.
Opttionaltexttoshowtheresspondentinstteadofthenaameofthequ
uestion.This
willlapplywhenthenameofthequestionisnotthesam
measthetexxtyouwishto
o
sho
owtherespon
ndent.

67

Chapter6SharedLists

SurveyProgrammingFundamentals

Tomakeuseoftheresponsesinaquestion:
Name"Text"categorical[Min..Max]
{uselistname};
Item
Name
"Text"
Categorical
[Min..Max]

Use
Listname

Description
NameoftheQuestion
Textassociatedwiththequestion(consideredthelabelintheobjectmodel).
Keywordtocreateaquestionwithcategoriesforresponsechoices.
Optionalparameters.Controlstheminimumandmaximumamountof
categoriesthatcanbechosenbyarespondent.Defaultisopentoanyamount
ofchoices.Automaticallyissuesanerrormessageifthenumberofresponses
chosenisbelowtheminimumorabovethemaximum.
Keywordtoincludethecategoriesfromadefinelistinthequestion.
Representsthenameofthedefinelisttouseforthecategoriesofthequestion.

Example

ResortTypesdefine
{
Historical,
AmusementPark"AmusementPark",
Beach,
Adventure
};

ResortStayed"Ofthefollowing,whichResorttypeshaveyoustayedatinthelastyear?"
Categorical[1..]
{useResortTypes};

Somethingstokeepinmindaboutsharedlists:

Youcanusemorethanonelistwithinthesamequestion
Youcancreatesharedliststhataremadeupofothersharedlists
Youcanuseasharedlistwithaquestioninadditiontoaddingothercategoriestothatspecific
question

68

SurveyProgrammingFundamentals

Chapter6SharedLists

CreatingSubheadingswithSharedLists
Youlearnedtocreatesubheadingsinapreviouschapter.Nowthatyouhavelearnedsharedlists,
thereisanotherwaytocreatesubheadingsusingmultiplesharedlists.
Name"Text"categorical[min..max]
{uselistname1Sublist"Sublistname1",
UselistnameNSublist"SublistnameN"};
Item
Name
"Text"
Categorical
[Min..Max]

Description
NameoftheQuestion
Textassociatedwiththequestion(consideredthelabelintheobjectmodel).
Keywordtocreateaquestionwithcategoriesforresponsechoices.
Optionalparameters.Controlstheminimumandmaximumamountof
categoriesthatcanbechosenbyarespondent.Defaultisopentoanyamount
ofchoices.Automaticallyissuesanerrormessageifthenumberofresponses
chosenisbelowtheminimumorabovethemaximum.
Use
Keywordtousethecategoriesfromadefinelist
listname1,
Representsthenameofthedefineliststouseforthesublistcategoriesofthe
listnameN
question.
Sublist
Keywordtodesignatetheprecedingdefinelistasasubheadinglist
Sublistname1, OptionalTexttodisplayasthesubheadingText.Ifnotspecified,willuselabel
SublistnameN specifiedinthedefinelist.

69

Chapter6SharedLists

SurveyProgrammingFundamentals

Thefollowingexampleusestheconceptofsublistusingtwodefineliststocreatesubheadingsinthe
categoricalquestion.

Example

Metadata(enUS,Question,Label)
ResortTypes""define
{
Historical,
AmusementPark"AmusementPark",
Beach,
Adventure
};
CampingTypes""define
{
GovtPark"GovernmentPark",
RainForest"RainForest",
River"River(Canoe/WhiteWaterRafting)",
Mountain"MountainClimbing"
};

CamporResortStayed"Ofthefollowing,whichResortshaveyoustayedatandwhattypes
ofcampinghaveyouparticipatedinthelastyear?"
Categorical[1..]
{
useResortTypessublist"Resorts:",
useCampingTypessublist"Camping:",
Noneofthese"Noneofthese"style(Indent=0)NA
};
EndMetadata

70

SurveyProgrammingFundamentals

Chapter6SharedLists

TheexampleshowsaNoneofthesechoice.Thisdemonstratesthatyoucanhaveadditional
categoriesinaquestionoutsideofanydefinelistsused.

Insteadofstatingthesubheadingtextafterthekeywordsublist,thiscouldhavebeen
placedbetweentheemptyinthedefinelists.

71

Chapter6SharedLists

72

SurveyProgrammingFundamentals

SurveyPrrogrammingFundamentalls

Chapte
er7

C
Chapter7Sor
rtingCategoriicalResponseeLists

SortingCate
egoricalR
ResponseLists

Youmayneedtochan
ngetheorderrofthecategoricalresponsesinaquesttion.Thisisssometimesdo
one
topreven
ntbiaswithin
nasurveyorssimplytoreo
orderthelistalphabetically.Thischaptterwillcoverthe
sortingoptionsformrrInterview.

Thischapterw
willshow
wyouhow
wto:
Changetheorderofyourresponselists
Usetheso
ortingcomman
ndsinboththe
metadataandroutingseections
Ensurecerrtainresponsessarenotsorteed
withinaso
ortedlist

ThetypesofsortsavaailableinmrIn
nterviewareaasfollows:
Item
Rotate

Descriptio
on
Thecatego
orylistisrotaatedbyonecategorybeforeeachpreseentationofth
he
list.
Thecatego
orylistispressentedinrandomizedordeer.
Thecatego
orylistisreveersedbeforeeachpresenttation.Thism
meansthattheelist
ispresenteedtopdowntothefirstreespondent,bottomuptotthenext,etc..
Thecatego
orylistissorttedinascendingalphabeticalorder.
Thecatego
orylistissorttedindescendingalphabeticalorder.

Randomiize
Reverse
Ascendin
ng
Descending

useanyofthe
esortingfeatturesabovein
neitherthem
metadataortheroutingseectionsassho
own
Youcanu
inthenextsections.

andomizefea
atureinthem
metadataandroutingsections
Thereisadifferencceusingthera
whenusingthesam
meresponsellistformultiplequestions. Usingthemetadatameth
hodwill
holdth
hesamepattternforeachq
questionperrespondent;ttheroutingm
methodwillch
hange
thepa
atternforeachquestion.

73

Chapter7SortingCategoricalResponseLists

SurveyProgrammingFundamentals

SortinginMetadata
TosortaquestionintheMetadatasection,useanyofthekeywordsforsortingfollowingthecurly
bracketsofacategorylist.
Name"Text"categorical[min..max]
{ID1"AltText1",
IDn"AltTextn"}sortingkeyword;

Item
Name

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
"Text"
Textassociatedwiththeitem(consideredthelabelintheobjectmodel).
categorical
Keywordtocreateaquestionwithcategoriesforresponsechoices.
[Min..Max]
Optionalparameters.Controlstheminimumandmaximumamountof
categoriesthatcanbechosenbyarespondent.Defaultisopentoanyamount
ofchoices.Automaticallyissuesanerrormessageifthenumberofresponses
chosenisbelowtheminimumorabovethemaximum.
{}
Indicatesthestartofthecategoriesyouwishtherespondenttochoosefromfor
thequestion
ID1,IDn
Uniqueidentifyingnamefortheresponse.
AltText1,
Optionaltexttoshowtherespondentinsteadofthenameofthequestion.This
AltTextn
willapplywhenthenameofthequestionisnotthesameasthetextyouwishto
showtherespondent.
sortingkeyword Representsoneofthesortingkeywordsrotateorrot;randomizeorran;reverse
orrev;ascendingorasc;descendingordesc

Intheexamplebelow,addingtherankeywordrandomizestheresponselist.

Example

Metadata(enUS,Question,Label)

Souvenirs"Whichofthefollowingsouvenirsdoyouprefertopurchasewhenonholiday
orvacation?"

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

EndMetadata

74

SurveyProgrammingFundamentals

Chapter7SortingCategoricalResponseLists

RoutingSectionSorting
Intheroutingsection,thesyntaxforsortingis:
Name.Categories.Order=orderconstants.osortingkeyword
Item
Description
Name
Representsthenameofthequestiontosort
Osortingkeyword RepresentsoneofthesortingkeywordsoAscending,oDescending,oCustom,
oRandomize,oReverse,oroRotate.

Routing(Web)
Example

Souvenirs.Categories.Order=orderconstants.oAscending
Souvenirs.Ask()

EndRouting

TheabovestatementwillsortthelistalphabeticallyAtoZ.

NotSortingSpecificResponses
Theremaybecertainresponsesthatyoudonotwantsortedwithinalist,suchasNoneofTheseor
AllofThese.Toforceagroupofcategoriestoretainitsoriginalpositionwhentheoverallcategory
listissorted,usethekeywordfix.
Name"Text"categorical[min..max]
{ID1"AltText1"fix,
IDn"AltTextn"}sortingkeyword;
Item
Fix

Description
Keywordtomakethecategorypriortothekeywordfixedinitsoriginalposition,
regardlessofthesortorder
sortingkeyword Representsoneofthesortingkeywordslistedintheprevioussection(example
ran)

75

Chapter7SortingCategoricalResponseLists

SurveyProgrammingFundamentals

ThefollowingexamplewillnotsorttheNoneoftheseoption;itwillstayatthebottomofthelist.In
addition,theOtherresponseswillalwaysbethelastintheseriesofitemsfortheirindividuallists.

Example

Metadata(enUS,Question,Label)
TravelHelp"Haveyouusedanyofthefollowingtohelpyouwithyourtravel
arrangements?"
Categorical[1..]
{
TravelBooks"TravelBooks"
{
LonelyPlanetBook"LonelyPlanet",
Fodor"Fodor's",
Frommer"Frommer's",
otherBooks"OtherTravelBook"otherfix
}ran,
Websites
{
Expedia,
Orbitz,
Govt"GovernmentWebsites",
otherwebsite"OtherWebsite"otherfix
}ran,
Noneofthese"Noneofthese"style(indent=0)fixexclusive
}ran;
EndMetadata

ThisalsodemonstratesastylebeingusedtoforcetheNoneoftheseresponsetobelinedupwith
theSubheadingsinsteadofindented(indent=0).YouwilllearnmoreaboutstylesinChapter13
ControllingtheLookofYourSurvey.

76

SurveyProgrammingFundamentals

Chapter7SortingCategoricalResponseLists

KeepingSpecificCategoriesGroupedTogether
Youmayneedtokeeppairsorgroupsofcategoriestogetherwithinalist,evenwhenadding
randomization.Youcanachievethisbycreatingasublistwiththeitemsthatneedtobekepttogether,
whilerandomizingthemainquestion.TheexamplebelowwillrandomizetheTypeAccomquestionbut
alwayskeeptheresponsesinthedefinelistresortstogether.

Example

Metadata(enUS,Question,Label)

Resortsdefine
{
FamilyResorts"FamilyResorts",
CouplesResorts"CouplesResorts"
};

TypeAccom"Atwhattypeofaccommodationsdidyoustay?"
categorical[1..1]
{
Hotel,
Motel,
BedBreakfast"BedandBreakfast",
Hostels,
useResortssublist,
OtherAccom"OtherAccommodations"otherfix
}ran;

EndMetadata

77

Chapter7SortingCategoricalResponseLists

SurveyProgrammingFundamentals

Exercise
UpdatethefollowingquestionsbyaddingthefeatureshighlightedbelowinyourGroceryBill.mddfile
toincludesortedcategories.
StoreName

Whatwasthenameofthestoreinwhichyoushopped?(RANDOMIZE)

Walmart
Safeway
Kroger
Albertsons
AholdUSA
Delhaize
Publix
WinnDixie
Other(Specify)______________

ItemTypes

Whichofthefollowingcategoriesofgroceriesdidyoupurchaseonthisshoppingtrip?

(RANDOMIZEBOTHTHEGROUPSANDTHEITEMSWITHINTHEGROUPS)
PreparedFoods

Cheese/OliveBar

SaladBar

DeliItems
NonPreparedFoods

Meat/Seafood

Produce

CannedGoods

Pasta/Grains

NoneofThese

78

SurveyPrrogrammingFundamentalls

Chapte
er8

Ch
hapter8ResttrictingRespo
onses

Re
estrictingResponse
es

Thelogiccbehindthessurveyisanim
mportantparttofresearchtoensureacccuratedata.Inthissection,
wecanleearnhowtop
presentthereespondentwiithlogicalcho
oices.

Inthischapterw
wewill:
Filterresponsesdisplayeedonaquestio
on
previousansweerstoquestion
ns
basedonp
Filterresponsesbasedonyourinternallogic
Limitthem
maximumorm
minimumamou
unts
fornumericquestionsbaasedonlogic

FilterC
Categoriess
TheFilterrpropertycanbeusedtolimitthecateegoriesdisplaayedbyaquestionintheroutingsection.
Routing(Web)
R
Name.Categories.Filter==condition
Name.Ask())
E
EndRouting

Item
Name
Categorie
es
Filter
condition
n

Desscription
Uniiqueidentifierforthequesstionname.
Pro
operty(keywo
ord)ofthequ
uestiondenottingtherespo
onses
Pro
operty(keywo
ord)tostateyyouarerestrictingthecateegoriesforth
hequestion
Rep
presentsanytthingthatstattesthecategoriestodisplayforthequestion

79

Chapter8RestrictingResponses

SurveyProgrammingFundamentals

Hereisanexampleinwhichweareaskingrespondentstochooseallthehotelchainstheyhavestayed
inthepastyear.ThefollowupquestionisOfthosechains,whichisyourfavorite?Theresponselist
forthefollowupquestionisrestrictedtoonlytheanswersgiveninthefirstquestion.

Example

Metadata(enUS,Question,Label)

HotelChainStayed"Choosethehotelchainsyouhavestayedatthispastyear."
categorical[1..]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow"DontRemember"DK,
Refused"PrefernottoAnswer"REF
};
FavHotelChain"Ofthosechains,whichonewouldyoumostprefertostayatagain?"
categorical
[1..1]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow"DontRemember"DK,
Refused"PrefernottoAnswer"REF
};

EndMetadata

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

EndRouting

80

SurveyProgrammingFundamentals

Chapter8RestrictingResponses

Ifyouchoose:

Theresultwillbe:

SpecialResponsesofDK,REF,andNAarenotfilteredoutautomatically.Inaddition,ifany
ofthosespecialresponsesarechosen,itskipsthefilteredquestion.

81

Chapter8RestrictingResponses

SurveyProgrammingFundamentals

Howdoestheabovework?ThefiltersarebasedontheNAMESoftheresponses.Whileitisnot
necessarytousesharedlistsforfiltering,itisagoodpracticewhentheresponselistsareidenticalto
ensurethatthenamesarealsoidentical.
YoudoNOTneedtohavethelistsidenticaltofilteronequestionoffanother.mrInterviewwillsimply
matchwhatitcananddisregardstherest.Forinstance,whatifourlistsweredifferent:

Example

HotelChainStayed"Choosethehotelchainsyouhavestayedatthispastyear."
categorical[1..]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow"DontRemember"DK,
Refused"PrefernottoAnswer"REF
};

FavHotelChain"Ofthechainslistedbelowinwhichyoustayed,whichonewouldyou
mostprefertostayatagain?"categorical
[1..1]
{
Accor,
Choice,
Hilton,
DontKnow"DontRemember"DK,
Refused"PrefernottoAnswer"REF
};

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

82

SurveyProgrammingFundamentals

Chapter8RestrictingResponses

Ifyouchoose:

Theresultis:

Asyoucansee,eventhoughInterContinentalwaschosen,itdoesnotshowinthelist,sinceitisnot
partofthecategoriesinFavHotelChain.

Theaboveexamplesassumeanamingconventionforyourcategorynames.Thisis
recommendedasnamesthatidentifytheresponsemakemoresenseacrosstheentire
projectlifecycle.

83

Chapter8RestrictingResponses

SurveyProgrammingFundamentals

Additionally,thefilterdoesnotneedtobeasinglequestion.Thiscanbeamultitudeofconditions,
suchasDimensionsfunctionsorspecificcategories.
Supposeourpreviousexamplewasslightlydifferent.Whatifwehadtwoseparatequestionsthat
collectedthehotelsstayedinthepastyear.Wewillneedtwofilterstatements:

Filtertheresponsefromthefirstquestionsothatitcannotbechosenfromthe2ndlist
Filtertocombineboththefirstresponseandthe2ndresponseforthefinalquestion

Example

84

HotelChainStayMost"ChoosethehotelchainyouhavestayedattheMOSTthispast
year."
categorical[1..1]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow"DontRemember"DK,
Refused"PrefernottoAnswer"REF
};

HotelChainStayed"Choosetheotherhotelchainsyouhavestayedatthispastyear."
categorical[1..]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
DontKnow"DontRemember"DK,
Refused"PrefernottoAnswer"REF
};

FavHotelChain"Ofthechainslistedbelowinwhichyoustayed,whichonewouldyou
mostprefertostayatagain?"
categorical[1..1]
{
Accor,
Choice,
Hilton,
DontKnow"DontRemember"DK,
Refused"PrefernottoAnswer"REF
};

SurveyProgrammingFundamentals

Chapter8RestrictingResponses

Routing(Web)
HotelChainStayMost.Ask()

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

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

SeetheDimensionsDevelopmentLibraryformorecategoricalfunctionstohelpwithfilters,
suchasDifferenceandIntersection)DDL.chm::/categorical_functions.htm

85

Chapter8RestrictingResponses

SurveyProgrammingFundamentals

LimitingNumericQuestionRangesBasedonLogic
Anotheraspectofaccuratedataistobeabletosettheminimumormaximumamountthatcanbe
enteredforanumericresponsebasedoffpreviousanswersfromtherespondent.Youcancontrolthe
minimumandmaximumvaluesforaquestionwiththefollowingstatementsintheroutingsection.
Name.Validation.MinValue=condition
Name.Validation.MaxValue=condition
Item
Name
Validation
MinValue

MaxValue

Condition

Example

Description
Metadataitemname
Propertyofquestions
Propertytocontroltheminimumvalueallowedforanumericquestion.Takes
precedenceoverwhatisstatedastheminimuminsquarebracketsonthe
question.
Propertytocontrolthemaximumvalueallowedforanumericquestion.Takes
precedenceoverwhatisstatedasthemaximuminsquarebracketsonthe
question.
Representsthenewvaluefortheminimumormaximumlimits

Metadata(enUS,Question,label)

AmtSpentonHoliday"Approximatelyhowmuchintotaldidyouspendlastyearonyour
holidays/vacations?"long[0..10000];

AmtSpentAir"Andofthatamount,howmuchwasspentonairfares?"long[0..10000];

EndMetadata

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

86

SurveyProgrammingFundamentals

Chapter8RestrictingResponses

Ifyouanswered5000forthequestionAmtSpentonHoliday,thentriedtosubmitananswergreater
than5000forAmtSpentAir,youwouldseethefollowing:

87

Chapter8RestrictingResponses

SurveyProgrammingFundamentals

Exercise
CreateanewmetadatafilecalledMealsOut.mdd.Makesurethat:

YoumakesharedlistsforAmericanCuisine,InternationalCuisine,andrestaurantattributes.
FavCuisineonlydisplaysthecuisinestherespondenthasevereaten.
TheanswertoEatMealOutisnotgreaterthantheOrderMealOutamount.
MakethefilterfortheRestaurantOthrquestionbetheresponsesnotchoseninRestaurant1.
Inaddition,theotherspecifychoiceshouldshowinRestaurantOtherregardlessifitwas
choseninRestaurant1.

CuisineEaten

WhichofthefollowingtypesofCuisinehaveyouevereaten?
AmericanCuisine

Barbecue

Cajun

Southern

Southwestern
InternationalCuisine

Italian

Russian

Polish

French

Caribbean

NoneofThese

FavCuisine

Ofthosementioned,whichonedoyouprefer?
AmericanCuisine

Barbecue

Cajun

Southern

Southwestern
InternationalCuisine

Italian

Russian

Polish

French

Caribbean

NoneofThese

OrderMealOut Onaverage,howmanymealsperweekdoyouorderfromarestaurant?

(IfzerotoOrderMealOut,skiptoThanks)

88

SurveyProgrammingFundamentals

Chapter8RestrictingResponses

EatMealOut Ofthosemeals,howmanydoyoueatattherestaurant,asopposedtohomedeliveryor
carryout?

(IfzerotoEatMealOut,skiptoThanks)

Restaurant1Whenyoueatatarestaurant,whatonethingmakesyouwanttoreturntotherestaurant
again?

Goodfood
Goodservice
NiceAtmosphere
LargeSelectionofmenuchoices
Other(Specify)________________________

RestaurantOthrWhatotherfactorsalsoinfluenceyourdecisiontoreturntoarestaurant?

Goodfood
Goodservice
NiceAtmosphere
LargeSelectionofmenuchoices
Other(Specify)________________________

Thanks

Thankyouforyourinput.

89

Chapter8RestrictingResponses

90

SurveyProgrammingFundamentals

SurveyPrrogrammingFundamentalls

Chapte
er9

Chapter9M
MultipleQuesttionsonOnePage

Mu
ultipleQu
uestionso
onOnePa
age

BydefaultmrInterview
wdisplayson
nequestionpeerscreen.Th
herewillbetimeswhenyo
ouwillwantto
displaym
multiplequesttionsonthessamescreen.

Inthischapterw
wewill:
Learntoplacemultipleq
questionsonth
he
samescreeen
Discusstheedifferencesb
betweenpagessand
blocks
Learntoco
ontrolifaquesstionispresentedon
thescreen
norinwhatord
der.

placemultiple
equestionso
onthesamesscreenbyusin
ngpageorblo
ockstatemen
nts.
Youcanp

Pagemetadattaitemsreferrenceotherquestionsinth
P
hemetadatatogroupthem
monthesam
me
s
screen.Ifyou
uareonlytryiingtopresenttmorethano
onequestiononascreen,useapage.
B
Blockmetada
taitemsconttainotherqueestions,similartohowaggridquestioncancontain
m
multipleques
tions.Theblocktypecan
nbeusedtoggroupalistoffquestionsfo
orpresentatio
on
a
andorganizat
tionalpurposees.Forexamp
ple,ifyouareetryingtogro
oupquestionsstogetherforruse
w
withtheanaly
ysisproductsmrTablesand
dDesktopReeporter.

91

Chapter9MultipleQuestionsonOnePage

SurveyProgrammingFundamentals

Page
Creatingapageinmetadatacreatesametadataitemthatstatesthequestionsyouwantdisplayedon
ascreenandtheorderinwhichtheyshouldbedisplayed.
Inthemetadatasection:
Name"text"page(QuestionName1,QuestionName2,QuestionNameN);
Item
Name

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
"text"
Optionaltexttoshowonthetopofthescreen
page
Keywordtostatewearegroupingthefollowingquestionsonthesamepage
QuestionName1, Representsthequestionnamestodisplayonthepagetogether.
QuestionName2,
QuestionNamen

Intheroutingsection,askthepage,nottheindividualquestions:
Name.Ask()
Item
Name
.Ask()

Description
Nameofthepagemetadataitem
Askthequestionslistedinthepageitem

Ifyouhavemanypagestocreate.Askstatementsfor,inthemetadataviewerchoosethe
Pagefolder.RightclicktochooseCopyasAsk.

92

SurveyProgrammingFundamentals

Chapter9MultipleQuestionsonOnePage

Thefollowingisanexampleshowingmultipledemographicquestionsonthesamescreen.

Example

Metadata(enUS,Question,label)
HouseHold"Includingyourself,howmanypeoplecurrentlyliveinyourhousehold?"
long[1..99];

Age"Towhichofthefollowingagecategoriesdoyoubelong?"
Categorical[1..1]
{
Under18"Under18",
_18to34"18to34",
_35to54"35to54",
_55plus"55andover",
Refused"PrefernottoAnswer"REF
};

Participate"Checkhereifyouwishtoparticipateinfuturestudiesontravel."
boolean;

Demos"Nowafewdemographicquestions"
page(
HouseHold,
Age,
Participate
);
EndMetadata

Routing

Demos.Ask()

EndRouting

93

Chapter9MultipleQuestionsonOnePage

SurveyProgrammingFundamentals

Willdisplayas:

Block
Blocksaremetadataitemsthatcontainthequestionsyouwantdisplayedtogetheronascreen.
Name"text"blockfields

QuestionName1"text"QuestionType;

QuestionNamen"text"QuestionType;

);

94

SurveyProgrammingFundamentals

Chapter9MultipleQuestionsonOnePage

Item
Name
"text"
block
fields
QuestionName1,
QuestionNamen

Description
Representsthenameoftheblock
Optionaltexttoshowonthetopofthescreen
Keywordtoidentifytheitemasablock
Startofthequestionscontainedintheblock
Representsthequestionscontainedinsidetheblock

Intherouting,asktheblockname:
Name.Ask()
Item
Name
.Ask()

Description
Nameoftheblockmetadataitem
Askthequestionslistedintheblockitem

Asyoucanseeinthefollowingexample,blocksarelikecontainerswhichholdmultiplequestions.

Example

Metadata(enUS,Question,label)
Demos"Nowafewdemographicquestions"blockfields

HouseHold"Includingyourself,howmanypeoplecurrentlyliveinyourhousehold?"
long[1..99];

Age"Towhichofthefollowingagecategoriesdoyoubelong?"
categorical[1..1]
{
Under18"Under18",
_18to34"18to34",
_35to54"35to54",
_55plus"55andover",
Refused"PrefernottoAnswer"REF
};

Participate"Checkhereifyouwishtoparticipateinfuturestudiesontravel."
boolean;

);
EndMetadata

Routing
Demos.Ask()
EndRouting

95

Chapter9MultipleQuestionsonOnePage

SurveyProgrammingFundamentals

Thepreviouscodewilllookidenticaltothepageexamplewhenviewedinthebrowser.However,the
metadataitselfisverydifferent.Theblockcreatesaseparateitemforblocks,asseeninthemetadata
viewer:

Sinceyourquestionsarenowcontainedwithinablock,thiswillalsoaffecthowyourefertoaquestion
inablock.
Blockname.Name

96

SurveyProgrammingFundamentals

Chapter9MultipleQuestionsonOnePage

Thefollowingexampleshowshowyouwouldrefertoquestionsinablockwithintheroutingsection.

Example

Metadata(enUS,Question,label)
AgeGroups""define
{
Under18"Under18",
_18to34"18to34",
_35to54"35to54",
_55plus"55andover"};

Demos"Nowafewdemographicquestions"blockfields

HouseHold"Includingyourself,howmanypeoplecurrentlyliveinyourhousehold?"
long[1..99];

Age"Towhichofthefollowingagecategoriesdoyoubelong?"
categorical[1..1]
{useAgeGroups,
Refused"PrefernottoAnswer"REF
};

Participate"Checkhereifyouwishtoparticipateinfuturestudiesontravel."
boolean;

);

KidsAtHome"Doyouhaveanychildrenundertheageof18livinginyourhousehold?"
categorical[1..1]
{
Yes,
No
};

EndMetadata

Routing
Demos.Ask()

IfDemos.household.Response.Value>1then
KidsAtHome.Ask()
Endif
EndRouting

97

Chapter9MultipleQuestionsonOnePage

SurveyProgrammingFundamentals

ControllingHowPageandBlockQuestionsareDisplayed
Youcancontrolthepageorblockquestionsaskedonthescreenby:

Filteringthepageorblock
Usingasortingkeywordonthepage/block

FilteringaPage/Block
Usingthesameprincipleswelearnedwithfiltering,wecanuseaQuestionFiltertorestrictthe
questionsshowntocertainrespondents.
Name.QuestionFilter=Question1,QuestionN
Item
Name
QuestionFilter
question1,
questionN

Description
Nameofthegrid/loopquestion
Property(keyword)tostateyouarerestrictingthequestionsofthepage,or
block.Thispropertyalsoappliestogrid/loopcategories.
Representsquestionsthatwillbeaddedtothequestionfilterandshownonthe
screen.

Thefollowingwillnotshowthequestionaskingtoparticipateinfuturestudiesiftheyarealreadya
memberofourpanelgroup.

Example

98

Metadata(enUS,Question,label)

Membership"Areyoucurrentlyamemberofourpanel?"
Categorical[1..1]
{
Yes,
No
};

HouseHold"Includingyourself,howmanypeoplecurrentlyliveinyourhousehold?"
long[1..99];

Age"Towhichofthefollowingagecategoriesdoyoubelong?"
categorical[1..1]
{
Under18"Under18",
_18to34"18to34",
_35to54"35to54",
_55plus"55andover"
Refused"PrefernottoAnswer"REF
};

SurveyProgrammingFundamentals

Chapter9MultipleQuestionsonOnePage

Participate"Checkhereifyouwishtoparticipateinfuturestudiesontravel."
boolean;

Demos"Nowafewdemographicquestions"
page(
HouseHold,
Age,
Participate
);
EndMetadata

Routing(Web)

Membership.Ask()

IfMembership={Yes}thenDemos.QuestionFilter=Household,Age
Demos.Ask()

EndRouting

SortingaPage/Block
Youcancontroltheorderofthequestionswiththesamesortingoptionsasshownpreviously.Simply
applythesortkeywordtotheblockorpagename.
Thefollowingexamplewouldrandomizethequestionsshownonthescreenforthedemospageor
block.

Example

Routing(Web)

'UsingDemosfromthepreviousexamples

Demos.QuestionOrder=OrderConstants.oRandomize

Demos.Ask()

EndRouting

99

Chapter9MultipleQuestionsonOnePage

SurveyProgrammingFundamentals

Exercise
OpentheGroceryBill.mddfileandSaveAsCH09GroceryBill.mdd.ModifyCH09GroceryBill.mddsothat:

100

GroceryDateandStoreNameareonthesamepageusingaPAGEstatement
Generic,ItemsBought,andGroceryCostarecontainedwithinaBLOCKitem
Reviewthemetadatafortheblocktoseehowithaschanged

Chapter10RepettitiveQuestio
onsLoops&Grids

SurveyPrrogrammingFundamentalls

Chapte
er10 Re
epetitiveQ
QuestionssLoops&
&Grids
Manysurrveysinvolvetheconceptofaskingthesamebasicq
questionwith
hdifferentatttributesmultiiple
times.Th
heconceptissometimesccalledagrido
oraloop.

Inthischapterw
wewill:
Understan
ndwhentouseeagridoraloo
opina
survey
Createmeetadataforgrid
dsandloops

Reviewdiffferenttypeso
ofgrids/loops

Ifyourqu
uestionnairecontainsaseriesofquestiionsthatlookksimilartoth
his:
Pleaseraatethefollow
wingtravelde
estinationsonyourintere
estinvisitingthelocation.
Extremely
Someewhat
Somewhat
Extremely

Aruba
Bermudaa
Florida
Hawaii
Fiji
CostaRicca
Thailand

Interestted

Interrested

N
Neutral

D
Disinterested

Disinterested
d

{
{
{
{
{
{
{

{
{
{
{
{
{
{
{
{
{
{
{
{
{

{
{
{
{
{
{
{

{
{
{
{
{
{
{

{
{
{
{
{
{
{

eofwhentousetheloop//gridmetadattaitem.Thepropertiesth
hisquestionh
has
Thisisaggoodexample
thatmakkeitaloop/grridare:

Allsharethessameresponsses(ExtremelyInterested,SomewhatIn
A
nterested,etcc.)
D
Duringanalys
is,wewillwaanttoseetheeresultsofeaachdestinatio
onseparately,,butperhapsswill
a
alsowanttos
seetheresulttsinsummaryyintheformaattheyappeaarinabove.

Youwillaalsoneedtod
decideifyouwanttohaveetheappearaanceofthequ
uestionstobeeexactlyasw
we
seethem
mabove(i.e.,o
onthescreen
nallatonce),orwouldweepreferthateeachquestion
nbeona
separatescreen(i.e.,""PleaserateA
Arubaonyou
urinterestinvvisiting.,PleaserateBermudaonyour
interestinvisiting.,etc.,")

101

Chapter10RepetitiveQuestionsLoops&Grids

SurveyProgrammingFundamentals

CategoricalLoops/Grids
Wewilldefinecategoricalloop/gridsnotbythetypeofquestionstheydisplay,butbywhatdefinesthe
numberoftimesyourepeatthequestions.Thefirstexampleswillshowalistofcategoriesdefining
thenumberoftimesyouwillshowthequestioninaloop/grid.
Name"GridText"loop
{

ID1"AltText1",
IDn"AltTextn"
}fields
(

Question1"LoopText1{@}";
Questionn"LoopTextn{@}"
)expandgrid;

Item
Name
"GridText"
Loop
ID1"AltText1",
IDn"AltTextn"
Fields
Question1,
Questionn
LoopText1,
LoopTextn
{@}
expand

grid

column

102

Description
Uniqueidentifierforloop/grid
Optionaltextthatwillbedisplayedwhenthequestionsintheloopareasked
togetherononescreen.
Keywordtomarkasetofrepeatedquestionsanddefinethenumberof
repetitionsrequired.
Definesthecategorylistthatcontrolsthenumberofrepetitionsrequired.You
defineitinthesamewayasthecategorylistforacategoricalquestion.
Keywordpriortothequestionstoberepeatedintheloop
Questionsthatwillberepeatedbasedonthecategorylist(ID1,ID2).
Definesanoptionallabelthatwillbedisplayedwhenthequestionsintheloop
areaskedonindividualscreens.
Representsthecurrentcategorytodisplaywhenthequestionsintheloopare
askedonindividualscreens.
SincemrInterviewsupportsbothahierarchicalandaflattenedviewofthe
data,usingtheexpandkeywordmeansthatthedataisrepresentedinboth
formats(bounded).
KeywordthatallowsSPSSDimensionsapplicationsandcomponentsto
recognizethattheloopisagrid.Examplewouldbeprintinggridsusing
mrPaper.
Optionalkeywordtochangetheorientationofthecategorylisttobethe
columnsofthegridinsteadoftherows.(Keywordrowisthedefault.)Is
placedontheendofthemetadatapriortothesemicolon.

SurveyProgrammingFundamentals

Chapter10RepetitiveQuestionsLoops&Grids

Hereisthesyntaxforthegridshownatthebeginningofthischapter.

Example

Metadata(enUS,Question,label)

InterestinLocation"Pleaseratethefollowingtraveldestinationsonyourinterestin
visitingthelocation."loop
{
Aruba,
Bermuda,
Florida,
Hawaii,
Fiji,
CostaRica,
Thailand
}fields
(
Rating""
categorical[1..1]
{
ExtremelyInterested"ExtremelyInterested",
SomewhatInterested"SomewhatInterested",
Neutral"Neutral",
SomewhatDisinterested"SomewhatDisinterested",
ExtremelyDisinterested"ExtremelyDisinterested"
};

)expandgrid;

EndMetadata

Routing(Web)

InterestinLocation.Ask()

EndRouting

103

Chapter10RepetitiveQuestionsLoops&Grids

SurveyProgrammingFundamentals

Inthepreviousexample,sinceweaskedthequestionusingtheloopname.Ask(),thesurveywillappear
inthisformat:

Thisiswhatthismanualwillrefertoasagridformat.

Ifyouwanttochangetheorientationsothatthedestinationsareacrossthetopofthe
screen,addthekeywordcolumnafterthegridkeyword.

104

SurveyProgrammingFundamentals

Chapter10RepetitiveQuestionsLoops&Grids

IfweaddtexttotheRatingquestionmetadataandchangethestatementintherouting:

Example

Metadata(enUS,Question,label)

InterestinLocation"Pleaseratethefollowingtraveldestinationsonyourinterestin
visitingthelocation."loop
{
Aruba,
Bermuda,
Florida,
Hawaii,
Fiji,
CostaRica,
Thailand
}fields
(
Rating"Pleaserate{@}onyourinterestinvisiting."
categorical[1..1]
{
ExtremelyInterested"ExtremelyInterested",
SomewhatInterested"SomewhatInterested",
Neutral"Neutral",
SomewhatDisinterested"SomewhatDisinterested",
ExtremelyDisinterested"ExtremelyDisinterested"
};

)expandgrid;

EndMetadata

Routing(Web)

InterestinLocation[..].Ask()

EndRouting

105

Chapter10RepetitiveQuestionsLoops&Grids

SurveyProgrammingFundamentals

Thenthesurveywillcomeuponequestionatatimeonthescreen.Thefirsttimeyouwillsee:

Afewthingstorememberaboutthepreviousexample:

Themaingridtext(textpriortothekeywordloop)willnotshowwhenthequestionsareasked
onindividualscreens.
The{@}willshowthelabelofthecurrentcategory,inthiscase,thedestinations.
The[..]indicatesthatyouwanttostepthrougheachvalueinyourcategoricallooponeata
time.

Iftheaboveisnotclear,thinkabouthowyouwoulddisplayjustoneofthequestionsinthe
loop:InterestinLocation[{Aruba}].Ask()

ForEachloops
Analternativewaytowrite[..]andstillhavethequestionscomeupindividuallyonthescreenwould
beusingaForEachloopstatement.
Dimvar
ForeachvarinLoopName
var.Ask()
Next

106

SurveyProgrammingFundamentals

Chapter10RepetitiveQuestionsLoops&Grids

Item
Dim
var
LoopName
ForEach
Next

Description
Declaresatemporaryvariabletobeusedwithintheroutingsection
Representsatemporaryvariablenameyoucreate
Nameofourmetadataloop/grid
Marksthestartandendofaloop.Inthiscase,theloopisdoingwhatsinside
thefor/nextforeachquestioninanotherelement.Inthiscaseour
metadataloop/grid.EachtimethroughtheForEach/Next,varwillbethe
individualquestionsoftheloop/gridandwillbeaskedbythevar.Ask()
statement.

HereisthepreviousexamplewrittenwithaForEach/Nextloopinsteadofthe[..]syntax.Thiswill
displaythesameinthebrowserasthepreviousexample.

Example

Metadata(enUS,Question,label)

InterestinLocation"Pleaseratethefollowingtraveldestinationsonyourinterestin
visitingthelocation."loop
{
Aruba,
Bermuda,
Florida,
Hawaii,
Fiji,
CostaRica,
Thailand
}fields
(
Rating"Pleaserate{@}onyourinterestinvisiting."
categorical[1..1]
{
ExtremelyInterested"ExtremelyInterested",
SomewhatInterested"SomewhatInterested",
Neutral"Neutral",
SomewhatDisinterested"SomewhatDisinterested",
ExtremelyDisinterested"ExtremelyDisinterested"
};

)expandgrid;

EndMetadata

107

Chapter10RepetitiveQuestionsLoops&Grids

SurveyProgrammingFundamentals

Routing(Web)
Dimlocation

ForeachlocationinInterestinLocation
location.Ask()
Next

EndRouting

Tohelpunderstandthis,whenrunningthiscodestopononeoftheloopquestionsand
choosetheExpressionstabandEvaluatelocation.QuestionFullName.Oryoucanchoose
theLocalspaneandlookatthecurrentvalueoflocation.

TheForEach/Nextloopwillprovehelpfulinmorecomplexscenarios.

CategoricalLoopswithaNumericQuestion
Anotherexamplewillshowchangingthetypeofquestionintheloop.Thismetadataexampledisplays
numericquestionsinsteadofacategoricalscale.
ExpenseCategoriesdefine
Example

{Transportation,
Accomodations,

FoodDrink"FoodandDrinks",
OtherMisc"OtherMiscellaneous"
};
BusTravelSpent"Inthepastyear,approximatelyhowmuchdidyouspendineach
categorylistedbelowforbusinesstravel?"loop
{useExpenseCategories}fields
(
BusTravel"AmountSpentonBusinessTravel"
long[0..];
)expandgrid;

108

SurveyProgrammingFundamentals

Chapter10RepetitiveQuestionsLoops&Grids

Woulddisplayinthebrowserlikethis:

Youcanalsohavemultiplequestionswithinagrid.Thefollowingexampleexpandsonthelast
exampletoincludetwocolumnsofnumericboxesonthescreen:

Example

Metadata(enUS,Question,label)

ExpenseCategoriesdefine
{Transportation,
Accomodations,
FoodDrink"FoodandDrinks",
OtherMisc"OtherMiscellaneous"
};

TravelSpent"Inthepastyear,approximatelyhowmuchdidyouspendineachcategory
listedbelowforbusinessandleisuretravel?"loop
{useExpenseCategories}fields
(
BusTravel"BusinessTravel"
long[0..];

LeisureTravel"LeisureTravel"
long[0..];

)expandgrid;

Routing
TravelSpent.Ask()
EndRouting

109

Chapter10RepetitiveQuestionsLoops&Grids

SurveyProgrammingFundamentals

110

SurveyProgrammingFundamentals

Chapter10RepetitiveQuestionsLoops&Grids

NumericLoops
Anotherwaytocreaterepetitivequestionsinagrid/loopistocreatealoopinwhichyousetanumber
torepresenttheloopdriver.
Name"GridText"loop[n1..n2]
fields
(

Question1"LoopText1{@}";
Question2"LoopText2{@}"
)expandgrid;

Item
Name
"GridText"
Loop
[n1..n2]
Fields
Question1,
Questionn
LoopText1,
LoopTextn
{@}
Expand

Grid

Description
Uniqueidentifierforloop/grid
Optionaltextthatwillbedisplayedwhenthequestionsintheloopareasked
togetherononescreen.
Keywordtomarkasetofrepeatedquestionsanddefinethenumberof
repetitionsrequired.
Definesthenumberoftimesyouwantthelooptoexecute.
Keywordpriortothequestionstoberepeatedintheloop
Questionsthatwillberepeatedbasedonthecategorylist(ID1,ID2).
Definesanoptionallabelthatwillbedisplayedwhenthequestionsintheloop
areaskedonindividualscreens.
Representsthecurrentcategorytodisplaywhenthequestionsintheloopare
askedonindividualscreens.
SincemrInterviewsupportsbothahierarchicalandaflattenedviewofthe
data,usingtheexpandkeywordmeansthatthedataisrepresentedinboth
formats.
DisplaythequestionasagridwhenthequestionisprintedusingmrPaper.No
effectinbrowserbasedinterviews.

Thecategoriesshowninpreviousloopexamplesarereplacedwithnumbers.Therearevariouswaysto
specifythenumberswhichwillrepresenttherepetitionsoftheloop.
Description
Ranges
SingleValues
StepValues
ExclusiveValues

Example
[1..10]
[1,5,10]

Results
Willdisplaythequestioninthegrid/loop10times
Willdisplaythequestionsinthegrid/loop3times,eachtime
representingoneofthenumberslisted
[1..10step2] Willdisplaythequestionsinthegrid/loop5times,eachtime
representinganoddnumber1to9.
[1..10^5]
Willdisplaythequestions9times,eliminatingthe5thtime.

111

Chapter10RepetitiveQuestionsLoops&Grids

SurveyProgrammingFundamentals

Thefollowingwillproduceapairofquestionsaskedabouttherespondentslastthreetrips.

Example

Metadata(enUS,Question,label)

Last3Trips"Pleasethinkaboutthelastthreetimesyoutraveledforbusinessorpleasure
andanswerthefollowingquestions."loop[1..3]fields
(
BusorLeis"TellusaboutTrip#{@}.Wasthistripfor..."
categorical[1..1]
{
Business,
Leisure,
Both
};

Accommodations"WhenyouweretravelingonTrip#{@},whichofthefollowingtypes
ofaccommodationsdidyoustay?"
categorical[1..]
{
Hotel,
Motel,
BedBreakfast"BedandBreakfast",
Hostels,
Resorts,
OtherAccom"OtherAccomodations"other
};

)expandgrid;

EndMetadata

Routing(Web)

Last3Trips[..].Ask()

EndRouting

112

SurveyProgrammingFundamentals

Chapter10RepetitiveQuestionsLoops&Grids

Thefirsttimethroughtheloopyouwillsee:

113

Chapter10RepetitiveQuestionsLoops&Grids

SurveyProgrammingFundamentals

Exercise
Createanewmetadatafile,Meals.mddforthisexercise.

Thinkbacktothelastthreemealsofbreakfast,lunch,anddinnerthatyouconsumed.
(ASKMEALTIME&MEALORIGINABOUTEACHMEAL.)

MealTime

Thinkingaboutthelast[INSERTMEAL]youhad,whattimedidyoueat[INSERTMEAL]?

MealOrigin

Wasyour[INSERTMEAL]

Madeathome
Purchasedfromarestaurant

Calories

Howmanycaloriesdoyouestimateyourlastthreemealsofbreakfast,lunchanddinner
contained?
Breakfast
Lunch
Dinner

HealthAttribs Pleasestateyourlevelofagreementwiththefollowingstatements

Strongly
Agree

Breakfastisthemostimportantmealoftheday
Eatingfastfoodcanbehealthy
Ihaveawellbalanceddiet
Idonteatalotofsugar

{
{
{
{

Agree Neutral Disagree


{
{
{
{

{
{
{
{

{
{
{
{

Strongly
Disagree
{
{
{
{

HealthComm Pleaseaddanyadditionalcommentsyouhaveabouttheimportanceofhealthyfoods
inrestaurants.

114

SurveyPrrogrammingFundamentalls

Ch
hapter11DeebuggingToolswithinmrStudio

Chapte
er11 De
ebuggingToolswitthinmrSttudio
Nowthattwearestarttingtolearnm
morecomplexxquestiontypes,weneed
dtohavesom
meproblem
solvingskkills.mrStudiioprovidesm
manytoolstohelpyouincreatingmorecomplexsurveys.

Inthischapterw
wewill:
Reviewconceptstohelp
pyoutroublesh
hoot
yourscriptt
Createtestdatawithinm
mrStudio

Createyou
urownmacross

owhichmayh
helpyouinteestingyoursccriptsaretheabilityto:
SomeoftheitemswitthinmrStudio

HavemrStudioproducetestdataforreview.
H
S
Setpointswit
thinyourscrip
ptthatthesu
urveywillstop
ptheactionaasyouaretesstingtoallowyou
t
toinvestigate
currentvalues.
V
Viewtheelem
mentsofaqueestion,suchaasitsstyleorcontrols,tosseethecurrentvaluesasyyou
t
testyourscrip
pt.

AutoA
AnswerQuestionnairre
Ifyouwo
ouldliketovie
ewyourskippatternsandviewwhatshappeningin
nyourroutinggatahighlevvel,
thenyoucanhavemrrStudioautom
maticallyansw
werthequesttionsforyouaanddisplayth
henumberoff
responseeseachquestionreceived.
Fromtheemenu,choosetheAutoA
Answericonsh
hownbelow:

115

Chapter11DebuggingToolswithinmrStudio

SurveyProgrammingFundamentals

Youwillbepromptedforthenumberofinterviewsyouwishtoproduceandthenumberofattempts
thesystemshouldmakeperquestion.

TheresultwillshowintheAutoAnswerwindowasshownbelow:

ThisshowsthattheFriendRelatequestiononlyreceived2outofthepossible10automaticallycreated
responses.Wheninvestigatedfurther,thismakessense,astherewasaskippatternaroundthat
question.Othergoodthingstolookatinthisviewwouldbequestionswithnoresponses,whichcould
meanyouforgottoaskthequestion.

116

SurveyProgrammingFundamentals

Chapter11DebuggingToolswithinmrStudio

ProducingTestData
Besidesseeingthesummaryofanswerscreated,wecanalsostorethoseresultstouseasdatachecks
beforethestudygoeslive.WithmrStudio,youcanwritetoSPSS.SAV,.XML,DimensionsDatafile
(.DDF),andDimensionsRDBdatabaseformats.

FromthemenuchooseTools
SelectWritetoDatabase

YoucannowchoosetheAutoAnswericonorToolsAutoAnswerDataGeneration
Youwillstillbepromptedforthenumberofinterviewsyouwishtoproduceandthenumberof
attemptsthesystemshouldmakeperquestion.

117

Chapter11DebuggingToolswithinmrStudio

SurveyProgrammingFundamentals

Thefirsttimeyourunthis,youwillnowseethefollowingscreenaskingyoutochoosethe
datatypetocreate.

Chooseyourdatatypeandbrowseandnamethenewdatafile.

IfyouchoosetocreateaSPSS.SAVfile,choosemetadatatypeasnoneandjustspecifya
casedatalocationandname.

118

SurveyProgrammingFundamentals

Chapter11DebuggingToolswithinmrStudio

AddingAdditionalDataSources
Aftersettingyourdatasourcethefirsttime,mrStudiowillautomaticallywritetothisfileeachtime.
mrStudioallowsyoutoaddmultipledatasourcesifyouwishtomaketestdatainmultipleformats.
ViewtheMetadataExplorerandfindthedatasourcescollection.Rightclickonthefolderandchoose
AddDataSources.Youwillseethemenutochoosethedatatypeandfilename.

NowyouwillbeabletoRightclickonDataSourcesandchooseChangeDataSourcetochoosewhich
datasourceyouwanttocreatetestdatafor.

119

Chapter11DebuggingToolswithinmrStudio

SurveyProgrammingFundamentals

SettingBreakpoints
Tofindoutwhathappensatcriticalpointsinyourprogram,youneedtostopexecutionatthesepoints
andlookatthecontentsofquestionsortemporaryvariablestoseeiftheycontainthecorrectvalues.
PointsatwhichmrStudiostopstoallowthisinvestigationarecalledbreakpoints.
Tosetabreakpoint,clickonthegreyareaontheleftsideofthenumberinginyourroutingsection.
Thisshouldproducealargedotonthatlineasshownbelow:

Youcanusethisfeatureinmanyways.Manypeopletestsurveysandwhentheyfindaproblem,they
wanttostopandfixtheproblemandstartretestingatthatpoint.

Setabreakpointinyourroutingatthequestionyouwanttoreview
ChooseAutoAnswer
Whenprompted,makesuretochooseNumberofinterviewstobesetto1
Thiswillstopautoansweringatthequestioninwhichyousetthebreakpoint
NowchooseF5tocontinueoutofAutoAnswermode

Thisisaneasywaytostartusingbreakpoints.Asyourcodebecomesmorecomplex,youwilluse
breakpointstoevaluateyourcodeevenmore.

120

SurveyProgrammingFundamentals

Chapter11DebuggingToolswithinmrStudio

TroubleshootingSpecificSectionsofCode
Anotherhelpfulfeatureistostepthroughthelinesoftheroutingsection,soyoucanpauseand
evaluateeachaction.Thenyoucanseethecurrentvaluesofquestionsorvariableswiththe
Expressionstaborthelocalspane.
Tostepthroughcode,choosetheF10keyorDebugSingleStep.
Next,investigatespecificquestionvaluesorproperties.
UsingtheLocalspane(ViewLocals)youcanviewpreviousanswerstoquestionsasshowninthe
picturebelow.

Inaddition,youcanseethepropertiesofquestions,suchastheappropriatestylesorpropernamesfor
elementsofaquestion.

121

Chapter11DebuggingToolswithinmrStudio

SurveyProgrammingFundamentals

UsingtheExpressionstab,youcanvieworsetthevaluestoquestionsorvariablesinordertofurther
testyourscript.(ViewExpressions).Intheexamplebelow,wearesettingthevalueofthe
TravelItemquestiontotesttheifthenroutingpatternwehavecreated.

122

SurveyProgrammingFundamentals

Chapter11DebuggingToolswithinmrStudio

WorkingwithMacros
mrStudiocontainsmacrostohelpyoucreatescripts.Youhavetheabilitytoaddnewmacrosand
modifyordeleteexistingmacros.
InmrStudio,chooseToolsMacros.Thiswilldisplaytheoptionsshownbelow.Noticethe3different
areasinwhichyoucanworkwithmacros.ForInterviewScripting,youshoulduse:

mrScriptBasic:Themacroswillappearintheroutingsection
mrMetadataScript:Themacroswillappearinthemetadatasection

Updating/DeletingExistingMacros
Chooseanexistingmacrofromthelistshowninthepreviousscreenshot.Makeanychangesdesiredin
theMacroTextorMacroNameareasandchoosetheUpdateMacroicon.Todeleteanexistingmacro,
choosethemacroandselecttheDeleteMacroicon.

AddingAdditionalMacros
Createthecodeyouwishtomakeintoamacro.ThencopythecodeandchooseToolsMacros.
Choosetheappropriateareatoplaceyourmacro(mrScriptBasicormrMetadataScript),thencopythe
codeintotheMacroTextwindow(CtrlV).CreateauniquenameforthemacrointheMacroName
area.ThenselecttheAddMacroicon.

123

Chapter11DebuggingToolswithinmrStudio

SurveyProgrammingFundamentals

Youcancopymacrosfromonemachinetoanotherbycopyingthefile,

C:\DocumentsandSettings\<yourWindowsusername>\ApplicationData\SPSS\
mrStudio\4.5.0.0\MacroDefinitions.xml.

124

SurveyPrrogrammingFundamentalls

Chapter12
2ConditioneedLoopsandGrids

Chapte
er12 Conditioned
dLoopsa
andGrids
Wehavelearnedtocrreatefilteredquestionsbaasedonansw
werstopreviousquestionsandlogic.
Addingfilterlogictolo
oopsandgrid
dsisthesameeconcept.

Thischapterrlooksatloops/gridsfilteredon:
Prevviousresponseeswithinthelo
oop
Prevviousresponseestoasimpleq
question
outssidetheloop/ggrid
Prevviousresponseestoadifferentloop/grids
quesstions
Asu
ublistofcatego
ories

PreviousRespon
nsesWithiintheLoop
p
Supposeyouhavethe
efollowingqu
uestion:

pondentshou
uldnotseethefollowupq
question,Wh
hydoyou
IftheresponseisNevver,theresp
wewishtorep
peatthesepairsofquestio
onsformultip
ple
referenceethetravelguide,LonelyPlanet?Ifw
travelguides,thenwe
emustplacetthequestionsswithinaloop.Thefollow
wingloopdem
monstratesho
ow
towritetthislogicwith
hintheroutin
ngsection.

125

Chapter12ConditionedLoopsandGrids

Example

SurveyProgrammingFundamentals

Metadata(enUS,Question,label)

TravelGuides"Now,somequestionsaboutTravelGuides."loop
{
LonelyPlanetBook"LonelyPlanet",
Fodor"Fodor's",
Frommer"Frommer's"
}fields
(
Read"Howoftendoyoureadorreferencethetravelguide,{@}?"
categorical[1..1]
{
Weekly,
Monthly,
Yearly,
Rarely,
Never
};

WhyRead"Whydoyoureferencethetravelguide,{@}?"
categorical[1..]
{
Hotel"AdviceonHotels",
Neighborhoods"InformationonNeighborhoods",
Attractions"TouristAttractions",
SaveMoney"Tipsonhowtosavemoney",
Transportation"Localtravel/transportation",
OtherReason"OtherReason"other,
Refused"PrefernottoAnswer"REF
};

)expandgrid;

EndMetadata

Routing(Web)

Dimtguide
ForEachtguideInTravelGuides
tguide.Read.ask()
Iftguide.Read.Response.Value<>{Never}Then
tguide.WhyRead.Ask()
EndIf
Next

126

SurveyProgrammingFundamentals

Chapter12ConditionedLoopsandGrids

Breakingdowntheexampleabove:

tguideisatemporaryvariablethatwillrepresentthecategoriesoftheloop(thetravelguides)
ForEach/nextloopwillloopthrougheachtguideinourloopquestion,TravelGuides
tguide.Read.Ask()willaskjustthequestion,readforeachtravelguide
TheIfstatementchecksthelogicsothatifthecurrentvalueoftguidesresponsetotheread
questionwasnotNever,thenaskthefollowupquestion,WhyRead

Loops/GridsFilteredonPreviousResponsesOutsidetheLoop/Grid
Inpreviousexamples,wecouldfiltertheresponselistofaquestionbytheresponsestoprevious
questions.Wecanapplythatsameprincipletothecategorylistofagrid/loop.Insteadoffilteringthe
categoriesofaquestion,wewilldoaQuestionFilteronaloop:
Name.QuestionFilter=categories
Item
Name
QuestionFilter
Categories

Description
Nameofthegrid/loopquestion
Property(keyword)tostateyouarerestrictingthecategoriesoftheloop/grid
question
Representsanythingthatstatesthecategoriesyouwishtodisplayinthe
loop/grid.SettingthefilterequaltoNullwillsetthefiltertoallvalidcategories.

Thefollowingisanexampleofagridwhichwillonlyshowgridcategoriesthatareappropriate/logical
fortherespondent.

Example

Metadata(enUS,Question,Label)

ResortTypes""define
{
Historical,
AmusementPark"AmusementPark",
Beach"Beach",
Adventure"Adventure"
};

AttendedResort"Fromthelistbelow,pleaseindicatewhichtypesofresortsyouhave
stayedat."
categorical[1..]{useResortTypes};

127

Chapter12ConditionedLoopsandGrids

SurveyProgrammingFundamentals

RateResortLoop"Oftheresortsyouhavestayedat,pleaseratethemonyouroverall
satisfactionwithyourexperiencesattheresort."loop
{useResortTypes}fields
(
RateResort""
categorical[1..1]
{VerySatisfied"VerySatisfied",
SomewhatSat"SomewhatSatisfied",
SomewhatDisSat"SomewhatDissatisfied",
VeryDissatisfied"VeryDissatisfied"
};

)expandgrid;
EndMetadata

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

Ifyouchoose:

128

SurveyProgrammingFundamentals

Chapter12ConditionedLoopsandGrids

Youwillonlyhavetheresponseschosenasthecategoriesofthegrid:

Loops/GridsFilteredonResponsestoaDifferentLoop/GridsQuestions
Sometimesthefilterconditionscanbecomemorecomplex.Letsthinkaboutanotherscenario.
Lookingatthegridfromthelastexample:

supposethefollowupquestionwas,
Whyareyousatisfiedoverallwiththe[INSERTRESORTTYPE]?Thisshouldonlybeaskedoftheresort
typestheyrespondedverysatisfiedorsomewhatsatisfied.

129

Chapter12ConditionedLoopsandGrids

SurveyProgrammingFundamentals

Tocorrectlyaskthisfollowup,weneedto:

Createaloopquestioncontainingthetextquestionabovetoholdtheanswerseparatelyfor
eachresorttype(asinglequestionwouldnotbesufficient).
CreateaQuestionFilterfortheloopthatholdsthetextquestion.ThisQuestionFiltershould
containonlytheresorts(categories)inwhichtherespondentratedVerySatisfiedorSomewhat
Satisfiedinthepreviousloop.

Example

130

Metadata(enUS,Question,Label)

ResortTypes""define
{
Historical,
AmusementPark"AmusementPark",
Beach"Beach",
Adventure"Adventure"
};

RateResortLoop"Oftheresortsyouhavestayedat,pleaseratethemonyouroverall
satisfactionwithyourexperiencesattheresort."loop
{useResortTypes}fields
(
RateResort""
categorical[1..1]
{VerySatisfied"VerySatisfied",
SomewhatSat"SomewhatSatisfied",
SomewhatDisSat"SomewhatDissatisfied",
VeryDissatisfied"VeryDissatisfied"
};

)expandgrid;

WhyLoop""loop
{
useResortTypes
}fields
(
WhyVerySat"Whyareyousatisfiedoverallwiththe{@}resort?"
text;

)expandgrid;

EndMetadata

SurveyProgrammingFundamentals

Chapter12ConditionedLoopsandGrids

Routing(Web)
RateResortLoop.Ask()

DimResort
DimWhyLoopFilter

WhyLoopFilter={}
ForEachResortInRateResortLoop
IfResort.RateResort.ContainsAny({VerySatisfied,SomewhatSat})Then
WhyLoopFilter=WhyLoopFilter+CCategorical(Resort.QuestionName)
EndIf
Next

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

EndRouting

YoumustsetthevariableWhyLoopFilterto{}sothatitstartsasafilterwithnothinginit.

Loops/GridsFilteredonaSublistofCategories
Aswehavelearnedinpreviouschapters,wecancreatesubliststomakedefinelistsmorereusable.
Youcanalsousesubliststocreategroupstobeusedascategoryfilters.

Name.QuestionFilter=Name.Categories.sublistname

Item
Name
QuestionFilter
Categories
sublistname

Description
Nameofthegrid/loopquestion
Property(keyword)tostateyouarerestrictingthecategoriesoftheloop/grid
question
Keywordforthecategoriesofthegrid/loop
Nameofthesublistyouwishtoshowinthegrid/loop

Thefollowingexampleasksiftherespondentprimarilytravelsforbusiness,leisureorboth.Basedon
thisresponse,thefollowupgridquestionwilldisplayadefinelistwithbusinesstravelattributes
(BusinessAttribs),leisuretravelattributes(LeisureAttribs)orbothlists.

131

Chapter12ConditionedLoopsandGrids

Example

SurveyProgrammingFundamentals

Metadata(enUS,Question,Label)

BusinessAttribsdefine
{
MeetInPerson"Ithinkmeetingfacetofaceimprovesworkcommunication.",
WeekendTravel"Travelingontheweekendsinterfereswithmypersonaltime.",
ArriveEarly"Iliketoarriveearlytoprepareforthenextday'sagenda."
};
LeisureAttribsdefine
{
ShortDistance"Iliketotakemanyshortweekendtripsvsonelongvacation/holiday.",
family"Travelisagreattimetoreconnectwithmyfamilymembers.",
cost"Ioftensplurgeonvacation/holidays,pickingthenicesthotelsandlocations."
};

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

TravelAttribs"Rateyouragreementwiththefollowingstatements."loop
{
useBusinessAttribssublist
ran,
useLeisureAttribssublist
ran
}ranfields
(
attrib""
categorical[1..1]
{
SAgree"StronglyAgree",
Agree,
Neutral,
Disagree,
SDisagree"StronglyDisagree"
};
)expandgrid;
EndMetadata

Theroutingsectionwouldlooklikethis:

132

SurveyProgrammingFundamentals

Example

Chapter12ConditionedLoopsandGrids

Routing(Web)
primarytravel.Ask()
SelectCasePrimaryTravel.Response.Value
Case{Business}

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

TravelAttribs.QuestionFilter=TravelAttribs.Categories.LeisureAttribs

CaseElse
TravelAttribs.QuestionFilter=Null
EndSelect

TravelAttribs.Ask()

EndRouting

Thecodeabovewilldisplay:

OnlytheBusinesssublistfortheTravelAttribsiftheyprimarilytravelforbusiness
OnlytheLeisuresublistfortheTravelAttribsiftheyprimarilytravelforleisure
BothlistsiftheychoseBothfortheprimarytravelquestion

Breakingdownthecodeabove:

TheQuestionFilterlinesabovearesetequaltotheQuestion.Categories.sublistnameifthe
respondentonlychosebusinessorleisure.
TheQuestionFilterwassettoNullwhentherespondentchoseboth.Nullresetsthe
QuestionFiltersothatallcategoriesareshown.Anotheralternativeistosetthefiltertothe
questionsdefinedcategories.

Usingthesublistsasshownabovedoeslimityourabilitiestosort,asthesublistscanbe
sortedwithinthemselves,butyoucannotsortthetwosubliststogether.Ifsortingisan
issueandyouwishtouseasublistasafilter,seefilterbysublist.mddonyourCDforan
advancedfunctiontoeliminatetheproblem.Thisexampledynamicallycreatesafilterfrom
thecategoriesinasublist,insteadofusingthesublistforthefilterdirectly.

133

Chapter12ConditionedLoopsandGrids

SurveyProgrammingFundamentals

Exercise
Usethemetadatafile,Restaurant.mdd.Themetadatahasbeencompleted;pleaseaddtherouting
sectionandlogicasstatedbelow.

(Askthenexttwoquestions(Eaten&OftenEat)foreachoftherestauranttypesof:
Deli/CarryOutRestaurantswithoutSeating
FastFoodRestaurants
Family/CasualDiningRestaurants
UpscaleRestaurants)
Eaten

Haveyouevereatenin[INSERTTYPEOFRESTAURANT]?

Yes
No

OftenEat

(IfYes)Howoftendoyoueatin[INSERTTYPEOFRESTAURANT]?

Daily
Weekly
Monthly
Yearlyorless

(AskonlyiftheysaidYestothetypeofRestaurantintheEatenQuestion)
FoodQuality

Pleaserateyouroverallsatisfactionwiththequalityoffoodobtainedinthefollowing
typesofrestaurants.
Very
Somewhat
Satisfied Satisfied

Deli/CarryOutRestaurantswithoutSeating

FastFoodRestaurant

Family/CasualDiningRestaurant

UpscaleRestaurant

Neutral

Somewhat
Very
Dissatisfied Dissatisfied

134

SurveyProgrammingFundamentals

Chapter12ConditionedLoopsandGrids

(IfYestoFastFoodinEatenQuestion,askChainAwareandFastFoodQual.)
ChainAware

Whichofthefollowingfastfoodchainshaveyoueatenat?

Wendys
McDonalds
BurgerKing
Arbys
InNOutBurger
Noneofthese

(OfthefastfoodchainsmentionedinChainAware)
FastFoodQual Pleaserateyouroverallsatisfactionwiththequalityoffoodobtainedinthefollowing
fastfoodrestaurants.

Very
Somewhat
Satisfied Satisfied

Neutral

Somewhat
Very
Dissatisfied Dissatisfied

Wendys
McDonalds
BurgerKing
Arbys

{
{
{

{
{
{

{
{
{

{
{
{

{
{
{

InNOutBurger

135

Chapter12ConditionedLoopsandGrids

SurveyProgrammingFundamentals

136

SurveyPrrogrammingFundamentalls

Chapter13ConttrollingtheLo
ookofYourSu
urvey

Chapte
er13 ControllingtheLook
kofYourS
Survey
Lookand
dfeelcanbeaacrucialelem
mentofsurveyyscripting.m
mrInterviewp
providesgreattflexibilityin
termsofmodifyingthelookofyou
ursurvey.

Intthischap
pterwewilllearrn:
Differentw
waystochangeetheoverall
appearancceofyoursurvey
Howtoap
pplydifferentlo
ookstoyoursu
urvey
Howtoefffectivelyusesttyleswithinyour
script

OverviiewoftheFormattin
ngofaSurrvey
Tofullyu
utilizethecap
pabilitiesofan
nmrInterview
wsurveysappearance,youneedtound
derstandhow
wthe
overallfo
ormattingoftthesurveywo
orks.Thehieerarchyofitem
msthataffectttheappearaanceofan
mrInterviewsurveyarre:
HTMLTemplaates(includingCascadingSStylesheetsaand.xmlfiles)).ThesearesspecialHTML
1) H
p
pagesthatare
eappliedtoyyoursurvey.
2) Styleswithint
S
thescript.Th
hesearescrip
ptingpropertiiesaddedtoeeitherthemeetadataorthee
r
routingsectio
on.

mple,ifyoufo
ormataspecifficquestionw
withastyleinawaythatco
ontradictswh
hatisintheH
HTML
Forexam
templatee,thenthequ
uestionstylew
willoverridetthetemplatesformatforthatquestion
n.
Nowthattyouhaveab
basicundersttandingofhow
wtemplatesandstylesareeappliedtotthesurvey,lets
takeaclo
oserlookate
eachaspect.

Templa
ates
TemplateesareHTMLp
pageswhichh
havespecialm
mrInterviewtagsthatreepresentthed
differentparttsof
asurvey.Templatesccontrolthelayoutofthem
mrInterviewp
pageseparateefromthetexxtofyour
questionnaireasyouccreateditintthemetadataa.Thisallowssyoutheflexiibilitytocreattestandard
templateesforreuseinmanyprojeects.Youcanalsousemorrethanoneteemplatewith
hinasurvey.

137

Chapter13ControllingtheLookofYourSurvey

SurveyProgrammingFundamentals

Thethreemaintypesoftemplatesare:

LayoutTemplate:Definesonepage/screenlayout.Thistemplateisusuallycreatedinawayin
whichyoucanapplythistomultiplestudiesifyouwantthemtoallhavethesamebasiclook.
Also,thisdoesnotnecessarilymeanthatyouhavetocreateacompletelynewtemplatefileif
youwanttovaryjustoneaspectofthelayoutforaparticularpartofanintervieworfora
differentproject.Ifthebasicpagelayoutisthesame,youcancreatesubtemplatesforthe
aspectsthatchange.
SubTemplate:Atemplatefilethatdefinesthelayoutofoneaspectofthepage.For
example,youcancreatesubtemplatesforquestions(questionandresponsetexts),errors,
banners,navigationbars,andgrids.Themainpagelayouttemplate(listedintheprevious
bulletpoint)containsabasictagindicatingwherethevariouscomponentsbelongandthesub
templatesdefinetheexactlayoutforeachcomponent.Youspecifywhichsubtemplatesareto
beusedbynamingthemintheroutingsectionoftheinterviewscriptorinthemainlayout
template.
LocalizedTemplate:Usedfororganizationsthatcreatesurveysforpeopleinmultipleregions
oftheworld.Localizedtemplatesallowyoutosetthelanguageofaninterviewbasedonthe
respondent'sbrowserlanguage,andthelanguagecanbechangedintheinterviewscript.The
interviewingprogrampassesthelanguagetotheHTMLPlayer,whichsearchesforthe
appropriatetemplateinthatlanguagesfolderandthenintheprojectfolder.

Inadditionallthreetemplatetypescanbeassignedgloballyorataprojectlevel.Theorderinwhich
mrInterviewlooksfortemplatesisasfollows:
1.
2.
3.
4.
5.
6.

Projectfolderspecificlanguagepassedasthecurrentinterviewslanguage
Projectfolderdefaultlanguage
Projectfolder
Globaltemplatesfolderspecificlanguagepassedasthecurrentinterviewslanguage
Globaltemplatesfolderdefaultlanguage
Globaltemplatesfolder

Becauseofallthevariableslistedabove,youwillwanttothoroughlytestyourscriptsinmanydifferent
waystoensurethattheproperlookisbeingappliedtoyoursurvey.

Thiscoursewillonlydiscusshowtoapplythetemplates,nothowtocreatethetemplates.
Formoreinformation,seetheDDL:DDL.chm::/interviewscripting_templates_writing.htm

138

SurveyProgrammingFundamentals

Chapter13ControllingtheLookofYourSurvey

ApplyingaTemplatewithinYourScript.
Toapplyatemplatewithintheroutingsection:
Routing(Web)
IOM.LayoutTemplate="templatename.htm"
Name.Ask()

Item
Description
IOM.LayoutTemplate Keywordstosignifyyouareaddingatemplatestyletothesurveyfromthis
pointforwardintheroutingsection
templatename.htm
Theactualnameofthetemplatetoapply

Ifaquestionistiedtoaspecifictemplateorsubtemplate(suchasjavascriptlogictocheckaspecific
question,oracomplexquestionstyle),youmaychoosetoaddthetemplatetothemetadata:

Metadata(enUS,Question,Label)
Name"text"
templates(Question="templatename.htm")questiontype

Item
Description
Templates(Question=) Keywordstosignifyyouareaddingatemplatestyletothisspecificquestionin
themetadata
Templatename.htm
Representstheactualnameofthetemplatetoapply
questiontype
Representsthequestionstype(categorical,long,text,etc.)Notethatthe
templategoesbeforethequestiontypekeyword.

139

Chapter13ControllingtheLookofYourSurvey

SurveyProgrammingFundamentals

Belowisanexampleofapplyingatemplatetotheentiresurvey.

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()

EndRouting

Youcandrasticallychangetheappearanceofaquestionwithtemplates.mrStudiodisplaysthe
templatesastheywillappearwhenactivatedtomrInterview.

Whenreviewingyourtemplates,youcanchoosetoseeafullbrowserviewasopposedto
thesmallerwindowwithinmrStudio,bychangingtheUseBuiltinBrowseroptiontoFalse
underToolsOptions.However,withthisoptionyoucannotusetheF5AutoAnswer
featureeasily.

Folders
TheDimensionsDevelopmentLibraryprovidesyouwithexampletemplatestouseandmodify.These
areincludedbydefaultinC:\ProgramFiles\SPSSDimensions\DDL\Scripts\Interview\Templates
folder.

140

SurveyProgrammingFundamentals

Chapter13ControllingtheLookofYourSurvey

TipsforScriptwritersRegardingTemplates
AfewthingstothinkaboutasyouareusingmrStudiotoapplyyourtemplates:

IfyouhavetemplatesfrompreviousversionsofmrInterview,youneedtoensurethe
templatesareXHTMLorperfectlyformedHTML.Inthetoolbar,chooseHTMLtidytohave
mrStudiotrytocleanupyourcode.Thismaynotalwayswork100%,butismaybeworth
seeingwhattheresultsare.MakeabackupofyourtemplatefilesbeforeattemptingHTML
tidy.
MakesurethatwhenyouactivatethestudyinmrInterviewthatyouhaveincludedanyproject
specifictemplatesyouhavebeenusinglocallyinmrStudio.

Styles
Stylesallowustocontrolthemanyformattingaspectsofsurveyitemsfrominsideoursurveyscript.
Wecanusestylesonsuchitemsasquestions,categories,labelsandnavigationcontrols.Therearetwo
majorgroupsofstyles:

DefaultStyles:Defaultstylesaresettingsthatgetappliedtoanentiregroupofsurveyitems.
Forexample,defaultstyleswouldbeusedtomakechangestoallthequestiontextfontfor
thatscript.
QuestionStyles:Questionstylesareusedtoformatitemsforspecificquestions.

Inpracticeyoushouldusedefaultstylestoperformthebulkofyourformattingwithstyles.Use
questionstylestoapplyuniqueorquestionspecificformatting.Itisrecommendedthatyoudeclare
yourdefaultstylesatthetopoftheroutingsectionofthesurvey.However,youcanchangethe
settingsofthedefaultstylesatanytimeinyoursurvey.

Completedetailsregardingtheavailableoptionsofthestylesobjectcanbefoundinthe
DDL:IOMLib.chm::/IStyle.html

DefaultStyles
Therearesixtypesofdefaultstylesandeachgrouphasanumberofsubtypes.Forthisintroductory
course,wewillfocusonlyonthemaindefaultstyles:

Default
Labels
Categories
Grids
Navigation
Questions

Whileeachofthesedifferentareasrepresentsadifferentareaforpotentialformattingyoushouldalso
beawareoftheinteractionbetweentheareas.Thestylesettingsfromoneareawillcascadetoother
styleobjects.Thefollowingistheorderofprecedence:

141

Chapter13ControllingtheLookofYourSurvey

SurveyProgrammingFundamentals

1)
2)
3)
4)
5)
6)

DefaultStyles.Default
DefaultStyles.Label
DefaultStyles.NavigationandDefaultStyles.Categories
DefaultStyles.Questions
DefaultStyles.Questions.Labels
DefaultStyles.Question.CategoriesandDefaultStyles.Grids

Forexample,ifwesetthefontdifferentlyinthedefaultandlabelssections,thelabelssectionwillbe
thesettingthatisused.Letsreviewsomeofthedifferentareasofasurveyinwhichstylescanbe
applied.
Default
Thedefaultstyleisthestylesettingsthatallotherstylesarederivedfrom.Sothesesettingswillform
thebasisforallotherdefaultstyletypesand/orquestionstylesettings.
IOM.DefaultStyles.Default

Example

Routing(Web)

IOM.LayoutTemplate="Card_Blue_TopAndBottomErrors.htm"

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

InterestinLocation.Ask()

EndRouting

TheexampleabovewouldsetalltexttobeTahomaforthisstudy,overridingwhathasbeensetinthe
template.

142

SurveyProgrammingFundamentals

Chapter13ControllingtheLookofYourSurvey

Categories
Thecategorydefaultstylessectionisusedtoapplyformattingtocategoricalresponses.
IOM.DefaultStyles.Categories[CategoryStyleTypes.CategoryStyleTypeEnum]
WheretheCategoryStyleTypesEnumsareasfollows:
CategoryStyleTypeEnum
csSingle
csMulti
csExclusive
csList

Description
Singleresponsecategorical.
Multiresponsecategorical.
Exclusiveresponsecategorical.
SubheadingText.

Example

Routing(Web)

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

ModeofTravel.Ask()

EndRouting

Thecodeabovewillturnallresponsesmarkedwiththekeywordsexclusive,DK,REF,orNAtobe
unbold.

143

Chapter13ControllingtheLookofYourSurvey

SurveyProgrammingFundamentals

Grid
Defaultgridstylesareusedtocontroltheformatofgridquestions.Itallowsustospecifyformatting
forcolumn/rowheadingsaswellasalternatingcolumns/rows.

IOM.DefaultStyles.Grids[GridStyleTypes.GridStyleTypesEnum]

WheretheGridStyleTypesEnumsareasfollows:
GridStyleTypesEnum
gsCell
gsAltRow
gsAltCol
gsRowHeader
gsColHeader
gsAltRowHeader
gsAltColHeader

Description
Thecellsofagrid.
Thealternatingrowsofagrid.
Thealternatingcolumnsofagrid.
Therowheadingsofagrid.
Thecolumnheadingsofagrid.
Thealternaterowheadingsofagrid.
Thealternatecolumnheadingsofagrid.

Example

144

Routing(Web)

'DefaultGridFormatting
WithIOM.DefaultStyles
'Rowcellitems
.Grids[GridStyleTypes.gsCell].Cell.BorderColor="black"
.Grids[GridStyleTypes.gsCell].Cell.BorderStyle=BorderStyles.bsSolid
.Grids[GridStyleTypes.gsCell].Cell.BorderWidth=1
'Alternatecellitems
.Grids[GridStyleTypes.gsAltRow].Cell.BgColor="#D5D5D5;"
'RowHeadings
.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"
'ColumnHeadings
.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"
'AlternateRowHeadings
.Grids[GridStyleTypes.gsAltRowHeader].Cell.BgColor="#CECECE;"
EndWith

SurveyProgrammingFundamentals

Chapter13ControllingtheLookofYourSurvey

InterestinLocation.Ask()

EndRouting

ThiscodehasbeenwritteninaWith/EndWithblock.TheWith/EndWithstatementallowsyouto
specifyinformationthatwillbeaddedtothebeginningofeachlinethatstartswithanopendot(.)
withintheblock.Ifthereisnotanopendot,thentheinformationontheWithlineisnotadded.The
previouscodewillformatallgridswithintheprojectwiththepropertiesspecified.Thereisno
templateappliedtothepicturebelow,onlythestylesspecifiedabove.

145

Chapter13ControllingtheLookofYourSurvey

SurveyProgrammingFundamentals

Labels
Labeldefaultstylesallowustospecifyformattingfordifferenttypesoflabels.Forexample,wemay
wantallquestionlabelstouseadifferentsizefontthanthecategorylabels.
IOM.DefaultStyles.Labels[LabelStyleTypes.LabelStyleTypesEnum]
WhereLabelStyleTypesEnumare:
LabelStyleTypesEnum
lsQuestion
lsCategory
lsBanner
lsError
lsNavigation
lsTitle

Description
Styleforquestionlabels.
Styleforcategorylabels.
Styleforbannerlabels.
Styleforerrorlabels.
Stylefornavigationlabels.
Stylefortitlelabels.

Thecodebelowwillmakeallquestiontexttohaveafontsizeof24.

Example

Routing(Web)

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

AmtSpentYr.Ask()

EndRouting

Navigation
Defaultnavigationstylescanbeusedtoformatthelookandfeelofthenavigationbuttons.
IOM.DefaultStyles.Navigation

Example

Routing(Web)

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

AmtSpenYr.Ask()

EndRouting

Thecodeabovewillcreateabluebackgroundcoloronthenavigationbuttons.

146

SurveyProgrammingFundamentals

Chapter13ControllingtheLookofYourSurvey

Thenumberthatrepresentsthecolorisahexadecimalcolorvalueandiscommonlyusedto
createaveryspecificcolor.Youcanfindmanywebsitesthatprovidethesecolorcodes.
Searchfortermslikewebsafecolors.

Questions
Questiondefaultstylesallowyoutodefineformattingspecifictothetypeofquestionbeingdisplayed.

IOM.DefaultStyles.Questions[QuestionStyleTypes.QuestionStyleTypesEnum]

WheretheQuestionStyleTypesEnumsare:
QuestionStyleTypesEnum
qsInfo
qsLong
qsText
qsCategorical
qsDate
qsDouble
qsBoolean
qsLoopCategorical
qsLoopNumeric
qsCompound
qsBlock
qsPage
qsOther

Description
Informationitems.
Long(integer)questions
Textquestions
CategoricalQuestions
Datequestions
Double(real)questions
Booleanquestions
Categoricalloops.
Numericloops.
Compoundquestions
Blockquestions
Multiplequestionpageitems.
AutomaticOtherSpecifyquestions.

Forexamplethefollowingcanbeusedtomakeall"otherspecify"textboxesacertainsize.

Example

Routing(Web)

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

HotelChainStayed.Ask()

EndRouting

147

Chapter13ControllingtheLookofYourSurvey

SurveyProgrammingFundamentals

QuestionStyles
Thesametypesofstyleswediscussedasdefaultcanbeappliedatthequestionlevel.Theuseof
questionstylesshouldbeminimal,forveryspecificformattingneeds.Thissectionwilldiscusssome
commonquestionspecificformattingneeds.
CategoricalQuestions
Withacategoricalquestionyoumaywanttodisplaytheavailablecategoriesinmultiplecolumnsor
usingalistboxorcomboboxratherthanthetraditionalcheckboxesorradiobuttons.

Thefollowingexamplewillcreate2columnsofresponsesinsteadofasinglecolumn.

Routing(Web)
Example

HotelChainStayed.Style.Columns=2

HotelChainStayed.Ask()

EndRouting

Thefollowingexamplewillcreateadropdownlist.Notethatthecategorieshaveasubheadingof
SelectOne.Thisisdonesothattherespondentmustchooseananswer,sincethesubheadingisnot
avalidresponse.

Example

148

Metadata(enUS,Question,Label)
Souvenirs"Whichofthefollowingsouvenirsdoyouprefertopurchasewhenonholiday
orvacation?"
categorical[1..1]
{
SelectOne"SelectOne"
{
Clothing,
Hats,
Postcards,
SnowGlobes"SnowGlobes"
}
};
EndMetadata

SurveyProgrammingFundamentals

Chapter13ControllingtheLookofYourSurvey

Routing(Web)

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

EndRouting

Youcanalsocontrolthecolumnwidthforthedroplistorcomboboxwith:
Name.Style.Width

TextQuestions
Foratextquestionyoumaywanttocontrolthewidthandheightofthetextboxgenerated.The
followingwillmodifythewidthandheightofthequestion.

Example

Routing(Web)

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

EndRouting

Youcanalsochangethetypeoftextboxthatwillbecreated:
Tochangetoasinglelineformat:
TextQ.Style.Control.Type=ControlTypes.ctSingleLineEdit
Tomaskwhatistypedintheboxwithdotsinsteadofthecharacters:
TextQ.Style.Control.Type=ControlTypes.ctPassword

149

Chapter13ControllingtheLookofYourSurvey

SurveyProgrammingFundamentals

MetadataStyles
Whenastyleisspecifictoaquestion,itmaybebettertoapplythestyletothequestiondirectlyinthe
metadata.Theoptionsavailablearethesameasintherouting,buthaveaslightlydifferentsyntax.
Thecodebelowwillorienttheresponseshorizontally(orientation=row)andreplacesthebuttonsand
textwithanimage.

Example

Metadata(enUS,Question,Label)
HappyLastTravel"ChoosetheimagebelowthatindicateshowhappyyouweretheLAST
timeyoutraveled."
style(Orientation=Row)
categorical[1..1]
{
VeryHappy"Veryhappy"
style(Image="VeryHappy.gif",Control(Type="Button")),

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

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

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

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

EndMetadata

Thecodeabovewillproducethefollowingquestion:

150

SurveyProgrammingFundamentals

Chapter13ControllingtheLookofYourSurvey

CustomControls
Customcontrolsareatypeofsubtemplatethatgeneratesaninteractivecontrolthatrespondentscan
usetoansweraquestion.Forexample,ifyouhaveadatequestionyoumaywanttherespondentto
seeacalendar.Youcouldhavetherespondentflipthroughacalendarandthenclickonthedateto
answerthequestion.

Foranexampleofacustomcontrol,reviewthecalendarexampleintheDDLproject,
C:\ProgramFiles\SPSSDimensions\DDL\Scripts\Interview\Projects\NewFeature.mdd

XHTMLinLabels
Wehaveseenthattemplatesallowustocontroltheoveralllookofasurveypage.Wecanusestylesto
formatindividuallabelsorothersurveyitems.However,sometimeyoumayneedtoformatjusta
singlewordonalabel.Thistypeofgranularformattingfallsoutsideoftemplatesandstyles.Wecan
useXHTMLwithinourmetadatafiletoperformthistypeofformatting.

WhatisXHTML?
XHTMLisamarkuplanguagebasedonHTML.Theprimarydifferenceistheneedforalltagstobewell
formed.Thismeansthatalltagsmusthaveanopeningandclosingtag.
Hereareafewbasictagsthatmayproveusefulwithinyourscript:
Tag
<b>text</b>
<i>text</i>
<u>text</u>
<br/>

Description
BoldTag
ItalicTag
Underline
CarriageReturn

151

Chapter13ControllingtheLookofYourSurvey

SurveyProgrammingFundamentals

Example

TravelItem"Fromthelistbelow,which<b>one</b>itemwouldyoumostwanttobring
withyouonaleisuretrip?"
categorical[1..1]
{
Camera,
Map,
ComfortableFootwear"ComfortableFootwear",
FriendTravelCompanion"Friend/TravelCompanion"
};

ItisrecommendedthatyouonlyincludeXHTMLtagswhennoneoftheotherformattingoptions
provideasuitablesolution.Thisisduetothatfactthatthesetagscanmeanadditionalworkwhen
relatingtotranslationand/orreporting.

FinalThoughtsonFormatting
Whenpeoplearefacedwithsomanyplacestoapplyformatting,theymaybeconfusedbywhat
formattingshouldgowhere.Oneissueyoushouldtakeintoconsiderationwhendecidingwhereto
applyspecificlooksofyoursurveyissystemefficiencyvs.easeofuse.Letssayforexamplethatyou
wantallthesurveystohaveadefaultfontof"Tahoma";whereisthebestplacetodeclarethis?Since
youwantthisappliedtoeverything,ideallyyoushouldputthisinthetemplateorassociatedCSSfile
sinceitisatthehighestlevel.Inthiswayyougetthecorrectfontwithouthavingtodeclareanything
inyoursurvey.Alsoifyoulaterchangeyourstyleyouwillnotneedtoupdateanyscripts.(Notto
mentionmrInterviewwillnothavetoprocessthatstyledetail.)Andyoucanstillusethestylesto
overridethetemplateswhennecessary.

152

SurveyProgrammingFundamentals

Chapter13ControllingtheLookofYourSurvey

Exercise
OpentheMeals.mddfileandSaveasMealsWithStyle.mdd

Addthetemplate,Verge_Layout.htmfiletothedocument
TheCaloriesgridhasnumericresponses;makeaboxsizeof50forthosenumericquestions.
ChangetheHealthCommboxsizetoheightof100andwidthof550.

Astimeallowsformatallthegridstohavethefollowinglook:

Hints:

Sizeofcolumns=90px
Colorofratingscaletext=#BB342B
Colorofalternaterows=#B8B8B8
Bordersaresolid,1width,andcolorof#B8B8B8

153

Chapter13ControllingtheLookofYourSurvey

SurveyProgrammingFundamentals

154

SurveyPrrogrammingFundamentalls

Chaptter14TextSubstitutionsaandTextHeadings

Chapte
er14 Te
extSubstittutionsan
ndTextH
Headings
Youmayneedtohave
etextwithinyyoursurveythatchangesw
withtheresp
ponsesgiven.Forinstancee,if
youwantttolisthowm
manyanswerswerechosenatapreviou
usquestiono
ortohavetexxtthatreflectsa
positiveo
ornegativeraatingtoapreviousquestio
on(Whydidyougivetheproductapo
ositiverating??).

Inthischapterw
wewill:
Displayananswertoapreviousquestionin
thetextoffthesurvey
Displayinganswerstoprreviousquestio
ons
withinagrrid
Inserttexttintothemetaadatathatwillbe
controlledintheroutinggsection

Display
yingRespo
onsestoP
PreviousQ
Questions
Youcand
displaythean
nswerstopreeviousquestio
onsinthesurrveywithinan
nyofthetextinthemetad
data.
{
{#Name}
Item
Name

Example

Description
Nameofth
hequestionthatcontainstheresponseeyouwanttodisplay

Souvenirs"Whicho
ofthefollowingsouvenirsdoyouprefeertopurchaseewhenonho
oliday
orvacation?"
cate
egorical[1..1]
{
Cllothing,
Hats,
Po
ostcards,
Sn
nowGlobes"SSnowGlobes""
}ran
n;

WhySo
ouvenir"Whyydoyouprefertopurchasse{#Souvenirrs}whenonholidayorvacation?"
text;

155

Chapter14TextSubstitutionsandTextHeadings

SurveyProgrammingFundamentals

IfSnowGlobeswaschosenintheSouvenirquestionpreviously,theWhySouvenirquestionwillappear
as:

Ifyouareinsidealoopandyouwanttodisplaytheitemdrivingtheloop,usethe{@}sign.

Example

Metadata(enUS,Question,Label)

InterestinLocation"Pleaseratethefollowingtraveldestinationsonyourinterestin
visitingthelocation."loop
{
Aruba,
Bermuda,
Florida,
Hawaii,
Fiji,
CostaRica"CostaRica",
Thailand"Thailand"
}fields
(
Rating"Pleaserate{@}onyourinterestinvisiting."
Categorical[1]
{
ExtremelyInterested"ExtremelyInterested",
SomewhatInterested"SomewhatInterested",
Neutral,
SomewhatDisinterested"SomewhatDisinterested",
ExtremelyDisinterested"ExtremelyDisinterested"
};
)expandgrid;
EndMetadata

156

SurveyProgrammingFundamentals

Chapter14TextSubstitutionsandTextHeadings

Ifthequestioniswithinaloop/gridandyouneedtoreferenceitoutsidetheloop,thenthereferenceis
slightlydifferent.Youneedtousetherootleveloperator\.inthesyntax:
{#\.LoopName[{LoopCategory}].InsideQuestion}
Item
Loopname
LoopCategory
InsideQuestion

Description
Nameoftheloop
Specificloop/gridsliceyouwishtodisplaytheanswerto
Questionwithintheloop/grid

Thefollowingwilldisplaytheresponsetoaspecificgridsliceinthefollowuptextquestion.

Example

Metadata(enUS,Question,Label)

InterestInLocation"Pleaseratethefollowingtraveldestinationsonyourinterestin
visitingthelocation."Loop
{
Aruba,
Bermuda,
Florida,
Hawaii,
Fiji,
CostaRica"CostaRica",
Thailand"Thailand"
}fields
(
Rating"Pleaserate{@}onyourinterestinvisiting."
categorical
{
ExtremelyInterested"ExtremelyInterested",
SomewhatInterested"SomewhatInterested",
Neutral,
SomewhatDisinterested"SomewhatDisinterested,
ExtremelyDisinterested"ExtremelyDisinterested"
};
)expandgrid;

WhyAruba"WhydidyourateAruba{#\.InterestinLocation[{Aruba}].Rating}?"
text;

EndMetadata

157

Chapter14TextSubstitutionsandTextHeadings

SurveyProgrammingFundamentals

InsertTextintotheMetadatathatwillbecontrolledintheroutingsection
Therewillbeothertimesinwhichyouwillcontrolthetexttobeshowninsteadofredisplayinga
previousanswer.Toachievethis,youneedtouseatextinsert.Therearetwopartstocreatingthis
item.Addamarkerinthemetadatatorepresentthetextyouwishtoinsert,andthencreatea
referencetothiswithintherouting.
Metadata(enUS,Question,Label)
Name"Text{Marker}"typeparameters;
EndMetadata

Routing(Web)
Name.Label.Inserts["Marker"].Text=Value
OR
Name.Ask(Value)
EndRouting

Item
Name
Text
{Marker}or
["Marker"]
Type
Parameters
Value

Description
NameofthemetadataitemthatcontainstheplaceholderorMarker
Textassociatedwiththeitem
Representsthevariableyoucreatedtobetheplaceholderforthetextyouwant
toinsert.Asshownabove,itisreferenceddifferentlyinthemetadatavs.the
routing.
Identifiestheitemforitsfunctionality(categoricalquestions,textonlyitems,
etc.)
Thisvariesbyitemtype,butanexamplewouldbetheresponsestoaquestion.
RepresentsthetextyouwanttoinsertinMarker.Werecommendmakingthe
texttobeinsertedaninfoiteminthemetadataforeaseoftranslation.

158

SurveyProgrammingFundamentals

Chapter14TextSubstitutionsandTextHeadings

ThefollowingexamplewillsubstitutetextfortheExplainChainquestionbasedoniftherespondent
choseoneanswerormanyanswerstotheHotelChainStayedquestion.Noticethetexttobe
substitutedisstoredininfoitemsinthemetadata.Thisisagoodpracticeifthestudyistobedonein
multiplelanguages.

Example

Metadata(enUS,Question,Label)
HotelChainStayed"Choosethehotelchainsyouhavestayedatthispastyear."
categorical[1..]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
OtherHotel"OtherHotelChain"other,
DontKnow"DontRemember"DK,
Refused"PrefernottoAnswer"REF
};

ExplainChains"Pleasegiveabriefexplanationwhyyouchosetostayat{Chain}as
opposedtoothersinthepastyear."
text[1..];

OneChain"thischain"info;

Chains"thesechains"info;

EndMetadata

Routing(Web)

HotelChainStayed.Ask()

IfNot(HotelChainStayed.ContainsAny({DontKnow,Refused}))Then

IfAnswerCount(HotelChainStayed)=1then

ExplainChains.Label.Inserts["Chain"].Text=OneChain.Label

Else

ExplainChains.Label.Inserts["Chain"].Text=Chains.Label

EndIf

ExplainChains.Ask()
EndIf

EndRouting

159

Chapter14TextSubstitutionsandTextHeadings

SurveyProgrammingFundamentals

Thereisanalternativetothemethodfortextsubstitutionshownabove.Youcanalsoaddtheinsert
referenceintotheaskstatement.Theexamplebelowshowsthepreviousinsertexample,butusing
thealternativemethod.

Example

Metadata(enUS,Question,Label)
HotelChainStayed"Choosethehotelchainsyouhavestayedatthispastyear."
categorical[1..]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
OtherHotel"OtherHotelChain"other,
DontKnow"DontRemember"DK,
Refused"PrefernottoAnswer"REF
};

ExplainChains"Pleasegiveabriefexplanationwhyyouchosetostayat{Chain}as
opposedtoothersinthepastyear."
text[1..];

OneChain"thischain"info;

Chains"thesechains"info;

EndMetadata

Routing(Web)

HotelChainStayed.Ask()

IfNot(HotelChainStayed.ContainsAny({DontKnow,Refused}))Then

IfAnswerCount(HotelChainStayed)=1then

ExplainChains.Ask(OneChain.Label)

Else

ExplainChains.Ask(Chains.Label)

EndIf
EndIf

EndRouting

160

SurveyProgrammingFundamentals

Chapter14TextSubstitutionsandTextHeadings

HereisanexamplethatgetsridoftheextraneoustextthatmrInterviewplacesinatextinsertfora
previousquestionwhentheanswerisanotherspecify.Youdonotusethestandard{#Name},but
insteadcreateatextinsertwithaconditiontocheckfortheother.

Example

Metadata(enUS,Question,Label)

TypeAccom"Atwhattypeofaccommodationsdidyoustay?"
categorical[1..1]
{
Hotels,
Motels,
BedBreakfast"BedandBreakfasts",
Hostels,
Resorts,
OtherAccom"OtherAccommodations"other
};

HowFreqStay"Howfrequentlydoyoustayat{Accom}?"
categorical[1..1]
{
VeryFreqently"VeryFrequently",
SomewhatFreqently"SomewhatFrequently",
Rarely,
FirstTime"Thiswasthefirsttime"
};
EndMetadata

Routing(Web)

TypeAccom.Ask()

ifTypeAccom={OtherAccom}then

HowFreqStay.Label.Inserts["Accom"]=TypeAccom.OtherAccom
else

HowFreqStay.Label.Inserts["Accom"]=TypeAccom.Response.Label
endif
HowFreqStay.Ask()

EndRouting

161

Chapter14TextSubstitutionsandTextHeadings

SurveyProgrammingFundamentals

TextHeadings
Youmaywishtoincludeheadingsthatareappliedtoasinglequestionormultiplescreens.Thiscanbe
achievedbycreatingabanner.Intheroutingsection,placethefollowingstatement:
Toaddanewheading:
Name.Banners.AddNew("BannerName",InfoName.Label)

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

Toremoveabanner:
Name.Banners.Remove("BannerName")
Item
Name

Description
Nameofthequestionorpagetoapplytheheading.ThiscanalsobeIOMto
usethesameheadingformultiplescreens.
BannerName
Uniquenameforthebanner.Mustfollowstandardnamingconventions.
InfoName.Label,
Nameoftheinfoitemholdingthetextyouwishtodisplay.Youcanalsochoose
NewInfoName.Label toplacespecifictextindoublequoteswithinthisitem.

Whenaddingbanners,itisrecommendedthatyouplacethetextininfoitemsinsteadofdirectlyinthe
routingsection.Thisallowsyoursurveystobeeasilytranslatedintomultiplelanguagesorcontexts.In
theexamplebelow,weareaddingonebannerandchangingitstextduringthesurveytoaccommodate
thedifferentsections.

Example

162

Metadata(enUS,Question,Label)

HotelChainStayed"Choosethehotelchainsyouhavestayedatthispastyear."
categorical[1..]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
OtherHotel"OtherHotelChain"Other,
DontKnow"DontRemember"DK,
Refused"PrefernottoAnswer"REF
};

SurveyProgrammingFundamentals

Chapter14TextSubstitutionsandTextHeadings

FavHotelChain"Ofthosechains,whichonewouldyoumostprefertostayatagain?"
categorical[1..1]
{
InterContinental,
Cendant,
Marriott,
Accor,
Choice,
Hilton,
OtherHotel"OtherHotelChain"Other,
DontKnow"DontRemember"DK,
Refused"PrefernottoAnswer"REF
};

InterestinLocation"Pleaseratethefollowingtraveldestinationsonyourinterestin
visitingthelocation."loop
{
Aruba,
Bermuda,
Florida,
Hawaii,
Fiji,
CostaRica,
Thailand
}fields
(
Rating"Pleaserate{@}onyourinterestinvisiting"
categorical[1..1]
{
ExtremelyInterested"ExtremelyInterested",
SomewhatInterested"SomewhatInterested",
Neutral"Neutral",
SomewhatDisinterested"SomewhatDisinterested",
ExtremelyDisinterested"ExtremelyDisinterested"
};

)expandgrid;

HotelText"HotelQuestions"info;

DestinationText"DestinationQuestions"info;

EndMetadata

163

Chapter14TextSubstitutionsandTextHeadings

SurveyProgrammingFundamentals

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
Dimlocation
ForeachlocationinInterestinLocation

location.ask()
Next
EndRouting

Theaboveexamplewilldisplaydifferentheadingsforthedifferentscreens.Wehavealsoaddeda
defaultstyletoincreasethefontsizeoftheBannerTextasshownbelow:

164

SurveyPrrogrammingFundamentalls

Chap
pter15EnhaancingSurveyyFlow

Chapte
er15 En
nhancingS
SurveyFlow
Toobtain
naccuratedata,bydefaulttmrInterview
wrequiresareesponsetoeaachquestion.Attimes,yo
ou
maywan
nttoeitherprresetinformaationintoqueestionsorallo
owrespondentstonotansswerthe
questionandcontinue
ewiththesurrvey.

Inthischapterw
wewill:
Preassignttheinitialansweerstoquestions.

Understand
dthepropertyth
hatallowsrespo
ondents
tonotgiveananswertoaq
question

Allowforan
nanswertobetthedefaultrespo
onse

Asstated
dabove,mrIn
nterviewrequ
uiresarespon
nsetoeachqu
uestion.Too
overridethiso
option,youm
must
do2things:

SSettheMustA
AnswerpropeertytoFalse
P
ProvidemrInt
terviewwithaadefaultansw
werwhentheerespondenttdoesnotcho
oosearespon
nse.

Technically,thereissttillananswerrforeachqueestionwhenyyoulookatyo
ourdata,how
weverthe
ndtoeveryqu
uestionwhen
nitisntnecesssary.Agood
duseofthis
respondeentwillnothaavetorespon
featurew
wouldbeatexxtquestionfo
oroptionalco
omments.Iftherespondeentdidnothaaveacommeent,
theycouldsimplychoosetheNextbuttontoco
ontinuewithtthesurveywh
hilemrInterviewwillrecorrd
therespo
onseasthepredetermineeddefault.

165

Chapter15EnhancingSurveyFlow

SurveyProgrammingFundamentals

MustAnswer
TheMustAnswerpropertycanbeappliedattheIOMlevel,oronaquestion,pageorblocklevel.
Routing(Web)
Name.MustAnswer=False

Thefirststatementwouldonlyapplytoaspecificquestion.TheIOMstatementabovewouldprepare
allquestionsinthestudytopotentiallynotgiveananswer.

IfmrInterviewisnotprovidedwithavaliddefaultanswer,thenthequestionwillneedtobe
answeredbytherespondentbeforegoingtothenextquestion.Theexceptionforthisisa
categoricalquestioninwhichtheminimumisnotstated(example[..5]).

DefaultAnswers
DefaultAnswerscaneitherbedirectlyassignedbytheprogrammerorusethepreassigneddefault
valueofNoAnswer.Youcanspecifydefaultanswersinthemetadataorroutingsections.
InMetadatasection:
Name"text"questiontype
DefaultAnswer(response);

OrRoutingsection:
Name.Response.Default=response
Item
Name
response

Description
Representsthequestionname
Representsavalidresponsetothequestion(validnumberforlongquestions,
categorynameforcategoricalquestions,etc.)

166

SurveyProgrammingFundamentals

Chapter15EnhancingSurveyFlow

Thefollowingisanexampleofaddingdefaultresponsesinthemetadata.

Example

TravelSpent"Inthepastyear,approximatelyhowmanymuchdidyouspendineach
categorylistedbelowforbusinessandleisuretravel?"loop
{
Transportation,
Accomodations,
FoodDrink"FoodandDrinks",
OtherMisc"OtherMiscellaneous"
}fields
(
BusTravel"BusinessTravel"
long[0..]defaultanswer(0);

LeisureTravel"LeisureTravel"
long[0..]defaultanswer(0)
)expandgrid;

Theresultwillnotchangewiththeadditionofthedefaults:

Howeverifanycellisleftblank,thedefaultanswerofzerowillbeenteredinsteadofmrInterview
issuinganerrormessageofMissingAnswer(s).

167

Chapter15EnhancingSurveyFlow

SurveyProgrammingFundamentals

Youcanevensetdefaultvaluesforcategoricalquestions:

Example

Metadata(enUS,Question,Label)

Age"Towhichofthefollowingagecategoriesdoyoubelong?"
categorical[1..1]
{
Under18"Under18",
_18to34"18to34",
_35to54"35to54",
_55plus"55andover",
Refused"PrefernottoAnswer"REF
}defaultanswer({Refused});

EndMetadata

Intheaboveexampleiftherespondentdoesntanswerthequestion,whentheyclicktheNextbutton
theanswerwillberecordedasRefused.

Anotherwaytosetthisdefaultwouldbeintheroutingsection:
Routing(Web)
Example

Age.Response.Default={Refused}
Age.Ask()
EndRouting

Tousedefaultsoptions,thedefaultanswermustbesettoavalidresponseforthequestion.

168

SurveyProgrammingFundamentals

Chapter15EnhancingSurveyFlow

Hiddendefaultresponses
ThekeywordNAistheassumedvalueforthepropertydefaultanswer.Ifyouhave:

TheMustAnswer=False
AresponseassignedtothekeywordNA
Nodefaultanswerresponsespecified

ThentheNoAnswerresponsewillbehiddenonthescreenandiftherespondentdoesnotanswerthe
questionandgoestothenextscreen,theNoAnswerresponsewillbeautomaticallychosenforthat
question.

Example

Metadata(enUS,Question,Label)
AddComments"Pleaseprovideuswithanyadditionalcomments."
text
codes({NoAnswer"NoComments"NA});

EndMetadata
Routing(Web)
AddComments.MustAnswer=False
AddComments.Ask()
EndRouting
Thescreendisplays:

Asyoucanseeabove,thereisnotaNoCommentsreplyonthescreenduetothepresenceofthe
MustAnswer=FalseandthelackofaDefaultAnswerspecified.

169

Chapter15EnhancingSurveyFlow

SurveyProgrammingFundamentals

InitialResponse
Insteadofassigningdefaultvalueswhentherespondentdoesnotansweraquestion,youcouldhave
anansweralreadyassignedtothequestionwhenitisfirstshowntotherespondent.Thiscouldbe
usedforlargegridsinwhicheveryresponsemaynotbeapplicabletotherespondent.Thisiscalledan
initialanswerandisappliedinthesamewayasthedefaultanswer.

Example

TravelSpent"Inthepastyear,approximatelyhowmanymuchdidyouspendineach
categorylistedbelowforbusinessandleisuretravel?"loop
{
Transportation"Transportation",
Accomodations"Accomodations",
FoodDrink"FoodandDrinks",
OtherMisc"OtherMiscellaneous"
}fields
(
BusTravel"BusinessTravel"
long[0..]initialanswer(0);

LeisureTravel"LeisureTravel"
long[0..]initialanswer(0)

)expandgrid;

Thiswouldbewhatthescreenwouldlooklikewhentherespondentfirstseesthequestion:

170

SurveyProgrammingFundamentals

Chapter15EnhancingSurveyFlow

Thecodeintheroutingsectiontosettheinitialvalueforthiscomplexquestiontypewouldbe:

Example

Metadata(enUS,Question,Label)

TravelSpent"Inthepastyear,approximatelyhowmanymuchdidyouspendineach
categorylistedbelowforbusinessandleisuretravel?"loop
{
Transportation"Transportation",
Accomodations"Accomodations",
FoodDrink"FoodandDrinks",
OtherMisc"OtherMiscellaneous"
}fields
(
BusTravel"BusinessTravel"
long[0..];

LeisureTravel"LeisureTravel"
long[0..]

)expandgrid;

EndMetadata

Routing(Web)

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

EndRouting

Initialvaluewillonlybesetthefirsttimetherespondentisshownthequestion,meaningif
theyusethepreviousbuttontogobacktoquestions,theiranswerswillnotberesetagain
iftheyhavechangedthevalues.Ifyouwouldliketoalwaysresetthevalues,thenusethe
QuestionName.Response.Value=response.

171

Chapter15EnhancingSurveyFlow

SurveyProgrammingFundamentals

Exercise
Openmealswithstyle.mddfileandmakethefollowingmodifications.
MakeHealthCommallowtherespondenttomovepastthequestionwithoutanswering
GivetheHealthAttribsloopinitialvaluesofNeutral
AddthefollowingquestionaftertheHealthAttribsgrid:
FastFoodComments
Pleaseelaborateonwhyyou[AGREE/DISAGREE]withthestatement

Eatingfastfoodcanbehealthy.

PrefernottoAnswer

RespondentswhochoseNeutralfortheattributeEatingfastfoodcanbehealthy
shouldnotbeaskedtheFastFoodCommentsquestion.
FortheinsertAGREEORDISAGREE,insertthewordagreeiftherespondentchose
StronglyAgreeorAgreefortheEatingfastfoodcanbehealthyattribute;insert
disagreeiftherespondentchoseStronglyDisagreeorDisagree.
(Hint:Ifyouneedhelpdetermininghowtoreferenceoneattributewithinagrid
outsidethegrid,refertotheinformationitemonpage106.)

172

SurveyPrrogrammingFundamentalls

Chapterr16CustomizingtheStandardErrorMessages

Chapte
er16 Cu
ustomizing
gtheStan
ndardErrrorMessa
ages
Theremaaybetimesw
whenthestan
ndarderrorm
messagesaren
notdescriptivveenoughforraspecific
question,oryourorgaanizationhasstandardsfortheerrorteextthatarediifferentthanthedefaults.You
cancontrrolthetextoffthestandarderrormessaages.

Inthischapterw
wewill:
Learnthekeywordsasso
ociatedwiththe
standardeerrormessagess
Customizeethetextoftheeerrormessagges
withinyou
urscriptforaspecificquestio
on
Changethestandarderrrormessageforall
surveys

ndarderrorm
messagehasaanameassociiatedwithitaandislistedin
nthetablebeelow.
Eachstan
Message
eName
MissingA
Answer

NotNumeric
NotIntegger
NotDate
NotInRan
nge
NotSingle
eAnswer
TooFewA
Answers

MessageTexxt
Missingansw
wer(s).

Whend
displayed
TherespondentclickksNextwitho
outansweringgthe
question,andthescriptdoesnotspecifyadeffault
answer.Alsoappliesswhentherespondentdoees
notenteranswersin
nallcellsofagrid.
Answer'{AN
NSWER}'isnot
Theresponsecannottbeconverteedintoavalid
d
long(integer)ordou
numeric.
uble(decimal),asappropriiate.
Answer'{AN
NSWER}'isnot
Theresponseisanumericvalue,butisnotan
anintegervaalue.
integervalue.
Answer'{AN
NSWER}'isnota Theresponsecannottbeconverteedintoavalid
d
validdate.
date.
Answer'{AN
NSWER}'isnot
Theresponsedoesn
notfallwithintherange
inrange'{RA
ANGE}'.
specifieedforthequeestion.
Onlyoneansweris
Moreth
hanonerespo
onsewascho
osenfromasiingle
allowed.
choicerresponselist.
Thereareto
oofewanswers, Thenum
mberofrespo
onseschosenfromamultiiple
atleast{MIN
NANSWERS}aare choicelistislessthantheminimu
umnumber
required.
requiredforthequeestion.

173

Chapter16CustomizingtheStandardErrorMessages

MessageName
TooManyAnswers

MessageText
Therearetoomanyanswers,
only{MAXANSWERS}are
allowed.

CannotCombine

Answer'{ANSWER}'
({CATEGORY})cannotbe
combinedwithotheranswers.
Answer'{ANSWER}'
({CATEGORY})hasaresponse
butisnotselected.
Answer'{ANSWER}'isnotvalid.

OtherNotSelected

InvalidText

TooLittleText

TooMuchText

PlayerNavigationDisabled

Theanswerdoesnothave
enoughtext,currentlengthis
'{LENGTH}',minimumis
'{MINLENGTH}'.
Theanswerhastoomuchtext,
currentlengthis'{LENGTH}',
maximumis'{MAXLENGTH}'.
Youhaveusedthebrowser
buttons,pleaseusethe
Next/Previousbuttonsbelow.

SurveyProgram

Whendisplayed
Thenumberofresponseschosenfrom
amultiplechoicelistisgreaterthanthe
maximumnumberallowedforthe
question.
Morethanoneresponsewasselected,
oneofwhichwasmarkedasexclusive.
The'Other'responseboxhastextfilled
in,buttheOtherresponsehasnot
beenselected.
Atextresponseisnotintheformat
specifiedinthequestion;forexample,
notavalidtelephonenumber.
Thenumberofcharactersinatext
responseislessthantheminimum
specifiedinthequestion.
Thenumberofcharactersinatext
responseisgreaterthatthemaximum
specifiedinthequestion.
Therespondentusedthebrowser's
navigationbuttonswhentheproject
doesnotallowthis.

TheabovetableislistedintheDDLatthislink:
DDL.chm::/interviewscripting_errors_standard.htm

Youcanchangethemessagesassociatedwiththeerrorsin3ways:

174

GloballyforallmrInterviewprojects
Forallquestionswithinametadatafile
Foraspecificquestion

SurveyProgrammingFundamentals

Chapter16CustomizingtheStandardErrorMessages

Globalchangestoerrormessages
Tochangethewordingoferrormessagesgloballyforallprojects,theyarecontainedinthe
StandardTexts.mddfileonthemrInterviewserver.Pleasenotethatthisfileholdsthetranslationsfor
theerrormessagesaswell.Ifyouproducemultilingualstudies,youwillneedtotranslatethenew
messagestoanyadditionallanguagesnecessary.

Errormessageschangesforaspecificmetadatafile
Toreplacetheerrormessagetextforthewholescript,includeaStandardTextsblockwithanErrors
blockinthemetadataasshownbelow.

StandardTextsblockfields
(
Errorsblockfields
(
MessageName1"Text1"info;
MessageNamen"Textn"info;
...
);
);

Item
Description
MessageName1, Nameofthestandardmessageasshowninthetablepreviously.
MessageNamen
Text1,Textn
Representsthereplacementmessagetext

ThefollowingexamplewillchangethedefaulterrormessageMissingAnswer(s)forallquestions
withinthissurvey.

Example

Metadata(enUS,Question,Label)
StandardTexts"StandardTexts"blockfields
(
Errors"Errors"blockfields
(
Missinganswer"Pleaseanswerthequestion."
info;

);

);

EndMetadata

175

Chapter16CustomizingtheStandardErrorMessages

SurveyProgram

Ifarespondentdidnotchooseananswerforanyquestionwithinthesurvey,theywouldsee:

Errormessageschangesforaspecificquestion
Changingtheerrormessageforaspecificquestionisverysimilartothemethodforeveryquestion
withinthesurvey.ThedifferenceisthattheStandardTextblockmustbeaddedtoahelperfield
attachedtothequestion:
Metadata(enUS,Question,Label)

QuestionName"text"questiontype
helperfields(
StandardTexts"StandardTexts"blockfields
(
Errors"Errors"blockfields
(

MessageName1"Text1"info;

MessageNamen"Textn"info;

...
);
);
);

Item
helperfields
MessageName1,
MessageNamen
Text1,Textn

176

Description
Keywordusedtostoreadditionalinformationforafield/question
Nameofthestandarderrormessage.
Representsthereplacementmessagetext

SurveyProgrammingFundamentals

Chapter16CustomizingtheStandardErrorMessages

Customizingtheerrormessage
Youcancustomizethewordingofthemessagebyusingsomeofthesubstitutionmarkerslistedinthe
tablebelow.Enclosethemarkersincurlybracketswheninsertingintotheerrortext.
SubstitutionMarker
ANSWER
RANGE
QUESTION
QUESTION_NUMBER
LENGTH
MINLENGTH
MAXLENGTH
MINANSWERS

Description
Therespondent'sanswer.
Thevalidanswerrangeforthequestionasdefinedinthemetadatasection.
Thequestionname.
Thequestionnumber.
Thelengthoftheresponsetext.
Theminimumlengthforatextresponse.
Themaximumlengthforatextresponse.
Theminimumnumberofanswersthatmustbechosenfromamultiplechoice
list.
Themaximumnumberofanswersthatmaybechosenfromamultiplechoice
list.
Thetextofasinglemultiplechoiceresponse.
Theerrormessageassociatedwithaninternalerror.

MAXANSWERS
CATEGORY
ERROR

Thisexamplewillmaketherespondentserrormessageclearerinitsmeaning.

Example

DaysTravelYr"Onaveragehowmanydaysperyeardoyoutravelforbusinessorleisure?"
long[0..365]
helperfields(
StandardTexts"StandardTexts"blockfields
(
Errors"Errors"blockfields
(
NotInRange"{ANSWER}ismorethanthenumberofdaysinayear.Pleasetry
again."
info;
);
);
);

177

Chapter16CustomizingtheStandardErrorMessages

SurveyProgram

Whentherespondentsanswerisoutoftherange,itwilldisplayanewerrormessage:

178

SurveyPrrogrammingFundamentalls

Chaptter17Functio
ons&Subrou
utines

Chapte
er17 Fu
unctions&
&Subrouttines
WithDim
mensionsScrip
pting(andoth
herprogramm
minglanguages),youcanccreatereuseeablecodethaat
willhelpyoutodocerrtainactions,suchasvalid
datequestionlogicorspeccificformattin
ngissues.

Inthischapterw
wewill:
DefineFun
nctionsandSubroutines
Learnhow
wtowriteFunctionsand
SubroutineesinDimensio
onsScripting
Seeexamp
plesofFunctionsandSubrou
utines
inDimensiionsScripting

nctionsan
ndSubrouttines
DefinittionofFun
Afunctio
onorsubrouttineisasectio
onofcodewiithinascriptw
whichperformsaspecifictaskandis
relativelyyindependen
ntoftheremaainingscript. Thesearetermsthatarecommontoo
other
programminglanguagges,notspecifictoDimenssionsScriptingg.
nes,includingg:
Thereareeseveraladvaantagestoussingfunctionssorsubroutin

Reducingtheduplicationo
R
ofcodeinaprrogram
E
Enablingreus
eofcodeacrossmultiplesscripts
complexpro
D
Decomposing
oblemsintosimplerpiecess(thismakestthemeasierttomaintainand
a
add/subtract
functionalityasneeded)
Improvedreadabilityofap
program

Thepartssofafunction
norsubroutinemayinclud
de:

Abodyofcod
A
detobeexecu
utedwhenthesubroutineiscalled
P
Parametersth
hatarepassedtothesubroutinefromtthepointwheereitiscalled
d
A
Avaluethatis
sreturnedtothepointwh
herethecallo
occurs(functiononly)

onceptoffuncctionsandsubroutines.
Letslookkatsomeverrybasicexamplestounderrstandtheco

179

Chapter17Functions&Subroutines

SurveyProgrammingFundamentals

Subroutine
Todefineasubroutine:
SubName(var1,var2,varN)
Statements
EndSub

Tocall(use)asubroutine:
Name(parameter1,parameter2,parameterN)

Item
Sub
EndSub
Name
Statements
var1,var2,varN
parameter1,
parameter2,
parameter3

Description
Marksthestartandendofasubroutine
Representsauniquenamegiventothesubroutine
Representsanystatementstobeexecutedwithinthesubroutine
Representsthenameofvariablesthatarepassedtothesubroutinefromthe
pointwhereitiscalled.Thevariablestogetherarecalledtheargumentlist.
Representstheactualparametersthatarepassedtothesubroutine.The
orderoftheseparameterswillmatchupwiththevariablesonthesubroutine
(example:parameter1istheinformationthatwillbeinsertedinthe
subroutinerepresentedasvar1)

SubroutineExample
Dependingonthespecificlookofyoursurveys,youmaywanttocontrolthecolumnwidthsofagridat
adefaultlevelforallgrids,orhaveindividualcontrol.Ifyouneedindividualcontrol,itwouldbeniceto
haveawaytoindicatethespecificspergridonasinglelineinthescript.Wecancreateasubroutine
tohelpuswiththis.
Supposeyouhadtwogridsinyourstudythatafterthedefaultstyleswereapplied,theylookedlike
this:

180

SurveyProgrammingFundamentals

Chapter17Functions&Subroutines

Lookingatthegrids,theymightlookbetterwithsomespecificstylesappliedtothem.Aswelearnedin
thestylesection,youcouldspecifythestyleforeachgrid(AirlineRatingandInterestinLocation)inthe
routingsection:

Example

Routing(Web)
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
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()
EndRouting

181

Chapter17Functions&Subroutines

SurveyProgrammingFundamentals

Thepreviouscodewouldproducethefollowinglook:

Nowwemightsaythatthiscodecouldbeusefulinmanystudies.Asyoucansee,wearerepeatingthe
samebasictexteachtime,justchangingthevaluesofthestylepropertiesandthequestionitapplies
to.Thisrepetitivenessmakesitacandidateforasubroutine.

First,createthesubroutinesstructureandgiveitanamethatiseasilyrecognizable:
SubGridStyle1()

EndSub

182

SurveyProgrammingFundamentals

Chapter17Functions&Subroutines

Then,askyourselfwhatwillchangeeachtimeaboutthelinesofcode;thequestionnameandthe
valuesofthestyleswillchangeeachtime,sotheyneedtobereplacedwithavariabletorepresent
thoseitems:
SubGridStyle1(QuestionName,ColHeadWid,ColWid,ColWrap)
EndSub

QuestionName,ColHeadWid,ColWid,andColWraparesimilartotemporaryvariables,so
thenamescanbeanythingyoulike.

Next,addthecode.Beginnersmayfindithelpfultoaddthecodeforonequestionwithoutthe
substitutionsthenmakethechangestothatcodewiththeparameters.

SubGridStyle1(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

EndSub

LookingattheaboveexamplewewillneedtochangeAirlineRating,300px,70px,andtrueto
matchthevariablenameswedefinedonthefirstlineofthesubroutine:

SubGridStyle1(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

EndSub

183

Chapter17Functions&Subroutines

SurveyProgrammingFundamentals

Theabovesubroutinealonedoesnothing.YouneedtoCallthesubroutineandspecifytheparameter
informationforaspecificaction.Hereisthecompletedsubroutineexample:

Example

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

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

SubGridStyle1(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

EndSub

EndRouting

Function
Asstatedearlierinthischapter,afunctiondiffersfromasubroutineinthatitcanpassavaluebackto
wherethecalloriginated.Inthesyntaxbelow,youwillseeitisverysimilartothesubroutine,butnow
youmaysetavalueequaltothefunctionnametopassbackandusewithinyourscript.
FunctionName(var1,var2,varN)

Statements
Name=value

EndFunction

Tocall(use)afunction:
Name(parameter1,parameter2,parameterN)

184

SurveyProgrammingFundamentals

Chapter17Functions&Subroutines

Item
Function
EndFunction
Name
Statements
var1,var2,varN
Value
parameter1,
parameter2,
parameter3

Description
Marksthestartandendofafunction
Representsauniquenamegiventothefunction
Representsanystatementstobeexecutedwithinthefunction
Representsthenameofvariablesthatarepassedtothefunctionfromthe
pointwhereitiscalled.Thevariablestogetherarecalledtheargumentlist.
Avaluethatisreturnedtothepointwherethefunctioncalloccurred
(Optional)
Representstheactualparametersthatarepassedtothefunction.Theorder
oftheseparameterswillmatchupwiththevariablesonthefunction
(example:parameter1istheinformationthatwillbeinsertedinthefunction
representedasvar1)

185

Chapter17Functions&Subroutines

SurveyProgrammingFundamentals

Supposewehadasharedlistoftravelagenciesthathad30categories:

Example

Metadata(enUS,Question,Label)
Agencylst""define
{
Agency1"TravelAgency1",
Agency2"TravelAgency2",
Agency3"TravelAgency3",
Agency4"TravelAgency4",

Agency30"TravelAgency30"
};

AgencyHeardOf"Whichofthefollowingtravelagencieshaveyouheardof?"
categorical
{
useAgencyLst
};

'CreateafilterforAgencyUsetobetheresponsesofAgencyHeardOf
AgencyUse"Ofthoseyouwereawareof,whichtravelagencieswouldyouconsiderusing
tobookyourtravel?"
categorical
{
useAgencyLst
};
EndMetadata

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

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

EndRouting

AndyouwantedtoforcethestyleofthenumberofcolumnsfortheAgencyUsequestiontohaveno
morethan10categoriesineachcolumn.SincethecategoriesofthequestionAgencyUseare
dependentontheresponsetoAgencyHeardOf,wewillneedtofindoutthenumberofcategories
choseninAgencyHeardof,anddivideby10toseehowmanycolumnsweneedusingtheAnswerCount

DimensionsFunctionwelearnedin

186

SurveyProgrammingFundamentals

Chapter17Functions&Subroutines

BasicRoutingLogic,page60.Sincedividingournumberofresponsesby10maynotresultinawhole
number,wewillalsouseabuiltinfunction,int(),whichreturnstheintegerportionofanumber.

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

DimActual,IntegerValue,DecimalValue

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

IfDecimalValue>0Then

agencyuse.Style.Columns=IntegerValue+1
Else

agencyuse.Style.Columns=IntegerValue
EndIf
AgencyUse.Ask()

EndRouting

Sincethismaybeanactionwewouldwanttodoonotherquestionsorinotherstudies,itmightbe
advantageoustocreateafunctioninstead.Thefunctionbelowdoesjustthat.Itwascreatedina
similarwaytothesubroutine.

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

FunctionForceCols(filterQ)
DimActual,IntegerValue,DecimalValue
Actual=CDouble(filterQ.AnswerCount())/10
IntegerValue=int(filterQ.AnswerCount()/10)
DecimalValue=ActualIntegerValue

IfDecimalValue>0then

ForceCols=IntegerValue+1
Else

ForceCols=IntegerValue
EndIf
EndFunction
EndRouting

187

Chapter17Functions&Subroutines

SurveyProgrammingFundamentals

Youcanseethatthefunctionissetupverymuchthesameasthesubroutine,inthatithasaname
(ForceCols)andhasaparameter(filterQ).Thedifferenceisthatafterthefunctioniscompleted,itis
settoavalue.Thevaluescanbeanything.

Exercise
Openthereusable.mddfile.Makethefollowingroutingsectioncodemorereuseablewiththe
conceptslearnedinthischapter.Itwouldbehelpfultohaveapieceofreusablecodethatwould
allowyoutoeasilyspecifythenumberofresponsecolumns,columnwidth,andquestiontextcolorfor
specificquestions.
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()
EndRouting

188

SurveyPrrogrammingFundamentalls

Chap
pter18Valid
dation

Chapte
er18 Va
alidation
Inthelasstchapterwediscussedtheconceptsofsubroutinessandfunction
ns.Dimensionsscriptingh
hasa
uniquefu
unctionthataallowsyoutoeasilyvalidattelogicinqueestions.Wew
willalsolookatadditionall
conceptssthatwillhelp
pusvalidatethelogicofth
hesurvey.

Inthischapterw
wewill:
Validateatextquestiontofollowapatttern
Understan
ndhowtoadderrorsforcusttom
logic
Createcusstomlogicwith
htheuseof
Dimension
nsvalidationfu
unctions

ValidattingTextQ
QuestionP
Patterns
Youcaniincludestatem
mentswithinthemetadattathatwillcheckatextfieldtoseeifitmatchesa
specificp
pattern.Regu
ularExpressio
onsallowyoutodocreateverycompliccatedmatchaalgorithmswiitha
smallamountofcode.
Name"Text"text
N
V
Validation("e
expression");
Item
Name

Descrription
Metadataitemname

"Text"
text
Validatio
on
expressio
on

Textaassociatedwiiththeitem
Questtiontype.Mustbetextto
oaddaregulaarexpression
Prope
ertykeywordtoallowyoutoaddaregu
ularexpressio
on
RegullarExpression
nsyntax

189

Chapter18Validation

SurveyProgrammingFundamentals

Testyourexpressionsthoroughly,astherearemanyvariationstoregularexpressions,toonumerous
toplaceinthismanual.Hereareafewtohelpyouunderstandtheexamplesbelow.
Symbol
\w
\W
\d

Description
Matchesanywordcharacter(az,AZ,09)
Matchesanynonwordcharacter.
Matchesanydecimaldigit.Equivalentto\p{Nd}forUnicodeand[09]fornonUnicode,
ECMAScriptbehavior.
Matchesanynondigit.Equivalentto\P{Nd}forUnicodeand[^09]fornonUnicode,
ECMAScriptbehavior.

\D

TheDDLdoesreferenceregularexpressions:DDL.chm::/aliasmap_regularexpressions.htm
however,therearealsomanyreferencesonthewebaswell,suchas:
http://en.wikipedia.org/wiki/Regular_expressionsand
http://regexlib.com/cheatsheet.aspx.

Thefollowingexamplewillcheckthelengthofthephonenumberandalsoifitfollowsthespecific
patternwith2dashes.

Example

Phone"Pleaseenteryour10digitphonenumberwithdashes:"
text[7..20]
validation("\d{3}\d{3}\d{4}");

Theregularexpressionaboveshowsyouwant3decimaldigits(numbers)adash,3morenumbersa
dashand4numbers.

190

SurveyProgrammingFundamentals

Chapter18Validation

Thenextexampleismoreflexible,allowingyoutocheckanemailaddresstoensureitcontainsan@
sign.

Email"Email:"
text[5..100]
Example
helperfields(
StandardTexts""blockfields
(
Errors""blockfields

(
InvalidText"Youmustenteravalidemailaddresswithan@andperiod."
info;
);
);
)validation("[.\w]+\@[.\w]*[.\w]+\.[.\w]*");

Thisexpressionensurestherespondentansweredadash,periodoranywordcharacter(az),thena
mandatory@sign,followedbyadash,periodoranywordcharacter.

191

Chapter18Validation

SurveyProgrammingFundamentals

CheckingCustomLogic
Therearemanytimesyouwillneedtodologiccheckswithinyoursurveythatarenotcoveredbythe
standarderrormessages.Themostefficientwaytoachievethisisthroughcustomvalidation.The
conceptisaspecialtypeoffunctionthatistieddirectlytoaquestion.

Functionfunctionname(Question,IOM,Attempt)

Statements
functionname=True
Statements
functionname=False
EndFunction

Item
Function
EndFunction
functionname
Question
IOM
Attempt

Statements
True
False

192

Description
Definesthestartandendofthefunction
Representstheuniquenamegiventothefunction
Parameterthatrepresentsthequestionyouareattachingtothefunction(this
willalwaysbeQuestion)
ParameterfortheInterviewObjectModel(ThiswillalwaysbeIOM)
Parameterforthenumberofcurrentcustomvalidationattempts(Thiswill
alwaysbeAttempt,ifused,butitisanoptionalparameter).Couldbeusedto
setthenumberoftimesthefunctionshouldattempttoreceiveaTruevalue.
RepresentstheDimensionsscriptingstatementstodoanyactionandreturna
value,suchaschecklogic
ValuesthattheDimensionscustomvalidationfunctionmustpassback.These
specialfunctionsmustsetthefunctionnametotrueorfalse

SurveyProgrammingFundamentals

Chapter18Validation

Tosetthevalidationfunctiontouseforaquestion,usethefollowingstatementintheroutingsection
somewherepriortoaskingthequestion:
Routing(Web)
Name.Validation.Function=functionname
Name.Ask()
EndRouting
Item
Name
Validation.Function
functionname

Description
Nameofthequestionyouwishtovalidate
Propertiestosetthevalidationfunctionforthequestion.
Representstheuniquenamegiventothefunction

Thereareafewthingstonoteaboutcreatingcustomvalidationfunctions:

Toreferenceanothermetadataitem(besidesthequestionyouarevalidating)insidethe
function,youneedtoreferencethequestionwithIOM.Questions.QuestionName.
ThefunctionmustreturneitheraTrue(logiciscorrect,moveontothenextquestion)orFalse
value(logicisnotcorrect,issueanerrormessageifthenumberofattemptshasnotbeenmet).
TheycanonlyhavetheparametersQuestion,IOM,andAttempt.Ifyouwanttoincludemore
variableinformationintothefunction,onewaytoachievethisistoaddcustompropertiesin
themetadataofthequestionyouwishtovalidate.(Moretocomeonthissubject.)

Addingcustomerrors
Inthenextexamples,wewillbecreatingcustomizedlogicthatmayrequireyoutohavethe
respondentreanswerthequestion.Todothataction,youneedtoaddyourownerrormessage.You
cancreateerrorsthathavethesamepropertiesasthestandarderrormessages.Intheroutingsection
youwouldadd:

Name.Errors.AddNew("errorname",errortext.label)

Item
Name
Errors.AddNew
errorname
errortext

label

Description
Nameofthequestionyouwanttoapplyanerrormessageto
Statesyouwanttoaddanewerrortothestandardsetoferrormessages
Representstheuniquenamegiventotheerrormessage
Representstheinfoitemcreatedtoholdthetextfortheerrormessage.Youcan
justaddtextindoublequotesintheroutingsectionforthis,butitishighly
recommendedtomaketheinfoitem.
Willshowthelabeloftheinfoitemastheerrormessagetext

193

Chapter18Validation

SurveyProgrammingFundamentals

Youdefinetheerrormessageyouwanttouseasaninfoiteminthemetadatasection.This
isimportantformultilingualprojectsbecauseitmakesthemessagetextavailablefor
translation.

Theexamplebelowisacategoricalgridthatdisplaysacolumnofnumericboxestoenterinformation
thatshouldaddto100%.

Example

Metadata(enUS,Question,Label)
Activitiesdefine
{
Train"Onatrain/trainstation",
Airplane"Inanairplane/airport",
Vehicle"InaVehicledrivingorriding",
Subway"SubwaySystem",
Walk"Walking",
OtherMode"Other"
};

PercActivity"Thinkingofyourtraveloverthelastyear,whatpercentageofyourtime
wasspentusingthefollowingmodesoftransportation?Thetotalshouldaddto100%."
loop
{
useActivities
}fields
(
QPercent"Percentage"
style(
Width="30px"
)
long[0..100]
initialanswer(0);

)expandgrid;

ErrorGridAddto100"Pleasecheckyourresponses.Responsesshouldaddupto100."
info;

EndMetadata

194

SurveyProgrammingFundamentals

Chapter18Validation

Intheroutingsection,wewillcreatethespecialDimensionsvalidationfunctiontomakesureourgrid
addsto100%asshownbelow.

Example

Routing(Web)
IOM.LayoutTemplate="Card_Blue_TopAndBottomErrors.htm"

PercActivity.Validation.Function="ValidateGrid100"
PercActivity.Ask()

FunctionValidateGrid100(Question,IOM,Attempt)
Dimcategory
Dimtotal

Ifattempt<=3Then

ForEachcategoryinQuestion
total=total+category.Item[0].Response.Value
Next

Iftotal<>100Then

Question.Errors.AddNew("ErrorGrid",
IOM.Questions.ErrorGridAddto100.Label)

ValidateGrid100=False

Else

ValidateGrid100=True

EndIf

EndIf
EndFunction

EndRouting

195

Chapter18Validation

SurveyProgrammingFundamentals

Letschangethescenarioslightly.Whatifyouwantedtomodifythequestion,sothatthequestion
priortothiswas:
Thinkingofyourtraveloverthelastyear,approximatelyhowmanyhoursdidyouspendusingsome
typeoftransportation?
Thiswillinvolvemodifyingourpreviousexampletobeabletoreferencethatquestionsresponse
withinthefunction.

Example

Metadata(enUS,Question,Label)

HrsTravelMode"Thinkingofyourtraveloverthelastyear,approximatelyhowmany
hoursdidyouspendusingsometypeoftransportation?"
long[0..8760];

HrsActivity"Thinkingofyourtraveloverthelastyear,howmanyhoursofyourtimewas
spentusingthefollowingmodesoftransportation?Thetotalshouldaddto
{#HrsTravelMode}."loop
{
useActivities
}fields
(
QHours"Hours"
style(
Width="30px"
)
long[0..]
initialanswer(0);

)expandgrid;

ErrorGridAddtohrs"Pleasecheckyourresponses.Responsesshouldaddupto
{#HrsTravelMode}."
info;

EndMetadata

196

SurveyProgrammingFundamentals

Chapter18Validation

Again,theroutingsectioniswherethevalidationhappens.Noticethereferencetotheadditional
questionwiththeIOM.Questionsprecedingit.

Example

Routing(Web)

IOM.LayoutTemplate="Card_Blue_TopAndBottomErrors.htm"

HrsTravelMode.Ask()

HrsActivity.Validation.Function="ValidateGridEqualDependentQ"
HrsActivity.Ask()

FunctionValidateGridEqualDependentQ(Question,IOM,Attempt)
Dimcategory
Dimtotal

Ifattempt<=3Then

ForEachcategoryinQuestion
total=total+category.Item[0].Response.Value
Next

Iftotal<>IOM.Questions.HrsTravelModeThen

Question.Errors.AddNew("ErrorGrid",IOM.Questions.
ErrorGridAddtohrs.Label)

ValidateGridEqualDependentQ=False

Else

ValidateGridEqualDependentQ=True

EndIf

Endif

EndFunction

EndRouting

197

Chapter18Validation

SurveyProgrammingFundamentals

Theaboveworksnicely,howeveritisveryspecifictothequestion.Theline:
Iftotal<>IOM.Questions.HrsTravelModeThen
Wouldhavetobechangedeverytimeitisusedforadifferentquestion,whichisnotagoodpractice.
Asstatedabove,oneofthebiggestdifferencesbetweenstandardfunctionsandcustomvalidation
functionsisthatcurrentlyyoucannotaddanyadditionalparameters.Thislimitstheflexibilityof
customvalidationfunctions.Onewaythatyoucouldpassparametersintoafunctiontomakeitmore
reusableisbyplacingcustompropertiesinthemetadata.

Addingcustompropertiestometadata
Custompropertiescanbeanyadditionalinformationattachedtoametadataitem.Onebasicwayto
addcustompropertiesisinthemetadatasection:
Name"text"[property]type
Item
Name
"text"
[property]
type

Description
Nameofthequestioninthemetadatasection
Textofthequestion
Representsanyinformationyouwantstoredinthemetadataassociatedwiththe
metadataitem
Representsthemetadataitemtype(categorical,long,etc.).Noticethecustom
propertiesarepriortothis.

Custompropertiesareanadvancedconcept,butanimportantonetorememberasyouprogresswith
yourDimensionsScriptinglearning.Letsaddacustompropertytoourpreviousexamplesothatwe
donothavetomakeourfunctionsospecifictothesesetsofquestions.Belowinboldyouwillnotice
theadditionofcustompropertiesthataddsthenameofthequestionwewanttouseinthefunction
tocomparetothesumofourgrid.

198

SurveyProgrammingFundamentals

Example

Chapter18Validation

Metadata(enUS,Question,Label)

HrsTravelMode"Thinkingofyourtraveloverthelastyear,approximatelyhowmany
hoursdidyouspendusingsometypeoftransportation?"
long[0..8760];

HrsActivity"Thinkingofyourtraveloverthelastyear,howmanyhoursofyourtimewas
spentusingthefollowingmodesoftransportation?Thetotalshouldaddto
{#HrsTravelMode}."
[dependentQ="HrsTravelMode"]
loop
{
useActivities
}fields
(
QHours"Hours"
style(
Width="30px"
)
long[0..]
initialanswer(0);

)expandgrid;

ErrorGridAddtohrs"Pleasecheckyourresponses.Responsesshouldaddupto
{#HrsTravelMode}."
info;

EndMetadata

199

Chapter18Validation

SurveyProgrammingFundamentals

Intheroutingyouwillseethechangetothecomparisonline.Noticetheadditionofthecommentsto
identifywhatisneededforthefunction.
Routing(Web)

Example
IOM.LayoutTemplate="Card_Blue_TopAndBottomErrors.htm"

HrsTravelMode.Ask()

HrsActivity.Validation.Function="ValidateGridEqualDependentQ"
HrsActivity.Ask()

FunctionValidateGridEqualDependentQ(Question,IOM,Attempt)
Dimcategory
Dimtotal

Ifattempt<=3Then

ForEachcategoryinQuestion
total=total+category.Item[0].Response
Next

Iftotal<>IOM.Questions[Question.Properties["dependentQ"]]Then

Question.Errors.AddNew("ErrorGrid",IOM.Questions.
ErrorGridAddtohrs.Label)

ValidateGridEqualDependentQ=False

Else

ValidateGridEqualDependentQ=True

EndIf

Endif

EndFunction

EndRouting

Nowthisfunctioncanbereusedindifferentprojects.Youcanseehowalibraryofcustomvalidations
willspeedtheprogrammingprocessovertime.

200

SurveyPrrogrammingFundamentalls

Chaapter19Com
mpoundQuesstions

Chapte
er19 CompoundQuestion
ns
Thecomp
poundtypeh
helpsyoutoaachieveaspecciallooktoyo
ourquestionn
nairewhenyo
ouwishtodissplay
multiplequestionsonthesamescrreenhorizonttally.Theseq
questionsmusthavetheco
ommon
urveys,butcaan
denominatorofasharedlistofcattegories.Thissistraditionallyusedinpaaperbasedsu
alsobedoneforwebbasedstudies.

Thisch
hapterco
overs:
Thedefinittionofacomp
poundquestion
n

Validatingcompoundqu
uestions
Differenceesbetweenloo
opsandcompo
ound
questions

Definin
ngCompou
undQuesttions
Inessencce,acompoundissimplym
multiplequesstions(includiinggrids)whiichallshareaacommonlisttof
categoriees.Thinkofaacompoundquestionasaacontainerfo
orotherquesttionsyouwishtodisplayo
on
thesameepagehorizontally.Thesyyntaxforaco
ompoundisassfollows:
C
CompoundNa
ame"Text"ccompound
{
{Categories}
}fields
(

Question1;
Q

Q
QuestionN;
);

Item
Compoun
ndName
"Text"
compoun
nd
categorie
es
fields
Question
n1,
Question
nN

De
escription
Un
niquenamefforthecompo
oundmetadataitem
Op
ptionalTextttodisplayacrossthetopofthescreeno
ofthecompo
oundquestion
n
Ke
eywordtocreeateacompo
oundmetadattaitem
Re
epresentstheecategoriesfo
orwhichthequestionsandloopsareto
obeasked.
Yo
oumayuseasharedlistheereifyouwissh.
Prrecedestheq
questionswith
hinthecompounditem
opsthatyouw
wanttodisplaysidebysid
de.
Caategoricalqueestionsandcategoricalloo

201

Chapter19CompoundQuestions

SurveyProgrammingFundamentals

Supposewewanttocreatethefollowinglookforoursurvey:

Youwillnoticeintheaboveexamplethatallthequestionsonthepagesharealistofairlines.Thenext
examplewillshowhowthiscanbecreatedasacompoundquestion.

202

SurveyProgrammingFundamentals

Example

Chapter19CompoundQuestions

Metadata(enUS,Question,Label)
Airlines""define
{
United,
Delta,
BritishAirways"BritishAirways",
Luftansa"Luftansa"
};

AirlineQ"Pleaseanswerthefollowingquestionsabouttheairlineslisted."compound
{
useAirlines
}fields
(
FlownBefore"FlownPreviously"
Categorical[1..];
Trips6MoLoop"#ofTripsPast6Months"loopfields
(
trips""
long[0..400];

)expandgrid;
SatisLoop"Overall,howsatisfiedareyouwitheachAirline?"loopfields
(
RateAirline"RateAirline"
categorical[1..1]
{
VerySatisfied"VerySatisfied",
SomewhatSat"SomewhatSatisfied",
SomewhatDisSat"SomewhatDissatisfied",
VeryDissatisfied"VeryDissatisfied"
};

)expandgrid;
);
EndMetadata

Routing(Web)
AirlineQ.Ask()
EndRouting

203

Chapter19CompoundQuestions

SurveyProgrammingFundamentals

Thequestionsinsideofthecompoundaremissingitemsyoumightexpecttosee.Forexamplethe
FlownBeforequestionhasnoresponses,andthetwoloopshavenoiterationelements.Thisis
becauseallthequestionsinsideofacompoundwillmakereferencetothesharedcategoriesfromthe
firstsectionofthecompound.

Thecompoundcanbecreatedwithoutomittingtheseelements,butforthesakeof
efficiencyyouwillwanttousethemethodshownabove.

Validatingacompoundquestion
Validatingcompoundquestionscanprovechallengingforbeginnerprogrammers.However,withthe
skillstaughtintheprevioussectionsofvalidations,youareonyourwaytovalidatingcomplex
compoundquestionsaswell.Hereisasimplifiedversionoftheexampleabove.Thisexampleonly
includesthequestionsFlownBeforeandTrips6Mo_Loop.

Example

Metadata(enUS,Question,Label)
Airlinesdefine
{
United,
Delta,
BritishAirways"BritishAirways,
Luftansa
};

AirlineQ"Pleaseanswerthefollowingquestionsabouttheairlineslisted."compound
{useAirlines
}fields
(
FlownBefore"FlownPreviously"
Categorical[1..];
Trips6MoLoop"#ofTripsPast6Months"loopfields
(
trips""
long[0..400]
codes(
{
NoAnswer""NA
});
)expandgrid;
);

CompoundError"Missinganswers,pleasetryagain."
info;
EndMetadata

204

SurveyProgrammingFundamentals

Chapter19CompoundQuestions

Thelogicyouwillneedtocheckforwillbe:

IfFlownBeforeischosen,thenTrips6MoLoopmustbeanswered
IfFlownBeforeisnotchosen,thenTrips6MoLoopmustbenull

Thefollowingvalidationfunctioncreatesthoselogicchecks.Byreferencingthequestionsinsidethe
compoundbytheirposition(0=FlownBefore,1=Trips6MoLoop),itmakestheFunctionmorereusable
forothersimilarscenarios.

Example

Routing(Web)
IOM.LayoutTemplate="Card_Blue_TopandBottomErrors.htm"

AirlineQ.MustAnswer=False
AirlineQ.Validation.Function="ValidateSimpleCompound"
AirlineQ.Ask()

FunctionValidateSimpleCompound(Question,IOM,Attempt)
ValidateSimpleCompound=True
DimCat
ForEachCatInQuestion.Categories

If(Question.Item[0].ContainsAny(Cat)AndQuestion.Item[1].Item[Cat].Item[0]=Null)_
Or(NOT(Question.item[0].ContainsAny(Cat))And_
Question.Item[1].Item[Cat].Item[0]IsNotNull)Then

ValidateSimpleCompound=False

EndIf
Next

IfValidateSimpleCompound=FalseThen
Question.Errors.AddNew("CompoundError",IOM.Questions.CompoundError.Label)
EndIf

EndFunction

EndRouting

205

Chapter19CompoundQuestions

SurveyProgrammingFundamentals

Compoundvs.Loop
Youmayhavenoticedsimilaritiesbetweencompoundquestionsandloopsthathavemultipledifferent
typesofquestions.Thereareafewmaindifferencesbetweencompoundsandloopstobeawareof:

Youcannotdropthesimilarcategorylistsfromthequestionsinaloopasyoucanwitha
compound
Validationofacompoundquestionisverydifferentthatforagrid

206

SurveyPrrogrammingFundamentalls

Chapter20Wo
orkingwithSaample

Chapte
er20 Wo
orkingwiithSamplle
mrInterviewallowsyo
outoaccessinformationyouhaveabou
utyourpoten
ntialrespondeentsandusethis
toenhancethesurveyyexperienceand/ordata.Onescenario
osforusingtheadditionallinformation
wouldbeetocustomize
etheintervieewscreensbaasedonwhoiiscurrentlytaakingtheinteerview.

Inthischapterw
wewill:
Retrievein
nformationfromthesampletable
intotheDiimensionsScript
SendinforrmationfromtheDimensionss
scripttoth
hesampletable
Useatestsamplerecord
dlocallyinmrSStudio
nsscript
tocheckyourDimension

mplemanage
ementallowsyoutheoptio
ontobringad
dditionalinformationabou
utthe
Usingsam
respondeentsforused
duringtheinteervieweitherrby:

Displayinginfo
D
ormationheldinthetableetotherespo
ondent(Hello
o,Bob.Thankyoufor
p
participating.
)
C
Creatingaque
estiontohold
dthesampleinformationssoitiseasilyanalyzedwith
hthe
r
respondents
answers.

nthesamplettableaboutth
hecurrentrespondent:
Torefereenceinformattionstoredin
IOM.SampleR
Record.Item[""sampleField
d"]
Item
SampleFiield

Desscription
Rep
presentsthen
nameoftheffieldintheSQ
QLdatabasetthatholdstheeinformation
you
uwishtoretriieve.

207

Chapter20WorkingwithSample

SurveyProgrammingFundamentals

Hereisanexampleofpullinginformationfromasamplerecordintothetextofaquestion.Weare
assumingtheprojectssampletablehasafieldnamedTAgencythatholdstheTravelAgenciesused
bythepeopleinthesample.

Example

Metadata(enUS,Question,Label)

VerifyTravelAgent"Ourrecordsindicateyouhaveusedthetravelagency{Agency}inthe
past,isthiscorrect?"
categorical
{
Yes,
No
};

EndMetadata

Routing(Web)
VerifyTravelAgent.Label.Inserts["Agency"].Text=IOM.SampleRecord.Item["TAgency"]
VerifyTravelAgent.Ask()
EndRouting

IfaspecificrespondentstravelagencywasTravelAgencyXYZ,thentheirquestionwillappearas
shownbelow:

208

SurveyProgrammingFundamentals

Chapter20WorkingwithSample

Thenextexampledoesnotdisplaytherespondentsinformation,butratherstoresitinaquestionfor
analysispurposes.

Metadata(enUS,Question,Label)

Example
Region"Storestheregionwheretheylive."
text;

EndMetadata
Routing(Web)

Region.Response.Value=IOM.SampleRecord.Item["SRegion"]

EndRouting

Youcanalsoputinformationcollectedorderivedinthescriptintoasamplefield.

Metadata(enUS,Question,Label)

Example
ReceiveTravelInfo"Checkhereifyouwishtoreceiveanemailregardingtravelsafety."
boolean;

EndMetadata

Routing(Web)
ReceiveTravelInfo.Ask()
IOM.SampleRecord.Item["WantsEmail"]=ReceiveTravelInfo.Response.Value
EndRouting

TheaboveexamplewillstoreaTrueorFalseinthesamplefield,providingyouhaveasamplefield
calledWantsEmail.

TestingsampleinformationwithinmrStudio
Youcaneasilytesttoseeifyouarecorrectlypullingyoursampleinformationintothescript.mrStudio
allowsyoutocreateatestsamplerecord.Todothis:
Accessthefile:
C:\ProgramFiles\SPSSDimensions\mrStudio\4.0.0.0\Interview\DefaultSample.xsu.

209

Chapter20WorkingwithSample

SurveyProgrammingFundamentals

ThisisanXMLdocumentwhichmrStudioreadsasasamplerecordbydefault.Thedefaultfileisshown
below:

210

SurveyProgrammingFundamentals

Chapter20WorkingwithSample

Item
<SampleRecordID=ID1>
</SampleRecord>
<Samplefields>
</SampleFields>
<SampleField>
</SampleField>
<name>
</name>
<type>
</type>
<value>
</value>

Description
Marksthebeginningandendofthesamplerecord.Canonlycreate
asinglerecordfortestingwithinmrStudio.
Marksthebeginningandendofthesamplefieldsfortherecord.
Marksthebeginningandendofasamplefield.
Tagstosurroundthenameofthesamplefield
Tagstosurroundthetypeoffield.SQLfieldtypesareused.Smallint
=2;Int=3;Datetime=7;Char,Text,Ntext,orNVarchar=8;Bit=11
Tagstosurroundthevalueyouwantthesamplefieldtohave.

YouhavetheabilitytocreateyourownfilesandaddadditionalSamplefieldsasshownbelow:

211

Chapter20WorkingwithSample

SurveyProgrammingFundamentals

Inordertoaccessthesampleinformation,makesurethatunder
ToolsOptionsSampleManagementRecord
youarereferencingthecorrect.xsufile.

TheexamplebelowwillassumeyouareusingthemodifiedTravelSample.xsuwiththeadditionalfield
forregion.
Metadata(enUS,Question,Label)

Example
Region"Storestheregionwheretheylive."text;

VerifyTravelAgent"Ourrecordsindicateyouhaveusedthetravelagency{Agency}inthe
past,isthiscorrect?"

categorical
{

Yes,
No

};

EndMetadata

Routing(Web)

Region.Response.Value=IOM.SampleRecord.Item["SRegion"]
VerifyTravelAgent.Label.Inserts["Agency"].Text=IOM.SampleRecord.Item["TAgency"]
VerifyTravelAgent.Ask()

EndRouting
Asyoucanseeinthescreenshotabove,youcaneasilycheckyourreferencestosamplefieldswithin
thetextofyoursurvey(SuchasAgencyXYZ),butwhenyouareaccessingthelocalspane,youcanalso
seethattheregionhasbeencorrectlyaddedtothequestion,Region.

212

SurveyProgrammingFundamentals

Chapter20WorkingwithSample

AlternativetoSampleManagementtopassinformationintothesurvey
Ifyouarenotusingsamplemanagement,youcansendoutseparateURLlinkstorespondentsthat
speakdifferentlanguages.ThenembedaparameterintheURLthatwillbepassedintothescriptto
setthelanguage.mrInterviewcanpassparametersontheURLusingthenamesI.User1through
I.User9.Thenyoucandothesamethingswiththeseparametersthatwedidwithsample
managementvariables.

URLtosendout:
http://www.servername.com/scripts/mrIWeb.dll?I.Project=myproj&I.User1=DEU
Example

Inthescript:
Routing(Web)

IOM.Language=IOM.Info.User1
EndRouting
TheaboveexamplewouldsetthelanguagetoGerman(DEU)fortheinterview.

213

Chapter20WorkingwithSample

214

SurveyProgrammingFundamentals

SurveyPrrogrammingFundamentalls

Chapter21Wo
orkingwithQu
uotas

Chapte
er21 Wo
orkingwiithQuotas
Quotasareasystemfforcontrollinggthenumberrofrespondeentsinterview
wedmatchingpredefined
criteria.FForexample,wemaybeaskedtointervview1000resspondentswiththerequirrementsthat500
aremaleand500arefemale.

In
nthischapterwillcover:
Anovervieewofthequotaprocess
Howtocheckandrespondtoquotasin
nthe
routingsecction
Checkingaandchangingq
quotasonline

Definin
ngSurveyQuotas
Tosetupaquotawen
needthreeiteems:

TThequestionthequotawillbebasedon
nscriptedinyyourmetadattasection.
T
Thetargetsfo
orthequota.
T
Thetypeofqu
uota

makingaquottabasedonth
heresponden
ntsgender.
Letslookkatasimpleexampleofm

Gender

Targets
Male
Female

500
500

onweshould
dhaveaquesttionforgender:
Inourmeetadatasectio

Example

Metad
data(enUS,Q
Question,Labeel)
Gende
er"Areyou...""
cate
egorical[1..1]
{
M
Male,
Fe
emale
};
EndM
Metadata

215

Chapter21WorkingwithQuotas

SurveyProgrammingFundamentals

Onceyouhavesavedthemetadatafile,youcancreateyourquotatargetsbyselectingToolsQuotas
orchoosingthequotabuttonfromtheInterviewOptionstoolbar:

Youwillseethequotatoolasshowninthepicturebelow.

Ontheleftofthescreenyouwillseealistofthequestionsinthesurvey.DraganddroptheGender
questionontothequotamatrix.

216

SurveyProgrammingFundamentals

Chapter21WorkingwithQuotas

Wecannowseethetwogendercategorieswithagreyboxtotherightofeach:

Next,doubleclickononeofthegreyboxestosetthetargets:

217

Chapter21WorkingwithQuotas

SurveyProgrammingFundamentals

Herewecansetthetargetandquotatypeforthecell.
Type
Normal
AllowOver

Counter

Description
Anormalquotawillreportquotafullwhenthequotacountofthecompletedand
pendinginterviewsisequaltothetarget.
Allowoverwillreportquotafullwhenthequotacountofcompletesisequaltothe
target.Note,thisdoesnotincludethependingandassuchyoupotentiallycangoover
quota.
Acounterquotaisreallynotaquotaatall.Thesystemwillnotstoprespondentsfrom
completinginterviewsoncethelimitisreached.Thistypeofquotaisusedfor
informationpurposesonly.

Onceyouhavesetthetargetandtypeforeachquotacellweneedtonamethequotamatrix.Wellcall
thisexampleQuotaGender.

NowSave.Thiswillcreateafiletypewitha.mqdextension.

CheckingQuotas
Nowthatwehavequotalimitsdefined,weneedtoaddlogictoourroutingsectionthattellsthe
sectiontocheckonthequota.Beforewedothat,letsaddanextraitemtoourmetadata.Weare
creatingascenariowhererespondentswillbeturnedawayfromthesurveybasedontheirresponses.
Letsaddamessagetouseforinformingtherespondentwhathashappened.

Example

Metadata(enUS,Question,Label)
Gender"Areyou..."
categorical[1..1]
{
Male,
Female
};

OverQuota"I'msorry,thequotaisfull."info;
EndMetadata

Intheroutingsection,wewillstartbydefiningatemporaryvariabletoholdourquotacheckandask
ourquotaquestion.

218

SurveyProgrammingFundamentals

Chapter21WorkingwithQuotas

Routing(Web)
Example

DimQuota_Pend_Result
Gender.Ask()
EndRouting

Youmustmakesurethatyoualwayscheckaquotaaftertherespondenthasanswered.

Nextaddthequotacheck:
Routing(Web)
Example

DimQuota_Pend_Result
Gender.Ask()
Quota_Pend_Result=QuotaEngine.QuotaGroups["QuotaGender"].Pend()
EndRouting

Asyoucanseeyoumustreferencethenameyougavethequotamatrix.Inthiswayyoucancreate
multiplequotamatrixesandcheckthematdifferentpointsofthesurvey.Thetemporaryvariable
Quota_Pend_Resultstorestheresultsoftheattemptedquotapend.Nowweneedtocheckthose
resultsandrespondaccordingly.

219

Chapter21WorkingwithQuotas

SurveyProgrammingFundamentals

Routing(Web)
Example

DimQuota_Pend_Result
Gender.Ask()
Quota_Pend_Result=QuotaEngine.QuotaGroups["QuotaGender"].Pend()
IfNot(IsSet(Quota_Pend_Result,QuotaResultConstants.qrWasPended))Then
IOM.Texts.InterviewStopped=OverQuota.Label
IOM.Terminate(Signals.sigOverQuota)
EndIf
EndRouting

TheIfstatementischeckingtoseeifthePend()attemptresultedinthesuccessofoneormorequota
cells.Ifthiswasnotthecase,thentherespondenthasfailedthequotacheck.Wewillsetthe
InterviewStoppedtexttothemessagewedefinedinaninfoiteminourmetadatasection.Thenwe
terminatetheinterview,flaggingtherespondentasoverquota.

220

SurveyProgrammingFundamentals

Chapter21WorkingwithQuotas

QuotasInmrStudio
IfyoutryrunningthisinmrStudionow,youwillgetanerrormessagebydefault.Onechoiceistoskip
overthecodewhenrunninginsideofmrStudiobyaddingacheckforwhenthescriptisinDebug
mode.
Routing(Web)
Example

DimQuota_Pend_Result
Gender.Ask()
IfNotIOM.Info.IsDebugThen
Quota_Pend_Result=QuotaEngine.QuotaGroups["QuotaGender"].Pend()
IfNot(IsSet(Quota_Pend_Result,QuotaResultConstants.qrWasPended))Then
IOM.Texts.InterviewStopped=OverQuota.Label
IOM.Terminate(Signals.sigOverQuota)
EndIf
EndIf
EndRouting

IOM.Info.IsDebugwillbeTruewheneverthesurveyisrunninginsidemrStudio.

mrStudiov.4.5andabovedoeshavethecapabilitytosimulatequotas.Noteyoumust
haveeitherMicrosoftSQLServer2000or2005,includingthefreeSQLServer2005Express
EditionandMicrosoftSQLServerDesktopEngine(MSDE)tousethisfeature.SeetheDDL
formoredetail:DDL.chm::/mrstudio_testing_quotas.htm

221

Chapter21WorkingwithQuotas

SurveyProgrammingFundamentals

ActivationwithQuotas
Nowthatthequotasarecreated,youneeduploadthe.mqdfileandactivatethestudywithspecial
optionsforquotas.YoucandothisdirectlyfrommrStudiousingToolsActivate,orthrough
DimensionNet.

ForinstructionsonActivatingquotaswithinDimensionNet,seetheDDL:
DDL.chm::/quota_dimnet.htm

Viewing&ChangingQuotas
YoucanviewandchangequotainformationonlineusingtheDimensionNetQuotasactivity.

Eachquotamatrixinyoursurveywillbeabuttononthelefthandsideoftheactivitypage:

222

SurveyProgrammingFundamentals

Chapter21WorkingwithQuotas

Selectingaquotagroupwilldisplaythecurrentquotacounts:

Youalsomayseeadropdownlistthatallowsyoutochangeadditionalquotainformation.

Type
DoNotEdit
Targets
All

Description
Viewonlymode.
Allowsyoutomodifythetargetsforeachquotacell.
Allowsyoutomodifythetarget,complete,pendingandtypeforeachquotacell.

223

Chapter21WorkingwithQuotas

SurveyProgrammingFundamentals

WhentheTargetsoptionisselectedtextboxeswillappear.Youcanraiseorlowerthecelltargets.Once
youhaveenteredthenewcorrecttargetsclicktheUpdatebutton.

224

SurveyProgrammingFundamentals

Chapter21WorkingwithQuotas

WhentheAllselectionischosenyoucaneditthetargets,completecount,pendingcountaswellas
changebetweenNormal,OverQuotaandCounterquotatypes.

225

Chapter21WorkingwithQuotas

226

SurveyProgrammingFundamentals

SurveyPrrogrammingFundamentalls

Chapter22 CreatingMulltiLingualPro
ojects

Chapte
er22 Cre
eatingMu
ultiLingu
ualProjeccts
Whenim
mplementingsstudiesindiffferentlanguages,Dimensio
onsallowsyo
outocreateaasurveyinab
base
languagee,andtheneaasilyaddlanguagestothemetadatafilee.Thechapteerwillreview
wtheprocessof
multilinggualstudies,ffocusingonthespecifictaasksforthesu
urveyprogram
mmer.

Intthischap
pterwew
willcoveer:
Anovervieewofhowtoeexecuteasurveeyin
multiplelaanguages
Settingtheelanguagewithinthescript

Tipsforcreeatingmultilin
ngualprojects

OverviiewofTran
nslatingStudiesinD
Dimension
ns
Whenap
projectwillbe
eruninmultiiplelanguagees,thebasicstepsare:

Createthesurrvey.mddfileeinabaselan
C
nguage.
U
UsemrTransla
atetoaddtraanslationstotthemetadataafile.
U
Uploadandac
ctivatethereevised.mddfiiletotheprojject.
B
Besurethatt
heErrorMesssage.mddfileehastheerrormessagestrranslatedforthelanguagees
y
youwillhave
inyourproject.

Onceyou
uhaveametaadatafile,you
ucanaddtheetranslationsthroughtheproduct,mrTTranslate.
mrTranslatereadsthe
emetadatafilleandpresen
ntsthetextoffyoursurveyinaformatssimilartoa
heet.Thenyo
oucanaddad
dditionallangguagesascolu
umnsinmrTrranslate.
spreadsh

mationonusin
ngmrTranslatte,seetheUssersGuideintheDDL:
Fordeetailedinform
mrTra
anslate.chm:://mrtranslate__overview.htm
m

227

Chapter22CreatingMultiLingualProjects

SurveyProgrammingFundamentals

Thensavethemetadatafileandnowitwillcontaintheadditionallanguages.Notethatwhenyoure
openthemetadatafileinmrStudio,youwillnotseetheadditionallanguageswithinthetextofthefile,
buttheyareinthemetadatafile.ToverifyadditionallanguagesareinthemetadatausingmrStudio:

ChoosetheMetadataExplorer
OpentheLanguages

Settingthelanguagewithinthescript
TousethemultilingualfunctionalitywithinmrInterview,youneedtosettheIOM.Language.You
couldaccomplishthisinmanyways.Hereareafewcommonmethods:

Createaquestioninwhichtherespondentchoosesthelanguage.
Havethelanguagestoredinasamplefieldandretrievetheinformationandsetthelanguage
fortherespondent.

Askaquestiontocollectandsetthelanguage
Whenyoudonotknowthepreferredlanguageofyourrespondent,asimpleintroductoryquestioncan
beaskedtocollectthelanguage.

228

SurveyProgrammingFundamentals

Example

Chapter22CreatingMultiLingualProjects

Metadata(enUS,Question,Label)
LanguageQ"Choosethelanguageforthissurvey:"
categorical[1..1]
{
ENU"English",
DEU"German",
ESN"Spanish"
};

EndMetadata

Routing(Web)

LanguageQ.Ask()

IOM.Language=LanguageQ.Categories.[LanguageQ].Name
EndRouting

Notethatintheexampleabove,thenamesoftheresponses(ENU,DEU,ESN)mustbethe3digit
Microsoftlanguagecodes.
Ifthescripthasthetranslationsadded,youwillbeabletoseethelanguageschangeswithinmrStudio
asyourunthesurvey.

Tofindafulllistofthelanguagecodes,seetheDDL:UserGuide.chm::/Intug
mrscriptmetadata_languages_3char.htm

Setlanguagefromasamplefieldvariable
Ifyoualreadyknowthepreferredlanguageandyouareusingsamplemanagement,afieldcanbeset
inthesampletabletoholdthe3digitlanguagecode.Thefollowingexampleassumesyoursample
tablehasafieldcalledSLanguage.

Example

Routing(Web)

IOM.Language=IOM.SampleRecord.Item["SLanguage"]

EndRouting

229

Chapter22CreatingMultiLingualProjects

SurveyProgrammingFundamentals

Tipsforcreatingmultilingualprojects
Creatingthescriptsformultilingualstudiesdoesnotneedtobedifficultaslongasyoufollowafew
simplerules:

230

Ifthetemplatescontaintextthatneedstobetranslated,uselocalizedtemplatesforeach
languagesothatthepropertextisshown.
VerifytheErrorMessage.mddfilehastheerrormessagesforthelanguagesyouwillbeusing.
Alwaysreferenceinfoitemsintheroutingsectionforanytext,suchascustomerrormessages
ortextinserts.TextintheroutingsectionisnotseenbymrTranslate,onlythemetadata
section.

SurveyPrrogrammingFundamentalls

Chaapter23Additionalinform
mationforAnalysis

Chapte
er23 Ad
dditionali
informatiionforAn
nalysis
Thissectiionshowsho
owtheDimensionsscriptin
nglanguageissnotonlyforcreatinginteerviews,butaalso
foranalysispurposes.Thissectionaddsoptionsstoyourinteerviewscripttthatwillspeeedtheanalysis
processb
byaddingcom
mmonstatistiicsandsumm
maryinformattion,suchasttopboxscoreesandalternaate
textforaanalysis.

Intthischap
pterwew
willcoveer:
Addingalternatetextforrreportingpurrposes
Addingspeecialstatisticsintotheintervview
script
Creatingfaactorscoresfo
orusewithstattistics

Alterna
ateTextfo
orAnalysis
Manyorgganizationsw
willaltertheteextofthequeestionsthatw
wereaskedin
nasurveyforreportingor
analysisp
purposes.Th
hemostcomm
monmethodistochangeffromquestion
nformatstosstatements
(Examplee:Whatisyo
ourgender?becomesReespondentGeender).Theealternateteextiscalledan
n
Analysiscontext.You
ucanaddthissinformationinafewdiffeerentways.TTwocommon
nwaysare
mrTranslateandmrSttudiotoviewandaddanallysiscontext.UsingmrTraanslatewillallowindividuaals
whoareunfamiliarwiithDimension
nsscriptingto
oaddthealteernatetext,asmrTranslateemasksthe
actualco
odewithitsin
nterface.Sinccethisisascrriptingcoursee,wewillfocu
usonaddingaanalysisconteext
withmrSStudio.
AddingA
AnalysisCon
ntextwithm
mrStudio
OpentheView
O
wmenu
ts
SelectContex
S
sis
ChooseAnaly
C

231

Chapter23AdditionalinformationforAnalysis

SurveyProgrammingFundamentals

YouwillnowseeablankspotbyalltextinthemetadatalabeledANALYSIS:.Youcanplacethe
alternatetextindoublequotesasshowninthepicturebelow:

Factors
Ifyouwishtoaddstatisticalelements,suchasameanorstandarddeviation,toyourcategorical
questions,thenyouneedtoaddamultipliertoeachresponsechoice.Evenifyoudonotaddthe
statisticalelements,factorscanalsobehelpfultoendusersofthedatacreatingcrosstabulationswith
mrTablesormrStudio.
Name"Text"categorical[min..max]
{ID1"AltText1"factor(value),
IDn"AltTextn"factor(value)};
Text
factor
value

232

Description
Keywordtoidentifyyouwishtoaddamultipliertotheresponseforstatisticalpurposes
Representsthenumericvalueyouwishtoassigntotheresponseforstatistics.

SurveyProgrammingFundamentals

Chapter23AdditionalinformationforAnalysis

Thisexampleshowsyouhowtospecifyvaluesforeachagerangeforstatisticsinusewithother
Dimensionsproducts,suchasmrTables,DesktopReporter,ormrStudiowithtablesscripting.

Example

Metadata(enUS,Question,Label)

Age"Towhichofthefollowingagecategoriesdoyoubelong?"
categorical[1..1]
{
Under18"Under18"factor(18),
_18to34"18to34"factor(26),
_35to54"35to54"factor(45),
_55plus"55andover"factor(55),
Refused"PrefernottoAnswer"REF
};
EndMetadata

CreatingQuestionItemsforAnalysis
Youcanalsoaddanalysiselementstothequestionstospeedtheavailabilityoftoplineandfinal
results.WewilldiscusstwodifferentmethodsforaddingelementsforAnalysis,ElementTypesand
AxisExpressions.

ElementTypesarenotseenduringinterviewingonlyinanalysis,suchasusingmrTablesor
creatingcrosstabulationswithmrStudio.Theyareasinglelineofinformation,suchasa
summaryitemormeanscore.
Axisexpressionsarealsonotseenduringinterviewing,butareusuallymorethanasingleline
ofanalysisresults.Anexamplewouldbeaddingapredeterminedrangeofcategoriestoalong
ordoubletypequestionforanalysispurposes.

233

Chapter23AdditionalinformationforAnalysis

SurveyProgrammingFundamentals

ElementTypes
Youusetheoptionalelementtypekeywordtocreateaspecialelementinmetadataforuseinanalysis.
Name"Text"type
{ID1"AltText1,
IDn"AltTextn",
IDElement"AltTextElement"elementtype(typevalue)
};
Item
Name

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
"Text"
Textassociatedwiththeitem(consideredthelabelintheobjectmodel).
Type
Identifiesthequestiontype(categorical,long,etc.)
ID1,IDn
Uniqueidentifyingnamefortheresponse.Thisneedstobeuniqueper
question,notmetadatafile.Rulesfortheresponsenamesarethesameasthe
nameofthequestion.
AltText1,
Optionaltexttoshowtherespondentinsteadofthenameofthequestion.This
AltTextn
willapplywhenthenameofthequestionisnotthesameasthetextyouwishto
showtherespondent.
IDElement
Uniqueidentifyingnameforthespecialelement.Rulesforthisnamearethe
sameasthenameofthequestion.
AltTextElement Texttorepresentthespecialelement
elementtype
Keywordthatindicatesyouwillbespecifyingusingaspecialelement
typevalue
Representsthekeywordslistedinthenexttabletostatethetypeofspecial
elementyouneed

Belowisatablewithafewcommonanalysiselements,representedbytype_valueinthesyntax
exampleabove.
Text
AnalysisCategory

AnalysisMean
AnalysisStdDev
AnalysisStdErr

234

Description
Anelementthatisusedonlyforanalysis.Youcanusethisvalueforcategories
thatyoudonotwanttoappearininterviews.Anexamplewouldbecreatinga
TopBoxorBottomBoxscore.
Ananalysiselementthatisusedtoshowthemeanvalueofavariable.
Ananalysiselementthatisusedtoshowthestandarddeviationofavariable.
Ananalysiselementthatisusedtoshowthestandarderrorofavariable.

SurveyProgrammingFundamentals

Chapter23AdditionalinformationforAnalysis

TofindafulllistofAnalysisElements,seetheDDL:
DDL.chm::/mrscriptmetadata_categorical.htm

Tousethetypeslisted,mostrequireadditionalproperties.Hereisthepreviousexamplewherethe
meanvaluehasbeenaddedtotheagequestion.Noticetheadditionalparametersrequiredfora
meanwithcategories.

Example

Metadata(enUS,Question,Label)
Age"Towhichofthefollowingagecategoriesdoyoubelong?"
Categorical[1..1]
{
Under18"Under18"factor(18),
_18to34"18to34"factor(26),
_35to54"35to54"factor(45),
_55plus"55andover"factor(55),
Refused"PrefernottoAnswer"REF,
Mean"MeanScore"[
CalculationType="Mean",
HasNoData=true,
ExcludedFromSummaries=true
]
elementtype(AnalysisMean)
};
EndMetadata

AnotherhelpfulelementtypeistheAnalysisCategory.Thisallowsyoutocreateadditionalelementsin
questionsthatarenotseenduringtheinterview,onlyinanalysis.Thefollowingdefinelistwillprovide
youwithaTopandBottomBoxScoreforeachquestionusingthelistintheanalysis.

Example

Metadata(enUS,Question,Label)
Rating5Ptdefine
{Top2"PositiveScores"elementtype(AnalysisCategory)expression("@*{VS,SS}"),
VS"VerySatisfied",
SS"SomewhatSatisfied",
Neutral,
Bot2"NegativeScores"elementtype(AnalysisCategory)expression("@*{SDS,VDS}"),
SDS"SomewhatDissatisfied",
VDS"VeryDissatisfied"
};
EndMetadata

235

Chapter23AdditionalinformationforAnalysis

SurveyProgrammingFundamentals

Inthepreviousexamplethe@representsanyquestionthedefineisusedwith.Ifyouwish
touseacombiningelementdirectlyinaquestionwithoutadefinelist,theexpression
wouldbe"qname*{VS,SS}"

AxisExpressions
Anotherwaytospeedtabulationprocesseswouldbetocreateanalysisitemscalledaxisexpressions.
Thesecancreatemanydifferenttypesofanalysisitems,acommononeininterviewscriptswouldbe
categoricalrangesonnumericquestions.
Theaxisexpressionsaredynamicallycreatedstatementsattachedtothemetadataquestions.The
syntaxisverysimilartowhatyouwoulddoinadatamanagementscript.
Name"Text"type
{ID1"AltText1,
IDn"AltTextn"}
axis("axis_spec");
Item
Name

"Text"
Type
ID1,IDn

AltText1,
AltTextn
axis
axis_spec

Description
Uniqueidentifierfortheitemwithinyourquestionnaire.Theymuststartwitha
letterorunderscore(_)andcontainonlyalphanumericcharactersorthe
symbols@,$,#,or_
Textassociatedwiththeitem(consideredthelabelintheobjectmodel).
Identifiesthequestiontype(categorical,long,etc.)
Uniqueidentifyingnamefortheresponse.Thisneedstobeuniqueper
question,notmetadatafile.Rulesfortheresponsenamesarethesameasthe
nameofthequestion.
Optionaltexttoshowtherespondentinsteadofthenameofthequestion.This
willapplywhenthenameofthequestionisnotthesameasthetextyouwishto
showtherespondent.
Keywordtorepresentelementswillbeaddedthatwillonlybeseeninanalysis
Representsmanydifferentsyntaxthatcreateselementstobeseeninanalysis

236

SurveyProgrammingFundamentals

Chapter23AdditionalinformationforAnalysis

Thefollowingexamplewillcollectalongquestiontypeduringtheinterview,buteasilyallowpeople
doinganalysistoviewthepresetrangesofanswersandameanvalue.

Example

Metadata(enUS,Question,Label)

HouseHold"Includingyourself,howmanypeoplecurrentlyliveinyourhousehold?"
long[1..20]
axis("{_1'One'expression('Household=1'),
_2to3'23'expression('Household>=2andHousehold<=3'),
_4to6'46'expression('Household>=4andHousehold<=6'),
_7plus'7andover'expression('Household>=7'),
mean'Mean'mean(household)}");

EndMetadata

Tipscreatinganalysiselements
Addinganalysiselementscanprovebeneficialforspeedingthetimeforanalysissetup.Afewthingsto
remember:

Theseitemscanbeaddedafterlivedatacollection,sodontworryifyoudonthaveallthe
analysisinformationupfront.
Themetadatasyntaxcheckwillonlybelookingforsyntaxmistakes,notifyourlogicactually
works.Makesuretocreatetestdataandhavesomeonechecktheanalysisfieldsforaccuracy.

Summary
Thischapterhasjustintroducedtheanalysisconceptsandbynomeanshasshownallthepossibilities.
AsyourknowledgeofDimensionsscriptinggrows,youwillseehowallpartsofDimensionsscripting
(interviewing,datamanagementandtabulation)areconnected.Thatknowledgewillallowyoutouse
thepowerofDimensionsScriptingtoitsfullestpotentialanddosomeamazingprojects.Youarenow
onthevergeofdoinggreatthingswiththispowerfullanguage.Remembertothinkoutoftheboxand
trynewwaystodothings,asthislanguagehassomanyfacetsandcapabilities.

237

Chapter23AdditionalinformationforAnalysis

SurveyProgrammingFundamentals

238

Vous aimerez peut-être aussi