Actions

ExpressionScript Engine - Quick start guide/it: Difference between revisions

From LimeSurvey Manual

(Created page with "Vediamo ora un altro esempio: un semplice censimento. Può essere scaricato al link seguente: Census survey example.")
(Created page with "La prima pagina si chiede quante persone vivono con l'utente e salva tale valore nella variabile "cohabs". La pagina è mostrata solo se hai almeno un convivente. Anche le var...")
Line 76: Line 76:
Vediamo ora un altro esempio: un semplice censimento. Può essere scaricato al link seguente: [[Media:ES survey - Cohabs.zip|Census survey example]].  
Vediamo ora un altro esempio: un semplice censimento. Può essere scaricato al link seguente: [[Media:ES survey - Cohabs.zip|Census survey example]].  


The first page asks how many people live with you and stores that in the "cohabs" variable. This page is only shown if you have more than one cohabitant (it is shown for the second person cohabitating with you). Also, p2name, p2age. p2sum are displayed only if the question before each of them contains a response.
La prima pagina si chiede quante persone vivono con l'utente e salva tale valore nella variabile "cohabs". La pagina è mostrata solo se hai almeno un convivente. Anche le variabili p2name, p2age. p2sum sono mostrate solamente se la domanda precedente ciascuna di esse contiene una risposta.





Revision as of 16:50, 12 August 2020


Quick start guide

LimeSurvey permette di configurare ulteriormente i sondaggi tramite l'utilizzo di ExpressionScript (short: ES). Nota: "Nelle precedenti versioni, ExpressionScript era nominato Expression Manager (EM), o Gestore espressioni. Se in qualche sezione della documentazione appare il nome Expression Manager, tenere presente che è semplicemente il vecchio nome di ES."

ES consente di realizzare funzionalità avanzate, quali:

  1. Navigazione/Ramificazione – le risposte precedentemente inserite condizionano l’ordine in cui le domande successive sono poste ;
  2. Adattamento/Piping – cambiare dinamicamente il modo in cui le risposte sono declinate (ad esempio, adattare genere e numero delle parole riferendosi a risposte precedenti) e possibilità di generare report personalizzati e fornire punteggi di valutazione o altri valori personalizzati;
  3. Convalida – verifica che le risposte rispondano a determinati criteri, come l’appartenenza ad un intervallo numerico o la rispondenza a uno schema (ad esempio, un indirizzo e-mail o un numero telefonico devono avere un certo formato).

Grazie a ES è disponibile una modalità intuitiva per specificare la logica di ciascuna di queste caratteristiche. È possibile costruire espressioni valide per praticamente ogni equazione matematica standard, anche contenente funzioni.

ES contente l'utilizzo di 70 funzioni e può anche essere esteso per includerne di ulteriori. Le variabili possono essere chiamate con nomi facilmente leggibili e non solo con i codici SGQA.

Le sezioni seguenti mostrano i vari posti nei quali ES può essere utilizzato.


Rilevanza (Controllo della navigazione/Ramificazione)

Alcuni sistemi di gestione per sondaggi utilizzano una logica di tipo "GoTo": ad esempio, se si sceglie l'opzione C per la Domanda 1, allora vai alla Domanda 5. Questo approccio è piuttosto limitato, perché implica difficoltà di convalida e soprattutto perché la struttura logica si rompe se le domande vengono riordinate. ES utilizza invece equazioni booleane di rilevanza, con le quali sono specificate tutte le condizioni che una domanda deve rispettare per essere valida. Se la domanda ha "rilevanza", allora essa viene mostrata; altrimenti, è "non applicabile" e il valore NULL è salvato nel database delle risposte.

Nota Si tratta di qualcosa di simile a quanto può essere fatto dall'editor delle condizioni ma ES permette di specificare facilmente criteri molto più complessi e potenti - e, inoltre, permette di usare il nome della variabile invece dei codici SGQA.




Per comprendere meglio il concetto di rilevanza, osserviamo il seguente sondaggio, che calcola l'Indice di Massa Corporea, in inglese "Body Mass Index" o BMI. L'esempio è in inglese e si può scaricare dal link seguente: Body Mass Index survey example..

L'equazione di rilevanza è mostrata nella colonna "Relevance", dopo il nome della variabile (che è scritto in verde). Come si può vedere, la rilevanza di weight, weight_units, height and height_units vale in tutti i casi 1 (che è il valore di default), pertanto tutte queste domande sono sempre mostrate. L'equazione di rilevanza per il BMI, invece, è {!is_empty(height) and !is_empty(weight)}: questo significa che il BMI sarà calcolato solo se chi risponde al sondaggio ha inserito un valore sia per height ("altezza") che per weight ("peso"); in tal modo si evita di eseguire una divisione per zero con conseguente messaggio di errore. Anche la domanda "Report" è mostrata solo se sono state fornite risposte a tutte e quattro le domande principali (height, height_units, weight, weight_units).



Nota: L'immagine in alto è generata dalla funzionalità File della logica dell'indagine, che permette di verificare la possibile presenza di errori di sintassi prima di attivare il sondaggio.


La rilevanza è mostrata e modificabile

  • a livello di domanda
  • a livello di gruppo


Visualizzare e modificare la rilevanza a livello di domanda

La seguente equazione calcola l'Indice di massa corporea. Viene mostrata solamente se la persona inserice la propria altezza e il proprio peso.



Questa è la pagina di modifica per la domanda "BMI".



Nota bene: non si utilizzano le parentesi graffe quando si inserisce una equazione di rilevanza.


Visualizzare e modificare la rilevanza a livello di gruppo

Vediamo ora un altro esempio: un semplice censimento. Può essere scaricato al link seguente: Census survey example.

La prima pagina si chiede quante persone vivono con l'utente e salva tale valore nella variabile "cohabs". La pagina è mostrata solo se hai almeno un convivente. Anche le variabili p2name, p2age. p2sum sono mostrate solamente se la domanda precedente ciascuna di esse contiene una risposta.



So, the group also has question-level relevance criteria, such that some questions only appear if you answered certain questions before them (e.g., p2age is displayed if p2name was answered). ES combines the Group and Question-level relevance for you. Questions in a group are only asked if the group as a whole is relevant. Then, only the subset of questions within the group that are relevant are asked.

Here is the screenshot for editing the group-level relevance of Cohabitant 2:



Note that you do not use the curly braces when you enter a relevance equation.


Tailoring/Piping

ES lets you easily do simple and complex conditional tailoring. Sometimes you just need a simple substitution, like saying, "You said you purchased [Product]. What did you like best about it?". Sometimes you need conditional substitution like "[Mr./Mrs.] [LastName], would you be willing to complete our survey?". In this case, you want to use "Mr. or Mrs." based on the person's gender. Other times you need even more complex substitution (such as based upon a mathematical computation). ES supports each of these types of tailoring/piping.


Conditional Equations

The Body Mass Index example shows the ability to compute a person's BMI, even while letting them enter their height and weight in two different units (cms vs inches and kgs vs lbs):



In this case, weightkg is {if(weightunits == "kg", weight, weight * 0.453592)}. This "if()" function means that if the subject enters the weight using kilograms, use that value, otherwise multiply the entered value (pounds is the alternative) by 0.453592 to convert it to kilograms. The heightm variable uses a similar approach to compute the person's height in meters (height in cms/100), even if he has entered his height in inches (1 meter=3.28084 inches).

BMI is computed as: {weightkg / (heightm * heightm)}.

Lastly, the report conditionally tailors the message for the subject, telling her what he entered. (e.g., "You said you are 2 meters tall and weight 70 kg.")

In the below image, weightstatus uses nested "if()" statements to categorize the person as underweight to severely obese. You can see its equation by checking its logic:



From the edit window for this question, you can see two things:

  1. Tailoring must surround expressions with curly braces
  2. Expressions can span multiple lines if, as in this case, you want to make it easier to read the nested conditional logic.



Tailored Questions, Answers, and Reports

Note: Dynamic tailoring may not work if answer options are made available in select boxes on the same question page. This results from the fact that tailoring inserts a <span> tag which is not valid inside select options.

The BMI report looks like this:



Here is the edit window for the same question.



Anything within curly braces is treated as an expression, being syntax-highlighted (color coded) in the prior image. If you have any typos (such as misspelled or undefined variable names or functions), ES would show an error. In our below example:

  • heightunit.shown is an undefined variable name (it is actually heightunits.shown) and
  • "rnd()" is an undefined function (the proper function name is "round()").

In both cases, the errors are located within a red box to make it easier to spot and fix them.



You can also see that you can quickly create complex reports, such as a table of entered values or tailored advice.

Please remember that all tailoring must surround expressions with curly braces so that LimeSurvey knows which parts of the question are free text and which should be parsed by the ExpressionScript engine.


Validation

ES controls how most of the advanced question options work. These control aspects like min/max numbers of answers, min/max individual values, min/max sum values, and checking that entered values match specified string patterns. Any value in one of those fields is considered an expression, so you can have min/max criteria with complex conditional relationships to other questions.

In all of these cases, since the advanced question attribute is always considered an expression, you do not use curly braces when specifying it.

The sample surveys page shows many working examples containing a variety of validation expressions.

Expression Manager - presentation

To find out more about the Expression Manager and how you can use different expressions to enhance your survey, please click on the following link.