Actions

ExpressionScript examples/da: Difference between revisions

From LimeSurvey Manual

(Created page with "Hvis du vil kontrollere, om det spørgsmål blev besvaret, kan du sætte en IF-sætning omkring dit output:")
(Created page with "Dette "oversætter" til: HVIS spørgsmål med kode q1 ikke er tomt, output "- " OG spørgsmålsteksten OG ": " OG svarteksten (join()-funktionen forbinder elementer som en ny...")
Line 193: Line 193:
<pre>{if(!is_empty(q1),join("- ",q1.question,": ",q1.shown),"")}</pre>
<pre>{if(!is_empty(q1),join("- ",q1.question,": ",q1.shown),"")}</pre>


This "translates" to: IF question with code q1 is not empty, output "- " AND the question text AND ": " AND the answer text (the join() function joins elements as a new string; ELSE: output nothing ("" means empty string).
Dette "oversætter" til: HVIS spørgsmål med kode q1 ikke er tomt, output "- " OG spørgsmålsteksten OG ": " OG svarteksten (join()-funktionen forbinder elementer som en ny streng; ELSE: output ingenting (" " betyder tom streng).


===Question with subquestions===
===Spørgsmål med underspørgsmål===





Revision as of 15:05, 2 January 2024

Template:Bemærk


Struktur

Den første del af artiklen vil beskrive, hvad udtryk kan bruges til, og hvor man kan finde/tilføje et udtryk. Anden del giver eksempler på, hvordan man bruger Expression.


Kategorier af udtryk

LimeSurvey bruger udtryk til følgende formål:


Relevans

Formål: Skjul spørgsmålsgrupper/spørgsmål

Relevans styrer, om en spørgsmålsgruppe eller et spørgsmål vises eller skjules. Hvis resultatet af udtrykket er "sandt" (dvs. 1), vil elementet blive vist. Ellers (hvis resultatet af udtrykket er "false" (dvs. 0)), vil elementet blive skjult.

Type Viser/skjuler Hvor kan man finde Skærmbillede
Spørgsmålsgruppe Relevans spørgegruppe Opret/Rediger spørgsmålsgruppe -> "Relevansligning:"
Spørgsmålsrelevans spørgsmål Opret/Rediger spørgsmål -> "Relevansligning:" File:Spørgsmålsrelevansligning screenshot.png
Underspørgselsrelevans underspørgsmål Rediger underspørgsmål -> "Relevansligning:" 30px


Validation

Formål: Validere input/handlinger på spørgsmål/underspørgsmål/svar

Validering kontrollerer, om respondentens input til et spørgsmål eller en handling er gyldigt eller ej. Hvis resultatet af udtrykket er "sandt" (dvs. 1), vil klassen "god" blive anvendt på elementet og valideringsmeddelelsen. Ellers, hvis resultatet af udtrykket er "false" (dvs. 0)), vil "error"-klassen blive anvendt på elementet og valideringsmeddelelsen. Du kan erklære en stil for disse klasser i template.css.

Type Validerer Hvor kan man finde Skærmbillede
Spørgsmålsvalidering spørgsmål Opret/Rediger spørgsmål -> "Logikfane" - > "Spørgsmålsvalideringsligning"
Underspørgsmålsvalidering underspørgsmål Opret/Rediger spørgsmål -> "Logikfane" -> " Underspørgselsvalideringsligning"

Tekstoutput

Formål: (Gør noget) og skriv noget tekst

Et udtryk kan bruges til at skrive noget tekst ud. For eksempel kan du teste eller beregne noget og angive output afhængigt af resultatet af testen eller beregningen. Det kan også bruges til at indsætte spørgsmålsteksten, svarene, spørgsmålstyperne, ... af et spørgsmål brugt før udtrykket bruges. Tekstoutput kan bruges overalt, hvor en tekst vises, og kan returnere alle slags resultater.

Use Case Description
Mikroskræddersy Juster en tekst, f.eks. skriv "Hr." eller "Fru" afhængigt af et kønsspørgsmål stillet før
Beregning Beregn en værdi og skriv den ud, f.eks. "Din familieindkomst er xxx"
Reference Indsæt en tekst fra et element, f.eks. "Dit navn er xxx. Hvor gammel er du?"


Svar lagrer

Formål: (Gør noget,) (skriv noget tekst) og gemme noget i databasen

The Equation Question Type kan bruges til at gemme noget i databasen. Du kan gøre noget med et udtryk, vise ligningsspørgsmålet (som ligner en tekstvisning) og gemme resultatet af udtrykket i databasen. Den gemmer svaret i svartabellen. Derefter kan resultatet bruges i statistikfunktionen, eller det kan også importeres til et af de formater, der leveres af LimeSurvey-eksportfunktionaliteten.

Eksempler på udtryk

Indsæt et svar fra et tidligere spørgsmål

Formål Indsæt et svar fra et tidligere spørgsmål
Type Reference
Eksempel Spørgsmål 1 (spørgsmålskode " Q00"): Hvilken by bor du i?
Spørgsmål to (spørgsmålskode "Q01") Hvor længe har du boet i CITY?
At gøre: Svaret fra spørgsmål et skal bruges i stedet for "BY" fra det andet spørgsmål.
Udtryk {QOO}
Beskrivelse Svaret i Q00 erstatter Q00-feltet fra det andet spørgsmål
Steps Opret/Rediger spørgsmål to
Indsæt "Hvor længe har du boet i {QOO} (år)?" ind i spørgsmålstekstfeltet
File:Simpelt udtryk bynavn.png

Brug af skjult ligningsspørgsmål til at autofylde et svar

Problem:

Forestil dig, at du har to spørgsmål Q1 og Q2. Q1 spørger respondenterne om deres alder. K2 ovenstående betingelser. Vi bør heller ikke glemme at gøre Q2 usynlig (spørgsmålet vil ikke blive vist i undersøgelsen, men værdierne vil være via "baggrundsprocessen" i svartabellen).

For at udfylde databasen ved hjælp af ligningsspørgsmålstypen:

  • Opret først et spørgsmål med kode Q1 som et numerisk inputspørgsmål.
  • Opret derefter endnu et spørgsmål med kode Q2 som et ligningsspørgsmål .
  • I kapitlet "Skærmindstillinger"-fanebladet i Q2:
    • sæt "Skjul altid dette spørgsmål"-felt som "Til"
    • skriv i "Ligning"-feltet udtrykket:
 {if(Q1.NAOK < 20, "1", if(Q1.NAOK > 20, "3", "2"))}

Opret en oversigtsside ved hjælp af pladsholdere

Denne vejledning viser, hvordan du kan skabe et overblik i slutningen af undersøgelsen, med en liste over alle spørgsmål og svar via ExpressionScript-pladsholdere. Den viser også, hvordan du begrænse en sådan oversigt til kun at omfatte besvarede spørgsmål.

Vores eksempel kan downloades herfra: Eksempel på undersøgelsespladsholdere.


Spørgsmålstyper, der bruges her:

1. Enkeltvalgsspørgsmål / enkelttekst/numeriske spørgsmål

  • Liste (dropdown)
  • Liste (radio) [L]
  • Ja/Nej [Y]
  • Lang fritekst [T ]
  • Kort fritekst [S]
  • Numerisk input [N]
  • Ligning [*]


2. Spørgsmål med underspørgsmål

  • Multiple short text [Q]
  • Multiple choice [M]
  • Array [F]
  • Array (Ja/Nej/Usikker) [C]
  • Array (10 point valg) [B]


3. Spørgsmål med 2 skalaer

  • Array dobbelt skala [1]


4. Spørgsmål med X- og Y-skalaer

  • Array (tal) [:]


5. Maskespørgsmål

  • Tekstvisning [X]


I dette simple eksempel vil vores oversigt være en simpel liste med:

- Spørgsmålstekst: Brugerens svar


Enkeltvalgsspørgsmål / enkelttekst/numeriske spørgsmål

For alle disse spørgsmålstyper vil Limesurvey gemme et enkelt svar:

  • Liste (dropdown)
  • Liste (radio)
  • Liste med kommentar
  • 5-punktsvalg
  • Ja/Nej
  • Kort fritekst
  • Lang fritekst
  • Kæmpe fritekst
  • Numerisk input
  • Ligning
  • Dato
  • Køn

Forudsat at spørgsmålskoden for spørgsmålet er q1, kan vi referere spørgsmålsteksten og svaret ved hjælp af:

- {q1.question}: {q1.shown}

Eksempel:

- Hvor gammel er du?: 25


Hvis du vil kontrollere, om det spørgsmål blev besvaret, kan du sætte en IF-sætning omkring dit output:

{if(!is_empty(q1),join("- ",q1.question,": ",q1.shown),"")}

Dette "oversætter" til: HVIS spørgsmål med kode q1 ikke er tomt, output "- " OG spørgsmålsteksten OG ": " OG svarteksten (join()-funktionen forbinder elementer som en ny streng; ELSE: output ingenting (" " betyder tom streng).

Spørgsmål med underspørgsmål

For all these question types LimeSurvey uses subquestions:

  • Multiple short text
  • Multiple choice
  • Multiple choice with comments
  • Array
  • Array (5 point choice)
  • Array (10 point choice)
  • Array (Yes/No/Uncertain)
  • Array (Increase/Same/Decrease)
  • Array by column

Assuming the question code of the question is q2 and the subquestions are numbered SQ001, SQ002, (auto-numbering done by LimeSurvey), we can reference the question text and answer using:

- {q2_SQ001.question}: {q2_SQ001.shown}

- {q2_SQ002.question}: {q2_SQ002.shown}

For multiple choice questions it makes sense to now show the text of the ticked subquestion but to show a Y for each selected option:

- {q2_SQ001.question}: {q2_SQ001}

- {q2_SQ002.question}: {q2_SQ002}

...

Note that currently it is not possible to output the question text of questions with subquestions, see this feature request.


Example 1 (assuming question type is multiple choice)

- Do you know these car brands?

-- Mercedes: Y

-- Audi: N

-- Volvo: Y


If you want to output checked items only you can put an IF statement around your output and check for the checkbox value:

{ if( q2_SQ001=="Y", join( "- ", q2_SQ001.question, ": ", q2_SQ001.shown ), "" ) }


Use the listifop function if you want to output a list of only the selected items, eg: Mercedes, Volvo

{ listifop( 'value', '==', 'Y', 'question', ', ', that.q2.sgqa ) }


Where  that.q2  expands to all of q2's subquestions. See self, this and that for more detail.


Example 2 (assuming question type is Array (10 point choice))

- Please rate the quality of the car brands below on a scale from 1=very bad to 10=very good?

-- Mercedes: 7

-- Audi: 9

-- Volvo: 9


If you want to output rated items only you can put an IF statement around your output and check if the current sub question was answered by using:

{ if( ! is_empty( q3_SQ001 ), join( "- ", q3_SQ001.question, ": ", q3_SQ001.shown ), "" ) }


Use the listifop function if for example you want to only output a list of the selected items greater than eight, eg: Audi / Volvo

{ listifop( 'value', '>', 8, 'question', ' / ', that.q3.sgqa ) }


Question with two scales

This applies to the dual scale question type only.


Let's assume that the following codes are being used:

  • Question code: q4
  • Subquestion codes: SQ001, SQ002, ...
  • Answer codes scale 1: A1, A2, ...
  • Answer codes scale 2: B1, B2, ...


To refer to the result of a certain subquestion on a certain scale, you need to use QuestionCode . '_' . SubQuestionCode . '_' . ScaleID. Note that "ScaleID" is 0 for the first scale and 1 for the other!
Example for referring to the answer of the third subquestion and second scale: q4_SQ003_1 - Question 4, subquestion 3, second scale.


Let's output the results for both scales and the first two subquestions:

- {q4_SQ001_0.question}: {q4_SQ001_0.shown} / {q4_SQ001_1.shown}

- {q4_SQ002_0.question}: {q4_SQ002_0.shown} / {q4_SQ002_1.shown}

To output the subquestion text, you need to add the scale ID to the placeholder (though the texts are the same for both scales). So instead of {q4_SQ001.question} we have to use {q4_SQ001_0.question} or {q4_SQ001_1.question}.

If you want to export/display the results of subquestions with at least one answer only, use this syntax for each subquestion:

{if(count(q4_SQ001_0,q4_SQ001_1)>0,join("- ",q4_SQ001_0.question,": ",q4_SQ001_0.shown," / ",q4_SQ001_1.shown),"")}

Question with X and Y scales

This applies to all matrix questions which allow an answer for every cell (not just every row as shown previously):

  • Array Texts
  • Array Numbers


Assumed codes used:

  • Question code: q5
  • Subquestion codes: SQ001, SQ002, ...
  • Answer codes: A1, A2, ...

To refer to the result of a certain subquestion from a certain column, you need to use QuestionCode . '_' . SubQuestionCode . '_' . AnswerCode. Example for referring to the answer of the third subquestion and second column: q5_SQ003_A2.

Let's output the results for columns 1-3 of the first two subquestions:

- {q5_SQ001_A1.question}: {q5_SQ001_A1.shown} | {q5_SQ001_A2.shown} | {q5_SQ001_A3.shown}

- {q5_SQ002_A1.question}: {q5_SQ002_A1.shown} | {q5_SQ002_A2.shown} | {q5_SQ002_A3.shown}


Since for these question types each cell (combination of X axes and Y axes) equals one answer option, a test for existing data needs to be done for each cell. Example:

{if(!is_empty(q5_SQ001_A1),join("- ",q5_SQ001_A1.question,": ",q5_SQ001_A1.shown),"")}


To output the subquestion text you need to add the answer code to the placeholder (though the texts are the same for all answer options). So instead of {q5_SQ001.question} we have to use {q5_SQ001_A1.question} or {q5_SQ001_A2.question}.

Hide question if answer from previous question is empty

Purpose Hide question if answer from previous question is empty
Type Question Relevance
Example Question one: question code "name", question text "What's your name?"
Question two: question text "{name}, how old are you?"
To do: Hide question two if the textfield of question one is empty
Expression !is_empty(name)
Description is_empty() determines whether a variable is considered to be empty. The "!" negates the result. So if the variable is not empty the Expression will be true and the question is shown
Steps Create/edit question two
Insert "!is_empty(name)" into "Relevance equation:"
Sample File Hide_question_if_empty_question_group.zip


Hide question group if answer from previous question is Yes or No

Purpose Hide question group if answer from previous question is Yes or No
Type Question group Relevance
Example Page one, Question Group one, Question one: question code "PET", question text "Do you have a pet?" -Yes -No
Page two, Question Group two: Title "About your pet(s)"
To do: Show/Hide question group two if answer from question one is Yes/No
Expression PET == "Y"
Description PET is the question code for the question you want to check the answer. If you don't use a suffix EM will use "Qcode.code". So you compare the answer code from the PET question to the value "Y". If the participant answers "Yes" the Expression is true and the question group "About your pet(s)" will be shown.
Steps Create/edit question group two
Insert "PET == "Y"" into "Relevance equation:"
Sample File Hide_question group_if_answer_from_previous_question_is_Yes_or_No.zip


Display value of a multiple answer input question field

Purpose Display value of a multiple answer input question field
Type Reference
Example Question one: question code "AskChildAge", question text "How old are your children?". Subquestions codes -Child1 -Child2 -Child3 - ChildXXX
Question two: question code "ReportChildAge" question text "About your first child: - CHILD1 is AGE1."
Expression {AskChildAge_Child1.question}, {AskChildAge_Child1.value}
Description You want to use the value of a subquestion in a following question. You can access the subquestion value with this kind of expression: QcodeQuestion_QcodeSubquestion.value
Steps Create/edit the second question
Insert this text in the description: "About your first child: - {AskChildAge_Child1.question} is {AskChildAge_Child1.value}."
Sample File Display_value_of_a_multiple_answer_input_question_field.zip

Validate number of boxes ticked per row for an "Array (Numbers) Checkbox" question

Purpose Validate number of boxes ticked per row
Type Validation
Example Question of type "Array Numbers (Checkbox Layout)"
Expression sum(...)
Description (sum(Test_A_1, Test_A_2, Test_A_3, Test_A_4, Test_A_5) <= X) determines whether at least X checkboxes in row A are checked.
If you want to check all three rows (A, B, C), you can connect the expression using "&&":
(sum(Test_A_1, Test_A_2, Test_A_3, Test_A_4, Test_A_5) <= X)
&& (sum(Test_B_1, Test_B_2, Test_B_3, Test_B_4, Test_B_5) <= X)
&& (sum(Test_C_1, Test_C_2, Test_C_3, Test_C_4, Test_C_5) <= X)
Steps Create/edit question of type "Array Numbers (Checkbox Layout)".
Insert the above expression into "Question validation equation" at the advanced question settings (you might have to adjust variable namings!).
Sample File Validate number of boxes ticker per row for an Array (Numbers) Checkbox.lss

Calculate difference between two dates

Purpose Calculate difference between two dates
Type Relevance / Equation question type / Validation
Example Question one (date/time, code: DOB): What is your date of birth?
Question two (date/time, code: datetoday): What is the date today?
Question three (boilerplate): You are XXXX days old.
To do: Calculate and display the number of days between the date given in question 1 and the question 2.
Expression {(strtotime(datetoday)-strtotime(DOB))/60/60/24}
Description strtotime calculates the number of seconds between the 1st of January 1970 and the given date. The above expression calculates the number of seconds between the two given dates. The term "/60/60/24" just calculates the number of days from the number of seconds.
Instead of asking for the "datetoday", you can also use strtotime('now') or simply time(), which directly returns the number of seconds from January 1970 until now (i.e. the time the survey was taken). Thus you could quickly figure out the age of a person in years with the equation {(time() - strtotime(DOB)) / 60 / 60 / 24 / 365.25} In any of these cases, it is critical that the date is entered in a proper format, otherwise the strtotime() function will not work right.
Steps Create two date questions (for the date of birth and for today's date) and a boilerplate question.
In the question text of the boilerplate question insert: "On {datetoday} you were {(strtotime(today)-strtotime(dob))/60/60/24} days days old."

Please note: The function strtotime can work with MANY but not all date formats. If you run into problems set your survey's date format to mm/dd/yyyy or yyyy-mm-dd or dd.mm.yyyy"
Sample File Date_difference.zip

Using ExpressionScript for Assessments

Here comes another example on how to use the ExpressionScript with Array type questions and assessments:</ br>

Let's say you have 2 array questions and you want to save the results of the calculation data to your database. It is actually simple, you will need to create and test your arrays and submit a dummy response to see if it works and gives you the results in the completed page.


Implementation details:

  • add a question of type equation
  • add the following line assuming that Q1 is your array question code while Q2 is the second one:
    • {sum(Q1_SQ001.value,Q2_SQ001.value)}

Note that SQ001 is the default code for any subquestion. If you change the subquestion code, adjust the equation above accordingly.


Using em_validation_q in array

You can use the question validation equation to control an array with any condition.


Implementation details:

  • for the first array : array of single choice
    • Question code is ARRAY
    • Sub question code are SQ01,SQ02,SQ03 and SQ04
    • update the Whole question validation equation and put
      !is_empty(ARRAY_SQ01) and !is_empty(ARRAY_SQ03) 
  • for the second array : array of text
    • Question code is ARRAYTEXT
    • Sub question at Y axis code are SY01,SY02,SY03, and SY04
    • Update the Whole question validation equation and put
      count(self.sq_SY01 >= 1) and count(self.sq_SY03 >= 3)