x

Capitoli principali

  1. LimeSurvey Cloud vs LimeSurvey CE
  2. LimeSurvey Cloud - Guida rapida
  3. LimeSurvey CE - Installazione
  4. Come progettare un buon sondaggio (Guida)
  5. Iniziare
  6. Configurazione di LimeSurvey
  7. Introduzione - Sondaggi
  8. Visualizza le impostazioni del sondaggio
  9. Visualizza il menu del sondaggio
  10. Visualizza la struttura del sondaggio
  11. Introduzione - Domande
  12. Introduzione - Gruppi di domande
  13. Introduzione - Indagini - Gestione
  14. Opzioni della barra degli strumenti del sondaggio
  15. Sondaggio multilinguale
  16. Guida rapida - ExpressionScript
  17. Funzionalità avanzate
  18. Domande frequenti generali
  19. Risoluzione dei problemi
  20. Soluzioni alternative
  21. Licenza
  22. Registro delle modifiche alla versione
  23. Plugin - Avanzati
 Actions

ExpressionScript How-tos/it: Difference between revisions

From LimeSurvey Manual

Maren.fritz (talk | contribs)
Created page with "=="Gentile {Mr}/{Mrs} Smith..." nell'e-mail di invito=="
Maren.fritz (talk | contribs)
Created page with "Puoi utilizzare l'esempio precedente nell'e-mail di invito utilizzando gli attributi della tabella dei token. Usa la funzione if() per scegliere se 'Mr.' o "signora". deve ess..."
Line 129: Line 129:




You can use the example above in the invitation email using attributes from the token table. Use the if() function to choose whether 'Mr.' or 'Mrs.' should be used in the email.
Puoi utilizzare l'esempio precedente nell'e-mail di invito utilizzando gli attributi della tabella dei token. Usa la funzione if() per scegliere se 'Mr.' o "signora". deve essere utilizzato nell'e-mail.





Revision as of 17:13, 31 July 2023


Panoramica di quanto spiegato in precedenza

Se finora hai seguito la struttura del manuale di LimeSurvey, significa che conosci già la Terminologia di LimeSurvey. Successivamente, abbiamo trattato espressioni e variabili per imparare come migliorare i nostri sondaggi. Nella parte successiva, siamo passati ai tipi e ai significati di evidenziazione della sintassi per imparare a correggere gli errori di sintassi.

Con queste nozioni di base coperte, potremmo passare agli esempi e spiegare come funzionano le espressioni all'interno di LimeSurvey.


Evidenziazione della sintassi

Gli screenshot seguenti forniscono esempi, ma non mostrano i valori dei suggerimenti. Un suggerimento è una casella informativa che viene visualizzata ogni volta che si passa il mouse su parole in grassetto.

Grazie a questa evidenziazione della sintassi, è molto facile comporre espressioni corrette, anche quelle complicate. Sebbene il team di LimeSurvey intenda provare a creare una GUI di Expression Builder, puoi utilizzare l'evidenziazione della sintassi esistente per identificare e correggere rapidamente gli errori di battitura. Puoi anche utilizzare i suggerimenti per convalidare l'accuratezza delle tue espressioni (ad esempio, confermare di aver selezionato le variabili desiderate).

In ognuno degli esempi, ci sono tre colonne:

  1. Source - questo è il testo non elaborato che inseriresti nel campo della domanda di LimeSurvey
  2. Pretty Print - questo è l'equivalente evidenziato in sintassi di quello che hai inserito! N!#*Nota che le espressioni sono mostrate con uno sfondo marrone chiaro, ma non circondate da parentesi graffe in questa evidenziazione.
    • Poiché EM supporta la sostituzione ricorsiva, mostrare le parentesi graffe nell'evidenziazione causerebbe errori di sintassi
  3. Risultato - questo è l'output generato quando EM elabora il sorgente
    • Tutto ciò che può essere correttamente sostituito è
    • Le espressioni con errori sono mostrate in linea, con l'evidenziazione della sintassi. Gli errori sono circondati da una casella bordata di rosso.


Sintassi corretta

Di seguito puoi trovare esempi di sintassi corretta:

  1. Values: mostra che le variabili note sono codificate a colori a seconda che siano impostate nella pagina corrente. Old-style INSERTANS:xxxx ottiene il proprio stile di codifica a colori
  2. Attributi domanda: mostra che la notazione punto può accedere ad alcune proprietà delle domande
  3. Math: mostra che sono supportati calcoli di base e complessi
  4. TextProcessing: mostra alcune delle funzioni disponibili per l'elaborazione del testo
  5. Dates: mostra due delle funzioni relative alla data disponibili
  6. Conditional: mostra l'utilizzo della funzione if(). Le scelte possono essere nidificate.
  7. Paragrafo su misura: puoi personalizzare completamente un report basato su valori precedenti
  8. EM processi all'interno di stringhe: mostra che può eseguire sostituzioni all'interno di stringhe. Questo esempio genera un nome immagine personalizzato.
  9. EM non elabora le parentesi graffe come queste: mostra che se le parentesi graffe sono sfuggite o c'è uno spazio bianco tra l'espressione e le parentesi graffe, ES ignora l'espressione.



Sintassi EM contenente errori

Ecco alcuni esempi di errori comuni durante la digitazione delle espressioni ES. Si noti che i suggerimenti forniscono informazioni aggiuntive.

  1. Inline Javascript che ha dimenticato di aggiungere spazi dopo la parentesi graffa
    • Poiché "document.write" appare subito dopo una parentesi graffa, EM pensa che sia un'espressione e red- caselle "document" e "write" poiché sono variabili e funzioni non definite, rispettivamente
  2. Variabili, funzioni e operatori sconosciuti/errati
    • Qui abbiamo dimenticato che stiamo usando il nome della variabile "gender" invece di " sex", ma EM rileva quell'errore. Inoltre, contrassegna in rosso '++', poiché non è un operatore supportato.
  3. Avverte se si usa = invece di eq o esegue assegnazioni di valori
    • Notare che '=' e '+=' sono in testo rosso invece che nero. Se passi il mouse sopra di essi, vedrai avvertimenti che stai assegnando un valore.
  4. Numero errato di argomenti per le funzioni
    • if() prende 3 argomenti, ma ne sono stati dati 4, quindi passandoci sopra sopra l'"if" nella casella rossa spiegherà l'errore e mostrerà la sintassi supportata
    • sum() prende un numero illimitato di argomenti, ma avevamo una virgola finale prima delle parentesi di chiusura, quindi è nella casella rossa! N!#Parenti non corrispondenti
    • Questo è uno degli errori più comuni durante la scrittura di espressioni.
    • Questo mostra due esempi di parentesi di chiusura mancanti e un esempio di parentesi di chiusura troppe.
#Sintassi non supportata
    • Se usi un operatore o una punteggiatura che ES non supporta, verrà inserito in una casella rossa.
  1. Assegnazioni non valide
    • Alcune variabili sono readWrite e possono avere i loro valori modificati. Altre sono di sola lettura.
    • Se provi a cambiare il valore di una variabile di sola lettura, non puoi. EM inserirà in una casella rossa il tentativo.
    • Se provi ad assegnare un valore a un'equazione o a una stringa, otterrai anche un errore



"Live" esempi di evidenziazione della sintassi con suggerimenti attivi

Fonte Bella stampa Risultato
Ecco un esempio di sintassi OK con suggerimenti
Ciao {if(gender=='M','Mr.','Mrs.')} {surname}, ora è {date('g:i a',time())}. Sai dove sono i tuoi {sum(numPets,numKids)} bambini e animali domestici?
Ecco un esempio di sintassi OK con suggerimenti
Hello if ( gender == 'M' , 'Mr.' , 'Mrs.' ) cognome , ora è date ( 'g:i a' , time ()) . Sai dove sono i tuoi bambini e animali domestici ( numPets , numKids ) ?
Ecco un esempio di sintassi OK con suggerimenti
Salve signor Smith , ora sono le 6:07. Sai dove sono i tuoi 3 bambini e gli animali domestici?
Di seguito sono riportati gli errori comuni in modo da poter visualizzare i suggerimenti
Variabili utilizzate prima di essere dichiarate: {notSetYet}
Funzione sconosciuta: {iff(numPets>numKids,1,2)}
Variabile sconosciuta: {sum(age,num_pets,numKids)}
# parametri errati: {sprintf()},{if(1,2)},{date()}
Assegna variabili di sola lettura:{TOKEN:ATTRIBUTE_1+=10},{name='Sally'}
Parentesi non bilanciate: {pow(3,4},{(pow(3,4)},{pow(3,4))}
Di seguito sono riportati gli errori comuni in modo da poter visualizzare i suggerimenti
Variabili usate prima di essere dichiarate: notSetYet
Funzione sconosciuta: iff ( numPets > numKids ,1,2)
Variabile sconosciuta: somma ( età , num_animali , numBambini )
# parametri errati: sprintf () , if (1,2) , date ()
Assegna variabili di sola lettura: TOKEN:ATTRIBUTE_1+= 10 , name= 'Sally'
Parentesi non bilanciate: pow (3,4 , ( pow (3,4) , pow (3,4) )
Di seguito sono riportati gli errori comuni in modo da poter visualizzare i suggerimenti
Variabili usate prima di essere dichiarate: notSetYet
Funzione sconosciuta: iff ( numPets > numKids ,1,2)
Variabile sconosciuta: somma ( età , num_animali , numBambini )
# parametri errati: sprintf () , if (1,2) , date ()
Assegna variabili di sola lettura: TOKEN:ATTRIBUTE_1+= 10 , name= 'Sally'
Parentesi non bilanciate: pow (3,4 , ( pow (3,4) , pow (3,4) )
Ecco alcune delle sintassi non supportate
Nessun supporto per '++', '--', '%',';': {min(++age, --age,age % 2);}
Né '|', '&', '^': {(sum(2 | 3,3 & 4,5 ^ 6)}}
Né array: {nome[2], nome['mio']}
Ecco alcune delle sintassi non supportate
Nessun supporto per '++', '--', '%',';': min ( ++ età , -- età , età % 2) ;
Né '|', '&', '^': ( somma (2 | 3,3 & 4,5 ^ 6) }
Né array: nome [ 2 ] , nome [ 'mio' ]
Ecco alcune delle sintassi non supportate
Nessun supporto per '++', '--', '%',';': min ( ++ età , -- età , età % 2) ;
Né '|', '&', '^': ( somma (2 | 3,3 & 4,5 ^ 6) }
Né array: nome [ 2 ] , nome [ 'mio' ]


Esempi di personalizzazione (ad es. estensione di {INSERTANS:xxx})

"Caro {Mr}/{Mrs} Smith..."

Utilizzare la funzione if() per scegliere in modo condizionale se visualizzare "Mr." o 'signora'.

La sintassi è if(test,do_if_true,do_if_false).

# Codice Domanda Tipo
1 sesso Qual è il tuo genere? Sesso
|example1 Gender {if(gender=='M','Mr.','Mrs.')} Smith, ... Testo libero lungo



Come si può osservare di seguito, "Mr" e "Mrs" sono adattati a ciò che l'intervistato seleziona come risposta alla domanda "sesso".



"Gentile {Mr}/{Mrs} Smith..." nell'e-mail di invito

Puoi utilizzare l'esempio precedente nell'e-mail di invito utilizzando gli attributi della tabella dei token. Usa la funzione if() per scegliere se 'Mr.' o "signora". deve essere utilizzato nell'e-mail.


The syntax is "if(test,do_if_true,do_if_false)".

# attribute value
1 Last name Smith
2 Email address test@test.com
3 ATTRIBUTE_2 M


Text in invitation email:

Dear {if(ATTRIBUTE_2=='M','Mr','Mrs')} {LASTNAME},

you have been invited to participate in a survey:

https:/...



email View:



Calculation / Assessment Examples

Calculate assessment values at runtime and store the results in the survey data

This example uses all of EM's features, including Relevance, Tailoring, and the Equation question type.

It also shows that all of them are JavaScript-enabled, so if you have these features on a page, it will dynamically change as people set and change their answers.

# Code Question Type Relevance
1 numKids How many children do you have? Numerical input 1
2 kid1 How old is your first child? Numerical input numKids >= 1
3 kid2 How old is your second child? Numerical input numKids >= 2
4 kid3 How old is your third child? Numerical input numKids >= 3
5 kid4 How old is your fourth child? Numerical input numKids >= 4
6 sumKidAges {sum(kid1.NAOK,kid2.NAOK,kid3.NAOK,kid4.NAOK)} Equation 1
7 kidSummary You said that you have {numKids}. {if(numKids==1,'child','children')}. {if(numKids>1,implode(' ','The sum of ages of your first ',min(numKids,4),' kids is ',sumKidAges,'.'),' ')} Text display 1


To download this example, please click on the following link: Assessments_survey_example.


You may find below screenshots of representative questions. As you can see, EM syntax-highlights all fields that might contain tailoring. Here, you see examples of syntax-highlighting Relevance, the Equation question type, and substitutions within a question. You can also use substitutions within Help, Group header display, Welcome message, and End message.

In the next example, since the relevance is {numKids >= 2), the question will only be visible if the respondent reports that she has at least two children.



Below, you may observe that each variable has the .NAOK suffix attached to it. This is because of how EM supports cascading relevance. If you did not have .NAOK, then the sum would only be computed if the person said she has 4 children (e.g., if all of the variables are relevant). The usage of .NAOK means that we want to compute the sum even if all or some of the variables are irrelevant (e.g., "Not Applicable" (NA) is alright (OK)).

However, the .NAOK attribute only affects whether variables are passed into EM. If the respondent initially says she has 3 children, and enters ages for each, then changes her mind and says she has 2, we don't want to see the sum of the 3 entered values - since the third child is "not applicable" in our case anymore:



Each separate Expression is color coded with a tan background. As you can see, there are three separate Expressions here. The last one contains a message that is conditionally shown only if the person has more than one child.



Now, here are screenshots of the survey in action.

When you first visit the page, you see this. Note that is says "You have 0 children" instead of "You have 0 child".



If I change the value for number of children to 1, the display instantly changes to this, even though it is on the same page:



Now notice that the grammar is correct: "You have 1 child".

Now I change the value for number of children to 3, and the display instantly changes to this.

Notice that you now see the conditional message at the bottom:  "The sum of ages of your first 3 kids is 0.".



Now I'll enter ages for my imaginary children, and I get this display, summing up their ages:



Again, the score and display updates instantly as I enter the values, so you can use this to show a running total of an Assessment Score.


Now, I change the value for the number of children to 2. The display has changed to this:



Notice that although I had entered a value of 5.5 for the third child, the report now only sums the values of my first 2 children.

The reason for this is that the 3rd value is now irrelevant, and irrelevant values are actively ignored by EM.

If I were to change the number of kids back to 3, I would see the value of 5.5 I entered again. So, I don't lose any information I enter on the page.

However, if I navigate to the Next or Previous page, all irrelevant values will be NULLed out in the session and in the database. So, if I were to keep the value at 2, go to the next page, and then come back and state that I actually have 3 kids, I would no longer see the age of 5.5.


Enter data and see a dynamically changing report of what was entered on the same page

This example presents the Tailoring process within LimeSurvey.

To download this example, click on the following link: Dynamic changes survey example.

Here is what the page looks like initially. You only see the question asking what city you live in:



Once you start to enter an answer, the tailoring process is also starting:


As you enter answers, the table at the bottom of the page is updated to show the answer codes and values of your responses.


Common Debugging Examples

Nested if() Statements (Conditional Logic)

EM supports the function "if(test,do_if_true,do_if_false)" so that you can perform conditional logic or tailoring. This function can be nested to do the equivalent of "if { } else if { } else {  }". EM will let you know if the parentheses are not balanced (e.g., you are missing a closing right parenthesis), or if you have any extra right parentheses. You should try to count the parentheses as you compose long nested if statements, save it, check for syntax errors, and fix them if any are found. Let's check together the below example.

The group of questions used below can be accessed from here: Tailoring survey example.lsg


First, with nothing entered, you just see "Hello."



If you enter a name, it says, "Hello {name}."



If you enter an age, you get a tailored message, depending upon whether you are a pre-school-age child or not:



School aged, teenager, or adult. Here is a  teenager who wants to be anonymous:



Here is the logic file of the group. As you can see in the "if-based" question, there are nested if statements based upon the person's age.



When you are originally editing this question, it is likely that at some point, you will have the wrong number of parentheses. Here's what happens if you have too few:



If you hover over the word "if", which is surrounded by a red box, it says "Parentheses not balanced". In this case, there should be four closing parentheses after "already an adult!", but there are only three.

If, on the other hand, you have an extra right parenthesis, it will be surrounded by a red box, like this:



When you are actually editing the question, the question looks like this: