Esempi di ExpressionScript
From LimeSurvey Manual
Struttura
La prima parte dell'articolo descriverà per cosa possono essere utilizzate le espressioni e dove trovare/aggiungere un'espressione. La seconda parte fornisce esempi su come utilizzare Expression.
Categorie di espressioni
LimeSurvey utilizza le espressioni per i seguenti scopi:
Pertinenza
Scopo: Nascondere gruppi di domande/domande
La pertinenza controlla se un gruppo di domande o una domanda viene mostrato o nascosto. Se il risultato dell'Espressione è "vero" (cioè 1), l'elemento verrà mostrato. Altrimenti (se il risultato dell'Espressione è "falso" (cioè 0)), l'elemento sarà nascosto.
Digita | Mostra/nascondi | Dove trovarlo | Screenshot |
---|---|---|---|
Gruppo di domande Rilevanza | Gruppo di domande | Crea/Modifica gruppo di domande -> "Equazione di rilevanza:" | File:Equazione di rilevanza del gruppo screenshot.png |
Rilevanza della domanda | domanda | Crea/Modifica domanda -> "Equazione di rilevanza:" | File:Schermata equazione rilevanza domanda.png |
Pertinenza sottodomanda | domanda secondaria | Modifica domande secondarie -> "Equazione rilevanza:" | File:Schermata equazione rilevanza sottodomanda. png |
Convalida
Scopo: convalida input/azioni su domande/sottodomande/risposte
La convalida controlla se l'input del rispondente in una domanda o in un'azione è valido o meno. Se il risultato dell'espressione è "true" (cioè 1), la classe "good" verrà applicata all'elemento e al messaggio di validazione. Altrimenti, se il risultato dell'espressione è "false" (cioè 0)), la classe "error" verrà applicata all'elemento e al messaggio di validazione. Puoi dichiarare uno stile per queste classi nel template.css.
Digita | Convalida | Dove trovarlo | Screenshot |
---|---|---|---|
Convalida domanda | domanda | Crea/Modifica domanda -> "Scheda Logica" - > "Equazione convalida domanda" | File:Equazione convalida domanda.png |
Convalida sottodomanda | sottodomande | Crea/Modifica domanda -> "Scheda Logica" -> " Equazione di convalida della sottodomanda" | File:Schermata di convalida della sottodomanda.png |
Emissione di testo
Scopo: (fare qualcosa) e scrivere del testo
Un'espressione può essere utilizzata per scrivere del testo. Ad esempio, puoi testare o calcolare qualcosa e specificare l'output in base al risultato del test o del calcolo. Può anche essere utilizzato per inserire il testo della domanda, le risposte, i tipi di domanda, ... di una domanda utilizzata prima dell'utilizzo dell'Espressione. L'output di testo può essere utilizzato ovunque venga visualizzato un testo e può restituire qualsiasi tipo di risultato.
Caso d'uso | Descrizione |
---|---|
Micro sartoria | Regola un testo, ad esempio, scrivi "Mr" o "Mrs" a seconda di una domanda di genere posta in precedenza |
Calcolo | Calcola un valore e scrivilo, ad es. "Il tuo reddito familiare è xxx" |
Riferimento | Inserisci un testo da un elemento, ad es. "Ti chiami xxx. Quanti anni hai?" |
Memorizzazione risposte
Scopi: (Fare qualcosa,) (scrivere del testo) e memorizzare qualcosa nel database
Il tipo di domanda Equazione può essere utilizzato per memorizzare qualcosa nel database. Puoi fare qualcosa con un'Espressione, mostrare la domanda Equazione (che è simile a una visualizzazione testo) e memorizzare il risultato dell'Espressione nel database. Memorizza la risposta nella tabella delle risposte. Quindi, il risultato può essere utilizzato all'interno della funzione statistica o può anche essere importato in uno dei formati forniti dalla funzionalità di esportazione di LimeSurvey.
Esempi per espressioni
Inserisci una risposta da una domanda precedente
Utilizzo della domanda di equazione nascosta per compilare automaticamente una risposta
Problema: Immagina di avere due domande Q1 e Q2. Q1 chiede agli intervistati la loro età. Q2 divide gli intervistati in tre gruppi: l'età è inferiore a 20 anni, l'età è 20 anni, l'età è maggiore di 20. Quindi, Q2 dovrebbe utilizzare i valori "1", "2", "3", che corrispondono a le condizioni di cui sopra. Inoltre, non dobbiamo dimenticare di rendere invisibile Q2 (la domanda non verrà visualizzata nel sondaggio, ma i valori verranno visualizzati tramite il "processo in background" all'interno della tabella delle risposte).
Per compilare il database utilizzando la domanda Equazione, digitare:
- Innanzitutto, creare una domanda con il codice Q1 come domanda di input numerico.
- Quindi creare un'altra domanda con il codice Q2 come domanda sull'equazione .
- Nel capitolo "Impostazioni di visualizzazione" di Q2:
- imposta il campo "Nascondi sempre questa domanda" come "On"
- digita nel campo "Equazione" l'espressione:
{if(Q1.NAOK < 20, "1", if(Q1.NAOK > 20, "3", "2"))}
Crea una pagina di riepilogo utilizzando i segnaposto
Questo tutorial mostra come creare una panoramica alla fine del sondaggio, elencando tutte le domande e le risposte tramite segnaposto ExpressionScript. Mostra anche come limitare tale panoramica solo alle domande con risposta.
Il nostro esempio può essere scaricato da qui: Esempio di sondaggio segnaposto sondaggio.
Tipi di domanda utilizzati qui:
1. Domande a scelta singola / domande testuali/numeriche
- Lista (dropdown)
- Lista (radio) [L]
- Si/No [S]
- Testo libero lungo [T ]
- Testo libero breve [S]
- Immissione numerica [N]
- Equazione [*]
2. Domanda con sottodomande
- Testo breve multiplo [Q]
- Scelta multipla [M]
- Array [F]
- Array (Sì/No/Incerto) [C]!N !*Array (10 punti a scelta) [B]
3. Domande con 2 scale
- Array doppia scala [1]
4. Domande con scale X e Y
- Array (Numbers) [:]
5. Maschera domande
- Visualizzazione testo [X]
In questo semplice esempio, la nostra panoramica sarà un semplice elenco con:
- Testo della domanda: Risposta dell'utente
Domande a scelta singola/domande a testo singolo/numeriche
Per tutti questi tipi di domande, Limesurvey memorizzerà un'unica risposta:
- Lista (dropdown)
- Lista (radio)
- Lista con commento
- Scelta 5 punti
- Si/No
- Testo libero breve
- Testo libero lungo!N !*Enorme testo libero
- Immissione numerica
- Equazione
- Data
- Sesso
Supponendo che il codice della domanda della domanda sia q1, possiamo fare riferimento al testo della domanda e alla risposta usando:
- {q1.domanda}: {q1.mostrato}
Esempio:
- Quanti anni hai?: 25
Se vuoi verificare se a questa domanda è stata data una risposta, puoi inserire un'istruzione IF attorno al tuo output:
{if(!è_vuoto(q1),join("- ",q1.domanda,": ",q1.mostrato),"")}
Questo "si traduce" in: SE la domanda con il codice q1 non è vuota, restituisce "- " E il testo della domanda E ": " E il testo della risposta (la funzione join() unisce gli elementi come una nuova stringa; ALTRIMENTI: restituisce niente (" " significa stringa vuota).
Domanda con sottodomande
Per tutti questi tipi di domande LimeSurvey utilizza sottodomande:
- Testo breve multiplo
- Scelta multipla
- Scelta multipla con commenti
- Array
- Array (scelta 5 punti)
- Array (scelta 10 punti)
- Array (Sì /No/Incerto)
- Matrice (Incremento/Uguale/Diminuzione)
- Matrice per colonna
Supponendo che il codice della domanda sia q2 e le domande secondarie siano numerate SQ001, SQ002 (numerazione automatica effettuata da LimeSurvey), possiamo fare riferimento al testo della domanda e alla risposta utilizzando:
- {q2_SQ001.domanda}: {q2_SQ001.mostrato}
- {q2_SQ002.domanda}: {q2_SQ002.mostrato}
Per le domande a scelta multipla ha senso ora mostrare il testo della sottodomanda spuntata ma mostrare una Y per ogni opzione selezionata:
- {q2_SQ001.domanda}: {q2_SQ001}
- {q2_SQ002.domanda}: {q2_SQ002}
...
Si noti che al momento non è possibile visualizzare il testo delle domande con domande secondarie, vedere richiesta di questa funzione.
Esempio 1 (supponendo che il tipo di domanda sia a scelta multipla)
- Conosci queste marche di auto?
--Mercedes: Y
--Audi: n
--Volvo: Y
Se si desidera emettere solo gli elementi selezionati, è possibile inserire un'istruzione IF attorno all'output e verificare il valore della casella di controllo:
{ if( q2_SQ001=="Y", join( "- ", q2_SQ001.domanda, ": ", q2_SQ001.mostrato ), "" ) }
Utilizzare la funzione listifop se si desidera generare un elenco dei soli elementi selezionati, ad esempio: Mercedes, Volvo
{ listifop( 'value', '==', 'Y', 'question', ', ', that.q2.sgqa ) }
Dove that.q2 si espande a tutte le sottodomande di q2. Vedere self, this and that per maggiori dettagli.
Esempio 2 (supponendo che il tipo di domanda sia Array (scelta di 10 punti))
- Si prega di valutare la qualità delle marche automobilistiche di seguito su una scala da 1=pessima a 10=molto buona?
--Mercedes: 7
-- Audi: 9
-- Volvo: 9
Se si desidera produrre solo elementi valutati, è possibile inserire un'istruzione IF attorno all'output e verificare se la domanda secondaria corrente ha ricevuto risposta utilizzando:
{ if( ! is_empty( q3_SQ001 ), join( "- ", q3_SQ001.question, ": ", q3_SQ001.shown ), "" ) }
Utilizzare la funzione listifop se, ad esempio, si desidera produrre solo un elenco degli elementi selezionati maggiore di otto, ad esempio: Audi / Volvo
{ listifop( 'value', '>', 8, 'question', ' / ', that.q3.sgqa ) }
Domanda con due scale
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, ...
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),"")}
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)