Actions

Instrucțiuni pentru ExpressionScript

From LimeSurvey Manual

Revision as of 09:16, 8 November 2023 by Maren.fritz (talk | contribs) (Created page with "=Exemple de calcul/evaluare=")


Prezentare generală a ceea ce a fost explicat anterior

Dacă ați urmat până acum structura manualului LimeSurvey, înseamnă că aveți deja Terminologia LimeSurvey. Apoi, am acoperit expresii și variabile pentru a învăța cum să ne îmbunătățim sondajele. În partea următoare, am trecut la tipurile și semnificațiile sintaxă evidențiere pentru a afla cum să corectăm erorile de sintaxă.

Cu aceste noțiuni de bază acoperite, am putea trece către exemple și să explicăm cum funcționează expresiile în LimeSurvey.


Evidențierea sintaxei

Următoarele capturi de ecran oferă exemple, dar nu arată valorile sfaturile instrumente. Un sfat explicativ este o casetă informativă care este afișată ori de câte ori treceți mouse-ul peste orice cuvinte colorate îndrăznețe.

Datorită acestei evidențieri de sintaxă, este foarte ușor să compuneți expresii corecte, chiar și cele care sunt complicate. Deși echipa LimeSurvey plănuiește să încerce să construiască o interfață grafică Expression Builder, puteți utiliza evidențierea de sintaxă existentă pentru a identifica și a remedia rapid greșelile de scriere. De asemenea, puteți utiliza sfaturile instrumente pentru a valida acuratețea expresiilor dvs. (de exemplu, confirmați că ați selectat variabilele dorite).

În fiecare dintre exemple, există trei coloane:

  1. Sursă - acesta este textul brut pe care l-ați introduce în câmpul de întrebare LimeSurvey
  2. Pretty Print - acesta este echivalentul evidențiat de sintaxă a ceea ce ați introdus! N!#*Rețineți că expresiile sunt afișate cu un fundal cafeniu, dar nu sunt înconjurate de acolade în această evidențiere.
    • Din moment ce EM acceptă substituția recursivă, afișarea acoladelor în evidențiere ar provoca erori de sintaxă
  3. Rezultat - aceasta este rezultatul generat atunci când EM procesează sursa
    • Tot ceea ce poate fi înlocuit corect este
    • Expresiile cu erori sunt afișate în linie, cu evidențierea sintaxelor. Erorile sunt înconjurate de o casetă roșie.


Sintaxă corectă

Mai jos puteți găsi exemple de sintaxă adecvată:

  1. Valori: arată că variabilele cunoscute sunt codificate cu culori în funcție de dacă sunt setate pe pagina curentă. INSERTANS în stil vechi:xxxx capătă propriul stil de codare a culorilor
  2. Atribute întrebări: arată că notația cu puncte poate accesa unele proprietăți ale întrebărilor
  3. Math: arată că sunt acceptate calcule de bază și complexe
  4. Procesare text: arată unele dintre funcțiile de procesare a textului disponibile
  5. Date: arată două dintre funcțiile disponibile legate de dată
  6. Condițional: arată utilizarea funcției if(). Opțiunile pot fi imbricate.
  7. Paragraf personalizat: puteți personaliza complet un raport pe baza valorilor anterioare
  8. EM procese în șiruri: arată că poate face substituții în șiruri. Acest exemplu generează un nume de imagine adaptat.
  9. EM nu procesează acolade ca acestea: arată că dacă acoladele sunt scapă sau există un spațiu alb între expresie și acolade, ES ignoră expresia.


Fișier:em-syntax-highlighting-1-v2.jpg


Sintaxa EM care conține erori

Iată exemple de erori comune la tastarea expresiilor ES. Rețineți că sfaturile instrumente oferă informații suplimentare.

  1. Inline Javascript care a uitat să adauge spații după acolade
    • Din moment ce „document.write” apare imediat după o acoladă, EM crede că este o expresie și roșu- casetele „document” și „scrie” deoarece sunt variabile și, respectiv, funcții nedefinite
  2. Variabile, funcții și operatori necunoscute/ortografiate greșit
    • Aici am uitat că folosim numele variabilei „gen” în loc de „ sex”, dar EM prinde acea eroare. De asemenea, introduce casete roșii „++”, deoarece acesta nu este un operator acceptat.
  3. Avertizează dacă se folosește = în loc de eq, sau se efectuează atribuiri de valori
    • Rețineți că „=” și „+=” sunt în text roșu în loc de negru. Dacă treceți mouse-ul peste ele, veți vedea avertismente că atribuiți o valoare.
  4. Număr greșit de argumente pentru funcții
    • if() ia 3 argumente, dar i s-au dat 4, așa că treceți cu mouse-ul peste „dacă” în casetă roșie va explica eroarea și va afișa sintaxa acceptată! N!#*sum() ia un număr nelimitat de argumente, dar am avut o virgulă finală înainte de parantezele de închidere, așa că este în casetă roșie! N!#Paranteze nepotrivite
    • Aceasta este una dintre cele mai frecvente erori la scrierea expresiilor.
    • Aceasta arată două exemple de paranteze de închidere lipsă și un exemplu de a avea una prea multe paranteze de închidere.
#Sintaxă nesuportată
    • Dacă utilizați un operator sau o semnătură de punctuație pe care ES nu le acceptă, acesta îl va afișa în casetă roșie.
  1. Atribuții nevalide
    • Unele variabile sunt readWrite și pot avea valorile modificate. Altele sunt doar pentru citire.
    • Dacă încercați să modificați valoarea unei variabile numai pentru citire, nu puteți. EM va marca în roșu încercarea.
    • Dacă încercați să atribuiți o valoare unei ecuații sau unui șir, veți primi și o eroare


Fișier:em-syntax-highlighting-errors-v2.jpg


"Exemple live de evidențiere a sintaxelor cu sfaturi active

Sursă Pretty Print Rezultat
Iată un exemplu de sintaxă OK cu sfaturi
Bună ziua {if(gen=='M','Mr.','Mrs.')} {prenume}, acum este {data('g:i a',time())}. Știți unde sunt copiii și animalele dvs. de companie {sum(numPets,numKids)}?
Iată un exemplu de sintaxă OK cu sfaturi
Bună ziua dacă ( gen == 'M' , 'Mr.' , 'Mrs.' ) nume de familie , acum este data ( 'g:i a' , ora ()) . Știți unde sunt suma ( numPets , numKids ) copiii și animalele dvs. de companie?
Iată un exemplu de sintaxă OK cu sfaturi
Bună ziua, domnule Smith , acum este ora 6:07. Stii unde sunt cei 3 copii si animalele tale?
Iată erori comune, astfel încât să puteți vedea sfaturile instrumente
Variabilele utilizate înainte de a fi declarate: {notSetYet}
Funcție necunoscută: {iff(numPets>numKids,1,2)}
Variabilă necunoscută: {sum(age,num_pets,numKids)}
# parametri greșiți: {sprintf()},{if(1,2)},{date()}
Atribuiți variabile numai în citire:{TOKEN:ATTRIBUTE_1+=10},{name='Sally'}
Paranteze dezechilibrate: {pow(3,4},{(pow(3,4)},{pow(3,4))}
Iată erori comune, astfel încât să puteți vedea sfaturile instrumente
Variabilele utilizate înainte de a fi declarate: notSetYet
Funcție necunoscută: ff ( numPets > numKids ,1,2)
Variabilă necunoscută: sum ( vârstă , num_animale de companie , numKids )
# parametri greșiți: sprintf () , if (1,2) , data ()
Atribuiți variante numai pentru citire: TOKEN:ATTRIBUTE_1 += 10 , nume = „Sally”
Paranteze dezechilibrate: pow (3,4 , ( pow (3,4) , pow (3,4) )
Iată erori comune, astfel încât să puteți vedea sfaturile instrumente
Variabilele utilizate înainte de a fi declarate: notSetYet
Funcție necunoscută: ff ( numPets > numKids ,1,2)
Variabilă necunoscută: sum ( vârstă , num_animale de companie , numKids )
# parametri greșiți: sprintf () , if (1,2) , data ()
Atribuiți variante numai pentru citire: TOKEN:ATTRIBUTE_1 += 10 , nume = „Sally”
Paranteze dezechilibrate: pow (3,4 , ( pow (3,4) , pow (3,4) )
Iată câteva dintre sintaxa neacceptate
Nu există suport pentru „++”, „--”, „%”,”;”: {min(++age, --age,age % 2);}
Nici „|”, „&”, „^”: {(sum(2 | 3,3 & 4,5 ^ 6)}}
Nici matrice: {nume[2], nume['al meu']}
Iată câteva dintre sintaxa neacceptate
Fără suport pentru „++”, „--”, „%”,”;”: min ( ++ vârstă , -- vârstă , vârstă % 2) ;
Nici „|”, „&”, „^”: ( suma (2 | 3,3 & 4,5 ^ 6) }
Nici matrice: nume [ 2 ] , nume [ „al meu” ]
Iată câteva dintre sintaxa neacceptate
Fără suport pentru „++”, „--”, „%”,”;”: min ( ++ vârstă , -- vârstă , vârstă % 2) ;
Nici „|”, „&”, „^”: ( suma (2 | 3,3 & 4,5 ^ 6) }
Nici matrice: nume [ 2 ] , nume [ „al meu” ]


Exemple de personalizare (de ex. extinderea {INSERTANS:xxx})

"Stimate {domnule}/{doamna} Smith..."

Utilizați funcția if() pentru a alege în mod condiționat dacă să afișați „Mr. sau „doamna”.

Sintaxa este if(test,do_if_true,do_if_false).

# Cod Întrebare Tip
1 gen Care este genul tău? Sex
|example1 Dragă {if(gen=='M','Domn','Doamnă')} Smith, ... Text lung liber



După cum se poate observa mai jos, „domnul” și „doamna” sunt adaptate la ceea ce respondentul selectează ca răspuns la întrebarea „sex”.


Fișier:em-tailoring-q-ex1-usage.jpg Fișier:em-tailoring-q-ex2-usage.jpg


"Stimate {Domnule}/{Doamna} Smith..." în e-mailul de invitație

Puteți folosi exemplul de mai sus în e-mailul de invitație folosind atribute din tabelul de simboluri. Utilizați funcția if() pentru a alege dacă „Mr.” sau „Doamna”. ar trebui folosit în e-mail.


Sintaxa este „dacă(test,do_dacă_adevărat,do_dacă_fals)”.

# atribut valoare
1 Nume Smith
2 Adresă de e-mail test@test. com
3 ATTRIBUTE_2 M


Text în e-mailul de invitație:

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

ați fost invitat  participați la un sondaj:

https:/...



e-mail Vizualizare:



Exemple de calcul/evaluare

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: