Actions

Expression Manager/sl: Difference between revisions

From LimeSurvey Manual

(Created page with "=Katero funkcionalnost razširi/zamenja Expression Manager? (LimeSurvey <= 1,91+)=")
(Created page with "==Pogoji => Ustreznost==")
Line 267: Line 267:
=Katero funkcionalnost razširi/zamenja Expression Manager? (LimeSurvey <= 1,91+)=
=Katero funkcionalnost razširi/zamenja Expression Manager? (LimeSurvey <= 1,91+)=


==Conditions => Relevance==
==Pogoji => Ustreznost==


Conditions controlled which  questions are visible.  The general syntax was ''SGQA operator Value'', like ''111X2X3 == "Y"''.  Conditions could be ANDed or ORed together, but mixing ANDs and ORs was difficult.  The conditions themselves were stored in a separate table, and large portion of LimeSurvey's code was devoted to managing Conditions.  Because of extensive database access, processing large numbers of conditions could cause noticable performance problems.  Furthermore, once you had conditions assigned to questions or groups, you were often not allowed to re-order or delete them.
Conditions controlled which  questions are visible.  The general syntax was ''SGQA operator Value'', like ''111X2X3 == "Y"''.  Conditions could be ANDed or ORed together, but mixing ANDs and ORs was difficult.  The conditions themselves were stored in a separate table, and large portion of LimeSurvey's code was devoted to managing Conditions.  Because of extensive database access, processing large numbers of conditions could cause noticable performance problems.  Furthermore, once you had conditions assigned to questions or groups, you were often not allowed to re-order or delete them.

Revision as of 08:04, 11 December 2023

Opomba: Ta funkcija je dosegljiva v LimeSurvey-u 1.92 ali novejši.

Vodnik za hitri začetek

Pregled

Ko prilagajate svoje ankete, običajno potrebujete način, da določite naslednje:

  1. Navigacija/Razvejanje – dovolite, da odgovori subjekta spremenijo vrstni red zastavljenih vprašanj
  2. 'Tailoring/ Piping - kako ubesediti vprašanje (na primer sklicevanje na prejšnje odgovore ali spreganje stavkov glede na število ali spol vaših predmetov) ali kako ustvariti poročila po meri (kot so rezultati ocenjevanja ali prilagojeni nasveti).
#'Validacija – zagotavljanje, da odgovori izpolnjujejo določena merila, kot so najmanjše in največje vrednosti, ali ujemanje z vnosnim vzorcem

Expression Manager (EM) ponuja intuitiven način za določanje logike za vsako od teh funkcij. Skoraj vse, kar lahko zapišete kot standardno matematično enačbo, je veljaven izraz, tudi če kličete funkcije. EM trenutno omogoča dostop do 80 funkcij in ga je mogoče enostavno razširiti, da podpira več. Omogoča tudi dostop do vaših spremenljivk z uporabo človeku berljivih imen spremenljivk (namesto imen SGQA).

Naslednji razdelki prikazujejo glavna mesta, kjer se uporablja Expression Manager

Ustreznost (nadzor navigacije/razvejanje)

Nekatere ankete uporabljajo "Pojdi na logiko", tako da če odgovorite na vprašanje 1 z možnostjo C, potem skočite na vprašanje 5. Ta pristop je zelo omejujoč, saj ga je težko preveriti in se zlahka prekine, ko morate preurediti vprašanja. EM uporablja Boolovo relevantno enačbo za določanje vseh pogojev, pod katerimi bi lahko bilo vprašanje veljavno. Če je vprašanje relevantno, se prikaže vprašanje, sicer ni uporabno, vrednost NULL pa je shranjena v bazi podatkov. To je podobno tistemu, kar lahko storite prek urejevalnika pogojev, vendar vam EM omogoča enostavno določanje veliko bolj zapletenih in zmogljivih kriterijev (in omogoča uporabo imena spremenljivke namesto poimenovanja SGQA).

Ta slika prikazuje en način za pregled logike ustreznosti za anketo. Izračunava indeks telesne mase. Enačba ustreznosti je prikazana v oglatem oklepaju takoj za imenom spremenljivke (ki je zelene barve). Torej je ustreznost teže, teže_enot, višine in višine enot 1, kar pomeni, da so ta vprašanja vedno postavljena. Vendar pa je relevantnost za ITM {!is_empty(height) in !is_empty(weight)}, kar pomeni, da bo ITM izračunan samo, če subjekt vnese vrednost za višino in težo (s čimer se izognemo tveganju deljenja z ničlo napaka). Poleg tega je vprašanje Poročilo prikazano samo, če preiskovanec odgovori na vsa štiri glavna vprašanja (višina, višina_enote, teža, teže_enote).

Datoteka:tutorial1.jpg

Ustreznost je prikazana in jo je mogoče urejati na naslednjih mestih:

Ogled/urejanje Ustreznost na ravni vprašanja

Ta enačba izračuna indeks telesne mase (ITM). Vpraša se le, ali oseba najprej vnese svojo višino in težo.

Datoteka:tutorial2.jpg

To je zaslon za urejanje vprašanja ITM.

Datoteka:tutorial3.jpg

Upoštevajte, da ne uporabite zavitih oklepajev, ko vnašate enačbo ustreznosti.

Ogled/urejanje ustreznosti na ravni skupine

To je vzorčna popisna raziskava. Prva stran vpraša, koliko ljudi živi z vami, in to shrani v spremenljivko "cohabs". Ta stran je prikazana samo, če imate več kot enega sostanovalca (torej je prikazana za drugo osebo, ki živi z vami), prav tako pa je prikazana samo, če ste navedli, kako je oseba ena povezana z vami (p1_rel).

Datoteka:tutorial4.jpg

Kot lahko vidite, ima skupina tudi kriterije ustreznosti na ravni vprašanja, tako da se vsako vprašanje pojavi šele, ko odgovorite na vprašanje pred njim (npr. {!is_empty(p1_sex)}). EM za vas združuje ustreznost na ravni skupine in vprašanja. Vprašanja v skupini se zastavljajo samo, če je pomembna skupina kot celota. Nato se zastavi samo podmnožica vprašanj znotraj skupine, ki so pomembna.

Tukaj je zaslon za urejanje ustreznosti na ravni skupine za to vprašanje:

Datoteka:tutorial5.jpg

Upoštevajte, da ne uporabite zavitih oklepajev, ko vnašate enačbo ustreznosti.

Krojenje/Piping

EM vam omogoča preprosto in zapleteno pogojno prilagajanje vaših vprašanj. Včasih potrebujete preprosto zamenjavo, na primer: "Rekel si, da si kupil [ Izdelek]. Kaj vam je bilo pri tem najbolj všeč?". Včasih potrebujete pogojno zamenjavo, kot je " [ Gospod Gospa.] [ Priimek], bi bili pripravljeni izpolniti našo anketo?". V tem primeru želite uporabiti g. ali gospa glede na spol osebe. Drugič potrebujete še bolj zapleteno zamenjavo (na primer na podlagi matematičnega izračuna) EM podpira vsako od teh vrst krojenja/cevovodov.

Pogojne enačbe

Primer indeksa telesne mase prikazuje zmožnost izračuna ITM osebe, čeprav ji dovolite, da svojo višino in težo vnese v metričnih ali nemetričnih enotah.

Datoteka:tailoring7.jpg

Tu je weight_kg {if(weight_units == 'kg', teža, teža * .453592)}. Ta funkcija if() pomeni, da če je subjekt vnesel težo v kilogramih, uporabite to vrednost, sicer pomnožite vneseno vrednost (ki je bila v funtih) z 0,453592, da jo pretvorite v kilograme. Spremenljivka height_m uporablja podoben pristop za izračun višine osebe v metrih, tudi če je vnesla svojo višino v palcih.

ITM izračuna formulo teže kot {teža_kg / (višina_m * višina_m)}.

Nazadnje poročilo pogojno prilagodi sporočilo subjektu in mu pove, kaj je vnesel. ("Rekli ste, da ste visoki 2 metra in težki 70 kg.")

Čeprav na zgornji sliki ni dobro prikazano, weight_status uporablja ugnezdene stavke if(), da kategorizira osebo kot prenizko telesno težo do zelo debelo. Njegovo enačbo si lahko ogledate v prikazu Logic View

Datoteka:tailoring8.jpg

V oknu za urejanje tega vprašanja lahko vidite dve stvari:

  1. Tailoring mora obdati izraze z zavitimi oklepaji
  2. Izrazi lahko zajemajo več vrstic, če želite, kot v tem primeru, olajšati branje ugnezdena pogojna logika.

Datoteka:tailoring9.jpg

Prilagojena vprašanja, odgovori in poročila

Opomba: dinamično prilagajanje morda ne bo delovalo, če so možnosti odgovora na voljo v izbirnih poljih na isti strani z vprašanji. To je posledica dejstva, da krojaški vstavki a oznaka, ki ni veljavna znotraj izbranih možnosti.

Ta primer prikazuje poročilo ITM.

Datoteka:tailoring10.jpg

Tukaj je okno za urejanje istega vprašanja.

Datoteka:tailoring11.jpg

Kot lahko vidite, je vse v zavitih oklepajih obravnavano kot izraz, zato je sintaksa poudarjena (barvno kodirana) na prejšnji sliki. Če bi imeli kakršne koli tipkarske napake (na primer napačno črkovana ali nedefinirana imena ali funkcije spremenljivk), bi EM prikazal napako, kot je ta, ki kaže, da je height_unit nedefinirano ime spremenljivke (pravzaprav je height_units), rnd() pa je nedefinirana funkcija (pravilno ime funkcije je round()). V obeh primerih so napake obdane z rdečim poljem, da jih lažje opazimo in odpravimo.

Datoteka:tailoring12.jpg

Opazite lahko tudi, da lahko hitro ustvarite kompleksna poročila, kot je tabela vnesenih vrednosti ali prilagojeni nasveti.

Zapomnite si, da mora vsako prilagajanje obdati izraze z zavitimi oklepaji, tako da LimeSurvey ve, kateri deli vprašanja so prosto besedilo in katere je treba razčleniti z upraviteljem izrazov.

Potrjevanje

EM nadzoruje, kako deluje večina naprednih možnosti vprašanj. Ti nadzorni vidiki, kot so najmanjše/največje število odgovorov; min/max posamezne vrednosti; min/max vsota vrednosti; in preverjanje, ali se vnesene vrednosti ujemajo z določenimi vzorci nizov. Še naprej vnašate te napredne možnosti vprašanj kot običajno. Vendar pa se zdaj katera koli vrednost v enem od teh polj šteje za izraz, tako da lahko imate minimalna/največja merila s kompleksnimi pogojnimi razmerji do drugih vprašanj.

V vseh teh primerih, ker se možnost naprednega vprašanja vedno obravnava kot izraz, pri določanju ne uporabite zavitih oklepajev.

Strani Vzorčne ankete prikazujejo številne delujoče primere uporabe izrazov za validacije.

Uvod

LimeSurvey uporablja nov modul Expression Manager (EM), ki bo LimeSurveyju omogočil podporo za bolj zapleteno razvejanje, ocenjevanje, validacijo in prilagajanje. Zamenjal bo način, kako LimeSurvey upravlja zamenjave, pogoje in ocene v ozadju. Prav tako bo znatno pospešil obdelavo, saj odpravlja večino branj baze podatkov med izvajanjem. EM je razvil dr. Thomas White (TMSWhite).

Ta stran wiki je dokončna referenca za sintakso in funkcionalnost Expression Managerja.

Ključne definicije

  1. Izraz': Vse, kar je obdano z zavitimi oklepaji
    • Dokler ni praznega prostora takoj za začetnim oklepajem ali pred zaključnim zavitim oklepajem
    • Vsebino izrazov ovrednoti EM, tako da lahko vsebujejo matematične formule, funkcije ter zapleteno obdelavo nizov in datumov.
  2. 'Krojenje': včasih imenovano "cevovod", je to proces pogojno spreminjanje besedila
    • Imate dostop do vseh 'nadomestnih polj', podatkov o udeležencih in podatkov o odzivih.
    • Imate tudi lažji dostop do vprašanj, odgovorov in njihovih lastnosti.
  3. Enačba 'Relevantnost': nov atribut vprašanja, ki nadzoruje vidnost vprašanja
    • Če obstaja enačba relevantnosti, potem je vprašanje prikazano le, če je relevantnost ocenjena kot res.
    • Interno, vsi array_filter in array_filter_exclude ukazi postanejo relevantni na ravni podvprašanja
  4. Equation Vrsta vprašanja: Nova vrsta vprašanja, ki shranjuje izračune ali poročila v zbirko podatkov
    • Je kot vprašanje Boilerplate, vendar se njegova vsebina shrani v baze podatkov, tudi če nastavite "Vedno skrij to vprašanje"
  5. Koda vprašanja: To je prednostno ime spremenljivke za EM
    • To je lahko opisno ime, ki označuje namen vprašanja , kar olajša branje zapletene logike
    • Veljavne kode vprašanj se NE smejo začeti s številko, zato, ko uporabljate kodo vprašanja za oštevilčenje vprašanj, preprosto uporabite »q1«, »q1a« ali »g1q2«.! N!#*To je tisto, kar trenutno postane ime spremenljivke, če izvozite podatke v SPSS ali R, tako da, če izvajate statistično analizo, ste to verjetno že naredili edinstveno.

Ali moram uporabiti EM?

Kratek odgovor je Ne (a tudi da).

EM je popolnoma nazaj združljiv z obstoječimi raziskavami. Če torej z veseljem uporabljate pogoje in ocene v slogu, ki ga je LimeSurvey uporabljal v različicah <= 1.91+, lahko to počnete še naprej.

Vendar pa EM popolnoma nadomesti način, na katerega LimeSurvey interno obravnava pogoje. Čeprav lahko še vedno uporabljate urejevalnik pogojev za ustvarjanje in upravljanje pogojev, jih bo LimeSurvey 1.92 pretvoril v enakovredne enačbe ustreznosti. Kot del nadgradnje bo LimeSurvey 1.92 samodejno pretvoril vse obstoječe pogoje v enačbe ustreznosti.

To bi vam moralo dati najboljše iz obeh svetov – lahko nadaljujete z uporabo LimeSurvey, kot ste navajeni, vendar boste videli ekvivalent Relevance Equation, tako da lahko postopoma preidete neposredno na Relevance Equations, kadar koli se vam zdi primerno.

Ali lahko kombiniram uporabo pogojev in ustreznosti?

ja Za nekatera vprašanja lahko uporabite urejevalnik pogojev, za druga pa urejevalnik ustreznosti. Ko shranite vprašanje, se pogoji samodejno pretvorijo v ustreznost.

Upoštevajte, da predpostavljamo, da če uporabljate urejevalnik pogojev, želite, da ti pogoji prepišejo vsako ročno vneseno enačbo ustreznosti. Torej, če imate obstoječe pogoje in želite ročno urediti ustreznost, najprej izbrišite pogoje za to vprašanje. Natančneje, kopirajte ustvarjeno enačbo ustreznosti v urejevalnik besedil, uporabite meni Pogoji, da izbrišete vse pogoje za to vprašanje (s čimer boste izbrisali tudi ustreznost), nato uredite vprašanje in prilepite ustvarjeno enačbo ustreznosti iz urejevalnika besedil nazaj v polje ustreznosti za to vprašanje (in shranite vprašanje). Če obstaja dovolj povpraševanja po izbrisu pogojev brez izbrisa ustvarjene enačbe pomembnosti, lahko dodamo postopek množične pretvorbe.

Kako naj izbiram med pogoji in ustreznostjo?

Tukaj je seznam prednosti in slabosti vsakega sloga:

Slog Prednosti Slabosti
Pogoji 1. Lep GUI za ustvarjanje preprostih pogojev
2. GUI je dobro dokumentiran in ga razume skupina za podporo
1. Podpira samo preproste primerjave in ne pogojuje dobro IN/ALI
2. Kaskadni pogoji delujejo neredno
3. Počasen - podatkovna baza je intenzivna, zato lahko upočasni dolge ankete
4. Nekateri so poročali o težavah s pogoji ponovnega nalaganja
5. GUI se ne prilagaja dobro, če je vprašanj na desetine, stotine ali tisoče
6. Pretvorba anket v papirni obliki je morda počasna, ker morajo uporabljati imena SGQA
7. Pogosto potrebujejo programerja za kodiranje logike po meri, potrebne za kompleksno razvejanje
Ustreznost 1. Podpira zelo kompleksno logiko, vključno z 80+ funkcijami in matematičnimi/niznimi operaterji
2. Popolna podpora za kaskadno logiko
3. Hitro – brez dodatnih klicev baze podatkov, zato podpira 1000+ anket z vprašanji
4. Brez težav z logiko ponovnega nalaganja, saj ne zahteva kod SGQA
5. Označevanje sintakse meri na 1000+ anket z vprašanji
6. Enostaven in hiter za uporabo za skupine, ki želijo računalniško obdelati obstoječe papirnate ankete.
7. Preprosto podpira polstrukturirane intervjuje in epidemiološke raziskave, ne da bi potrebovali programerje
1. Brez GUI za preproste pogoje - namesto tega uporabite označevanje sintakse
2. Novo, zato podporne ekipe še niso obvladale EM.

Bistvo je, da če ste zadovoljni z delovanjem LimeSurvey 1.91+, ni razloga, da bi spreminjali svoje početje.

Katere so druge prednosti uporabe EM?

Tukaj je nekaj drugih razlogov, zakaj bi morda želeli uporabiti EM.

  1. Izračuni - ustvarite lahko poljuben izračun, ki vam pade na pamet:
    • Imate dostop do vseh običajnih matematičnih operatorjev in funkcij
    • Imate dostop do 70+ matematičnih funkcij, funkcij za obdelavo datumov in nizov
    • Razvijalcem je dokaj enostavno dodati nove funkcije, če jih uporabniki potrebujejo
  2. Shranjevanje izračunov v zbirko podatkov
    • Zdaj lahko izračunate preproste in zapletene izračune in/ali ocene na lestvici IN jih shranite v zbirko podatkov, ne da bi potrebovali JavaScript.
    • Za to uporabite vrsto vprašanja Equation.
  3. Ocene
    • Zdaj lahko ustvarite ocene ali lestvice rezultatov iz katere koli vrste vprašanja, ne samo iz podmnožice, ki je bila prej podprta
    • Uporabite lahko prilagoditev za prikaz tekočih ali skupnih rezultatov ocenjevanja, kjer koli je to potrebno – tudi na isti strani
    • Imate več nadzora nad poročili, ustvarjenimi na podlagi teh ocenjevalnih rezultatov
    • Ocenjevalne rezultate lahko shranite v bazo podatkov, ne da bi potrebovali JavaScript
    • Ocenjevalne rezultate lahko skrijete, ne da bi potrebovali JavaScript ali CSS
  4. Nadomestna polja
  5. *Namesto uporabe {INSERTANS:SGQA} lahko uporabite samo kodo vprašanja - to olajša branje in preverjanje.
    • S tem se tudi izognete pogosti potrebi po urejanju vprašanj za spreminjanje kode SGQA, da bo vse delovalo .
  6. Prilagoditev - besedilo lahko pogojno prikažete na podlagi drugih vrednosti
    • Uporabite ustrezen naslov za zadevo, na primer (npr. »Pozdravljeni [ G./Mrs.] Smith")
    • Izdaj slovnično pravilne stavke, ki temeljijo na ednini/množini: (npr. "Imaš 1 otroka" proti "Imaš 2 otroka")
    • Ustrezno spreženi glagoli in zaklanjajte samostalnike glede na spol in množino osebka.
  7. Novi atributi spremenljivk - za prilagajanje lahko dostopate do naslednjega:
    • (brez pripone) - vzdevek za qcode.code
    • . koda - izbrana koda odgovora na vprašanje, če je relevantno (sicer prazno), ali besedilna vrednost, če ni kodirano vprašanje
    • .NAOK - enako kot .code, vendar je lahko del izračunov ali seznamov tudi če je nepomembno
    • .value - vrednost ocene za vprašanje, če je relevantno (sicer prazno), ali besedilna vrednost, če ni kodirano vprašanje -- na voljo, če so ocene omogočene za anketo, sicer vedno zero
    • .valueNAOK - enako kot .value, vendar je lahko del izračunov ali seznamov, tudi če ni pomembno
    • .shown - odgovor, kot je prikazan uporabniku (to počne {INSERTANS:xxx} )
    • .qid - ID vprašanja
    • .gid - ID skupine
    • .sgqa - vrednost SGQA za vprašanje
    • .jsName - pravilno ime spremenljivke javascript za vprašanje, ne glede na to, ali je definirano na tej ali drugi strani
    • .qseq - zaporedje vprašanj (začenši z 0)
    • .gseq - zaporedje skupine (začenši z 0)
    • . obvezno - ali je vprašanje obvezno (Y/N)
    • .question - besedilo vprašanja
    • .relevance - enačba relevantnosti za vprašanje
    • .grelevance - enačba relevantnosti za skupino
    • .relevanceStatus - ali je vprašanje trenutno relevantno ali ne (logična vrednost (lahko se razlikuje v PHP in JS))
    • .type - vrsta vprašanja (koda z enim znakom)!N !#Dinamične spremembe na strani
    • Vsa ustreznost, izračuni in prilagajanje delujejo dinamično na strani – tako spremembe vrednosti takoj posodobijo stran
    • Vaša vprašanja se torej dinamično pojavljajo/izginejo glede na to, ali so ustrezni
    • Vprašanja so tudi dinamično prilagojena glede na odgovore na strani, tako da lahko vidite tekoče vsote, prilagojene stavke in prilagojena poročila.
  8. Nov zaslon za vnos podatkov
    • Poleg uporabe trenutnem sistemu za vnos podatkov, lahko preprosto uporabite Survey-All-In-One.
    • To podpira ustreznost in prilagajanje na strani, tako da lahko uradniki za vnos podatkov hitro pregledajo in bodo morali vnesti samo ustrezne odzive
    • To je lahko ključnega pomena, če mora vaša oseba za vnos podatkov videti prilagoditev, ki je tudi dinamična.
  9. Odpravlja potrebo po večini JavaScripta po meri
    • EM enostavno podpira zapletene izračune, točkovanje , prilagajanje in pogojna logika.
    • Nekatere stvari bodo še vedno potrebovale JavaScript (na primer postavitve po meri in pogojno skrivanje podelementov vprašanj), vendar lahko vaš JavaScript uporablja funkcije EM, tako da lahko dostopate do vprašanj z njihovo Qcode namesto SGQA in dostop do katere koli zgoraj navedene lastnosti vprašanja.

Katere so druge uporabne nove funkcije, ki jih omogoča EM?

Ne glede na to, ali boste še naprej uporabljali urejevalnik pogojev ali ročno sestavljali enačbe ustreznosti, boste prejeli te dodatne prednosti:

  1. Ustvarite lahko bolj zapletena merila za preverjanje veljavnosti
    • Vse napredne atribute vprašanj (kot so max_answers, min_num_value_n, max_num_value) lahko uporablja izraze. Tako je mogoče vaša najmanjša/največja merila preprosto prilagoditi glede na predhodne odgovore, tudi če so na isti strani.
    • EM obravnava tudi vsa preverjanja, ki temeljijo na regularnih izrazih, tako da lahko robustno kombinirate preg in enačbo- na podlagi atributov vprašanj.
  2. Enostavno prerazvrščanje (ali brisanje) vprašanj in skupin
    • Pred različico 1.92 niste mogli prerazporediti vprašanj ali skupin, če je LimeSurvey menil, da bi se takšno prerazporejanje lahko pokvarilo pogojih, v katerih so bili uporabljeni. Podobno ne morete izbrisati vprašanj, če so bila od njih odvisna katera koli druga vprašanja.
    • Z označevanjem sintakse EM je preprosto videti in potrditi, ali poskušate uporabiti vprašanja, preden so navedena. Tako vam zdaj omogočamo, da vprašanja in skupine preuredite ali izbrišete, kadar koli želite. EM bo posodobil vse označevanje sintakse, da vam bo pokazal morebitne napake.
    • Pogled vprašanj za ponovno vrstni red je bil izboljšan za pomoč pri takem pregledu. Zdaj prikazuje enačbo pomembnosti vprašanja in njegovo prilagajanje, tako da lahko takoj vidite, ali katera koli spremenljivka postane rožnata (kar pomeni, da se uporabi, preden se razglasi).
  3. Navigacijski indeks vprašanj/skupin je vedno na voljo in točen
    • Pred različico 1.92 ti indeksi niso bili na voljo, če so bili zapleteni pogoji
    • Z EM lahko zagotovimo, da so točni.
    • Subjekt lahko celo skoči nazaj na prejšnje vprašanje, spremeni odgovor , nato skočite naprej (ali pošljite)
      • Pri skoku naprej bo EM ponovno preveril vsa vmesna vprašanja/skupine.
      • Če katero koli vprašanje postane nepomembno, bo v zbirki podatkov razglašeno za NULL. tako da so vaši podatki interno skladni
      • Če kakršna koli vprašanja postanejo pomembna ali na novo ne izpolnjujejo obveznih ali pravil preverjanja, se bo EM ustavil na tej strani in prisilil uporabnika, da odgovori na ta vprašanja, preden skoči na končni cilj.
#Samodejna pretvorba pogojev v ustreznost
    • Ko nadgradite svojo zbirko podatkov, bodo za vse obstoječe ankete, ki imajo pogoje, ustvarjene enačbe ustreznosti
    • Kadar koli uvozite anketo, bodo po potrebi ustvarjene enačbe ustreznosti
    • Kadar koli dodate, izbrišete ali spremenite pogoje, bo EM ustvaril ustrezno enačbo ustreznosti.
  1. Priročno označevanje sintakse
    • Ko EM prikaže enačbo pomembnosti, bo prikazal Qcode, tudi če vnesli ste kodo SGQA, saj predvidevamo, da bo to lažje brati.
    • Vse spremenljivke so barvno kodirane, da pokažejo, ali so bile deklarirane pred ali za trenutnim vprašanjem (ali pred ali za trenutno skupino). To vam omogoča hitro odkrivanje in popravljanje primerov, ko poskušate uporabiti spremenljivke za ustreznost (vključno z array_filter), prilagajanje ali validacijske enačbe, preden jih objavite.
    • Poleg tega, če z miško premaknete nad barvno kodirano spremenljivko , boste videli najpomembnejše metapodatke o tem vprašanju. To vključuje zaporedje skupine #, zaporedje vprašanja #, kodo Q, besedilo vprašanja in vse razpoložljive izbire odgovorov (če gre za vrsto vprašanja z oštevilčenimi možnostmi odgovorov).
      • Seznam izbir odgovorov uporablja to sintakso : 'odgovori':{ključ:val, ... }.
      • ključ ima sintakso 'lestvica~koda', kjer je lestvica lestvica odgovorov (npr. za dvojno lestvico) in koda je koda odgovora.
      • val ima sintakso 'prikazana vrednost', kjer je vrednost vrednost ocene (če uporabljate ocene, drugače koda)(npr. Qcode.value) in prikazano je prikazana vrednost, kot jo vidi subjekt (npr. Qcode.shown)
      • To pomeni, da lahko številne raziskave uporabljajo izračune, ne da bi potrebovali način ocenjevanja. Če ste našteli možnosti odgovorov, ki so edinstveni, nedecimalni in nenegativni, lahko preprosto izračunate vrednosti Qcode.code.
  2. Enostaven pregled celotne logike in vsebine ankete
    • Obstaja nova funkcija Prikaži logiko ankete, ki vam omogoča ogled vsega o anketi (ali skupini ali vprašanju) na eni strani.
    • Prikaže podrobnosti na ravni skupine, vprašanja, podvprašanja in odgovora za izbran obseg (anketa v primerjavi s skupino v primerjavi z vprašanjem)
    • Prikaže tudi ustreznost, ustreznost na ravni podvprašanja (za array_filter in array_filter_exclude) in ustvarjeno validacijsko enačbo (za preg in morebitna validacijska pravila, kot je najmanjša/največja vsota/število vrednosti) in vsi atributi vprašanj, ki niso prazni.
    • Vse je skladenjsko označeno, tako da lahko vidite morebitne sintaksne napake (kot so neuravnoteženi oklepaji ali uporaba spremenljivk, preden so bile deklarirane)
    • Skladnja- Highligting podpira hitro navigacijo in urejanje ankete.
      • Če kliknete ime spremenljivke, se odpre okno brskalnika (ali zavihek), ki vam prikaže to vprašanje in vam omogoča urejanje.
      • Če kliknete ime skupine, se odpre okno (ali zavihek) brskalnika, ki prikazuje pogled za preurejanje skupine, tako da lahko preprosto premikate vprašanja.
      • Vsi atributi vprašanja so sintaktično označeni. To vam omogoča nastavitev in ogled izrazov v naprednih možnostih vprašanj (na primer določanje največjega/najmanjšega števila/vsote vrednosti na izrazu)
    • Avtor EM je uporabil podoben pogled (malo čistejši), da je svojim sodelujočim epidemiologom in institucijam omogočil Nadzorni odbor potrdi in odobri ankete s tisoči vprašanj v zelo razvejanih in prilagojenih strukturiranih intervjujih

Začetek

Najboljši način, da začnete z EM je:

  • Namestiti najnovejšo stabilno različico s http://www.limesurvey.org/en/download
  • Uvoziti in raziskati vzorčne ankete .
  • Raziščite primere uporabe in navodila in primere po korakih.
  • Raziščite dokumentacijo EM (ta stran)! N!*Preglejte vgrajeno zbirko testov EM
    • V kateri koli anketi pod orodji izberite možnost EM
    • Razpoložljive funkcije navajajo 70+ funkcij in sintakso
    • Preizkusi enot izoliranih Izrazi
      • prikazuje primere uporabe vseh funkcij in operatorjev EM ter rezultatov PHP in JavaScript
      • upoštevajte, da obstaja nekaj funkcij, ki ustvarjajo različne rezultate v različicah PHP in JavaScript, zato vam ta stran omogoča ustrezno načrtujte svojo EM logiko.

Katero funkcionalnost razširi/zamenja Expression Manager? (LimeSurvey <= 1,91+)

Pogoji => Ustreznost

Conditions controlled which  questions are visible.  The general syntax was SGQA operator Value, like 111X2X3 == "Y".  Conditions could be ANDed or ORed together, but mixing ANDs and ORs was difficult.  The conditions themselves were stored in a separate table, and large portion of LimeSurvey's code was devoted to managing Conditions.  Because of extensive database access, processing large numbers of conditions could cause noticable performance problems.  Furthermore, once you had conditions assigned to questions or groups, you were often not allowed to re-order or delete them.

Assessments => Equations and  Micro-Tailoring

Assessments let users create scale scores from a collection of questions.  However, they could not dynamically change on the current page, and their values were not stored to the database.

Replacements => Micro-Tailoring

Users could tailor some messages and questions based  upon prior responses.  For example, a question might be, {TOKEN:FIRSTNAME}, you said {INSERTANS:111X3X4} was your favorite sport.  However, it was not possible to do conditional tailoring (like say "Mr." or "Mrs." depending upon the person's gender), or conjugate verbs or decline nouns without fancy JavaScript.  Authors could implement surveys that seemed to tailor questions, but it required separate questions for each permutation, and complex conditions to decide which questions to display.

Validation

Question could be validated with Regular expressions, or minimum/maximum values, or let an SGQA response serve as the minimum or maximum value.  However, validations could not be based upon calculations of other variables without fancy JavaScript.

Equations

Equations were not supported without fancy JavaScript.

Equation Question Type

Equations could not be saved to the database (e.g. the final score for an assessment) without fancy JavaScript.

How Will Expression Manager Replace/Extend That Functionality?

The Expression Manager is a new core module within LimeSurvey that makes it much easier to support the type of complex functionality that used to require custom JavaScript.  It is also replacing the way LimeSurvey currently manages Conditions and Assessments.

New Terminology When Referring to Expression Manager (EM)

EM "thinks" of its functionality in the following terms:

  • Relevance-based Branching - if a question is relevant, then ask it, otherwise don't (e.g. make it invisible, and mark it as NULL in the database).  There is a new Relevance field for all Question types, and also for each Group (so you can apply a set of conditions to an entire group without having to copy the same condition to each question, and/or combine group and question-level conditional logic).
  • Tailoring - Once you know which questions should be asked, tailoring (sometimes called piping) specifies how the question should be asked. This lets you support not only simple subsitution (like {TOKEN:FIRSTNAME}), but also conjugation of verbs and declination of nouns based upon the gender or number of your subjects.  It also lets you change the message you deliver to a subject based upon whether they answered (or how they answered) other questions.
  • Equations - EM adds a new question type called Equation which stores the result of an Expression.  These equations results are computed and written to the database, even if you hide them on the page.  Thus, they are useful for hidden scoring calculations, navigation based upon complex equations, assessments, and reports that should be generated and easily available within the database.

Relevance and Cascading Relevance

Every question type now has a Relevance option which controls whether the question is displayed.  EM processes each of the Relevance Equations in the order they should appear in the survey.  If the expression is true (or missing - to support legacy surveys), the question will be displayed. If it is not relevant, then the question will be hidden, and the value will be NULLed in the database.  If there are no relevant questions in a group, the entire group will be skipped.

Moreover, if any of the variables within an expression is irrelevant, then the expression always evaluates to false.  This enables Cascading Relevance so that you do not have to write very long Relevance equations for each question.

Say you have 5 questions Q1-Q5, and you only want to show Q2 if Q1 was answered, and Q3 if Q2 was answered, etc.  The relevance equations might be:

Question Code Relevance Question
Q1 1 What is your name?
Q2 Q1 {Q1}, how old are you?
Q3 Q2 So, you are {Q2} years old.  Are you married?
Q4 Q3 == "Y" {Q1}, how long have you been married?
Q5 Q4 How many children do you have, {Q1}?

The relevance calculations also work in JavaScript - so you could put all the above questions on one page and it would still work as expected.  In fact, EM totally replaces how EM processes Survey vs. Group vs. Question-at-a-time survey formats.  They now all use the exactly same navigation engine so they work identically regardless of survey style.

As long as you are on the same page, any data you entered will still be there, just hidden.  So, if you enter some information, then choose an option that makes them irrelevant, then make them relevant again, your answers will still be available.  However, as soon as you move to a different page, all irrelevant responses will be lost to integrity of the dataset.

Group-Level Relevance

Expression Manager also supports group-level relevance.  This makes it easier to implement looping.   Say you want to collect information about up to 10 entities (such a products or people in a household), where you first determine how many entities need follow-up (such as by asking how many people live in a household, or having people check which products they like from a long list).  After knowning how many entities need follow-up, you can use Group-level relevance like {count >= 1}, {count >=2}, ... {count >= 10} for each of the 10 groups of follow-up questions.  Within each group, you can have question-level conditional logic (e.g. gender or age-specific follow-up questions for each subject).  The question and group-level relevance equations are ANDed together to determine which should be shown.

Tailoring / Piping

Anything within curly braces is now treated as an Expression (with one exception described below).  Expressions have acccess to all of the LimeReplacementFields, all of the variables (via several aliases), all typical equation operators (mathematical, logical, and comparison), and dozens of functions (that even work dynamically on the client-side).

Using these equations, you can do things such as:

  1. Conditionally show tailored messages to the respondants based upon prior responses
  2. Create Assessments and show Assessment results (or conditionally branch or show messages) based upon those results, all without using the Assessments module itself
  3. Conjugate verbs and decline nouns within questions, answers, and reports.
  4. Show summaries of responses before the "Show your answers" page at the end of the survey

Equations

There is a new question type called  Equation.  It is like a Boilerplate questions, except that it stores the value of what is displayed in the database.  So, if the Equation Question text contains an Assessment computation, that value would be stored in the database in a variable that can be displayed within public or private statistics.

This solves a common request for storing Assessment scores within the database

Syntax

Anything contained within curly braces is now considered an Expression (with one exception:  there must be no leading or trailing whitespace - this is needed to ensure the Expression Manager does not try to process embedded JavaScript).

Note, it is OK for expressions to span multiple lines, as long as there is no whitespace after the opening  curly brace or before the closing curly brace.  This is especially helpful for nested if() statements like this:

{if(is_empty(PFTotals),
 '',
 if(PFTotals >= -5 && PFTotals <= -4,
   'Very Soft',
   if(PFTotals >= -3 && PFTotals <= -2,
     'Soft',
     if(PFTotals == -1,
       'Somewhat Soft',
       if(PFTotals == 0,
         'Moderate',
         if(PFTotals == 1,
           'Somewhat Hard',
           if(PFTotals >= 2 && PFTotals <= 3,
             'Hard',
             if(PFTotals >= 4 && PFTotals <= 5,
               'Very Hard',
               ''
             )
           )
         )
       )
     )
   )
 )
)}
Expression Manager supports the following syntax:
  • All standard mathematical operators (e.g. +,-,*,/,!)
  • All standard comparison operators (e.g. <,<=,==,!=,>,>=, plus these equivalents:  lt,le,eq,ne,gt,ge)
  • Parentheses (so you can group sub-expressions)
  • Conditional operators (e.g. &&,| | and these equivalents: and,or)
  • Single and double-quoted strings (which can each embed strings with the other quote type)
  • Comma operator (so can have a list of expressions and just return the final result)
  • Assignment operator (=)
  • Pre-defined variables (to refer to questions, question attributes, and responses) - e.g. all of the SGQA codes
  • Pre-defined functions (there are already 70+, and it is easy to add more)

Operators

EM syntax follows normal operator precedence:

Level Operator(s) Description
1 () parentheses for grouping or calling functions
2 ! - + unary operators: not, negation, unary-plus
3 * / times, divide
4 + - plus, minus
5 < <= > >= lt le gt ge relative comparisons
6 == != eq ne equality comparisons
7 and logical AND
8 or logical OR
9 = assignment operator
10 , comma operator

Warning with plus operator (+)

For consistency between JavaScript and PHP, the plus operator (+) does addition if both operands are numeric, but does concatenation if both parts are non-numeric strings.  However, we recommend using the join() function for concatenation and sum() function for addition, as that makes your intent more clear, and avoids unexpected results if you were expecting strings but got numbers instead (or vice versa).

Warning with mismatch between number and string and alphabetic comparison

When you want to compare value with relative or equality comparisons, pay attention to type mismatch. Value entered by user or answer code selected can be used as number if it's clearly a number. If you surround one of the values with "it will force the comparison as text (alphabetic compare). If you want to compare numerically, never surround the number with quotation marks, ".

For example Q0.NAOK > "50" is true if Q0.NAOK is a numeric question with 9 as value. This is because the operator > will assume it's alphabetical compare and not numerical.

To be sure to compare integer value, you can use intval(Q0.NAOK) > 50, just remember if Q0.NAOK is not a number (empty or a string), then intval(Q0.NAOK) === 0. To compare string value ("A" < "B") use strcmp directly : strcmp(Q0.NAOK,"B") or strcmp(Q0.NAOK,"A5").

Caution about using Assignment Operator (=)

Note, you should avoid using the assignment operators unless absolutely necessary, since they may cause unexpected side-effects.  For example, if you change the value of a previous response, the cascading relevance and validation logic between that question and the current question is not re-computed, so you could end up with internally inconsistent data (e.g. questions that stay answered but should have been NULLed, or questions that are skipped but should have been answered).  In general, if you want to assign a value to a variable, you should create an Equation question type, and use an expression to set its value.  However, there are some rare times that people really need this operator, so we made it available.

To help caution you about this operator, it is shown in red font within the syntax equations (so that you don't confuse it with "==")

Using Assignment Operator

The main reasons you may want to use assignment are:

  • You need to set the default value for a question that does not accept defaults via equation (such as list radio, where the user interface lets you pick one of the answer options, but does not let you enter an equation).  However, be careful, as LimeSurvey will not be able to validate that your equation generates one of the allowable answers for that question.
  • You need to forcibly change the response to a previous question based upon a later response
  • You need complex quota : using one hidden single choice for quota and set it using assignment
  • etc...

You can use all expression manager system for this purpose.

  Assignment is done only in PHP. This doesn't update any values on the same page, but only when the user navigates with next, previous, save ….


  If you don't use an equation question type for this purpose: the assignment is done only after the logic of the current page is done. The recommended method is to always use an equation question.


Some example:

  • Set answer to a short text question in lowercase : {QCODE=strtolower(QCODE.NAOK)}
  • Set a default answer to an array question type at start of a survey : {Q1_SQ1=((is_empty(Q1_SQ1.NAOK),"A99",Q1_SQ1.NAOK)}
  • Set a default answer to an array texts question type at start of a survey : {Q1_SQY1_SQX1 = ((is_empty(Q1_SQY1_SQX1.NAOK),"Inserted answer", Q1_SQY1_SQX1.NAOK)}
  • Set an answer with condition : {QCODE=if(YesNo="Y","A1","")}

XSS security

With XSS enable, some expression manager system can not be used :

  • starting a HTML tag in expression but ending in another expression
  • use a complex expression in URL.

Example and workaround

  • {if( 1 ,"<strong>","")}information{if( 1 ,"</strong>","")} is broken with XSS security, here you can use {if(1,"<strong>information</strong>","information")}
  • <a href="/script.php?value={if(QCODE == "Y","yes","no")}">next</a>, here you can use an equation question because using a complete question code is OK : <a href="/script.php?value={EQUATION.NAOK}">next</a>

Access to Variables

Expression Manager provides read-only access to whichever variables we might need.  For backwards compatibility, it provides access to the following:

  • TOKEN:xxx - the value of a TOKEN (e.g. TOKEN:FIRSTNAME, TOKEN:ATTRIBUTE_5) (Only for NOT anonymous survey).
  • INSERTANS:SGQA - the display value of an answer (e.g. "Yes"). For Expression Manager it's the same that using {QCODE.shown}.
  • All {XXX} values used by templates.
  • In question text, you can use {QID} replaced by the question id and {SGQ} replaced by the SGQA of the question

In addition, Expression Manager lets you refer to variables by the Question Code (the 'title' column in the questions table within the database).  This is also the variable label used when you export your data to SPSS, R, or SAS.  For example, if you have questions about name, age, and gender, you could call those variables name, age, and gender instead of 12345X13X22, 12345X13X23, and  12345X13X24.  This makes equations easier for everyone to read and validate the logic, plus makes it possible to shuffle questions around without having to keep track of group or question numbers.

Important: It is only safe to refer to variables that occur in preceding pages or questions.

Furthermore, Expression Manager lets you access many properties of the Question:


Syntax Meaning Example Example Result
Qcode an alias for Qcode.code {implode(',',name,gender)} 'Tom','M'
Qcode.code the selected response code for the question if it is relevant (otherwise blank), or the text value if it is not a coded question {implode(',',name.code,gender.code)} 'Tom','M'
Qcode.NAOK same as Qcode - see discussion of NAOK {gender.NAOK} 'M'
Qcode.value the assessment value for the question if it is relevant (otherwise blank), or the text value if it is not a coded question {gender.value} '1'
Qcode.valueNAOK same as Qcode.value - see discussion about NAOK {gender.valueNAOK} '1'
Qcode.shown the dispay value for the question {implode(',',name.shown,gender.shown)} 'Tom','Male'
Qcode.question the text of the question {gender.question} 'What is your gender?'
Qcode.mandatory whether the question is mandatory (Y/N) {gender.mandatory} 'N'
Qcode.qid the internal question number (not the sequential number) {gender.qid} 337
Qcode.type the question type {gender.type} 'G'
Qcode.jsName the correct javascript name for the question, regardless whether declared on or off this page {gender.jsName} 'java1827X3X337'
Qcode.gid the internal group number (not the sequential number) {gender.gid} 3
Qcode.qseq the sequential number of the question, starting from 0 {gender.qseq} 5
Qcode.gseq the sequential number of the group, starting from 0 {gender.gseq} 1
Qcode.relevanceStatus whether the question is currently relevant (0 or 1) {gender.relevanceStatus} 1
Qcode.relevance the question-level relevance equation {gender.relevance} '!is_empty(name)'
Qcode.grelevance the  group-level relevance equation {gender.grelevance} 'num_children >= 5'
Qcode.sgqa the SGQA value for this question {gender.sgqa} '1827X3X337'

HTML editor issue

  This issue is fixed after 2.05 build 140803


If you use HTML editor, some characters are replaced by HTML entities.

  • & by &amp;
  • < by &lt;
  • > by &gt;

If you use HTML editor you need to use :

  • and for &
  • lt for <
  • le for <=
  • gt for >
  • ge for >=

Qcode Variable Naming

Here are the details of how to construct a Qcode (and access some properties) by question type.  In general, Qcodes are constructed as:

 QuestionCode . '_' . SubQuestionID . '_' . ScaleId

For comment and other, question code are QuestionCode_comment and QuestionCode_other

Type Description Code SubQs Answer Options Scales Answer Code Answer Shown Relevance
5 5 Point Choice Radio-Buttons Q1 1-5 {Q1} {Q1.shown} {Q1==3}
B Array (10 Point Choice) Radio-Buttons Q2 L1-L6 1-10 {Q2_L2} {Q2_L2.shown} {Q2_L2==7}
A Array (5 Point Choice) Radio-Buttons Q3 1-5 1-5 {Q3_1} {Q3_1.shown} {Q3_1>=3}
1 Array (Flexible Labels) Dual Scale Q4 sq1-sq5 0:a1-a3 1:b1-b3 {Q4_sq1_0} {Q4_sq1_1.shown} {Q4_sq1_1=='b2'}
H Array (Flexible) - Column Format Q5 1-5 s,m,t {Q5_1} {Q5_1.shown} {Q5_1=='s'}
F Array (Flexible) - Row Format Q6 F1-F5 1-5 {Q6_F3} {Q6_F3.shown} {Q6_F3==4}
E Array (Increase/Same/Decrease) Radio-Buttons Q7 1-7 I,S,D {Q7_4} {Q7_4.shown} {Q7_4=='D'}
: Array (Multi Flexi) 1 To 10 Q8 ls1,todo,ls2 min,max,avg {Q8_ls1_max} {Q8_ls2_avg.shown} {Q8_ls2_min==7}
; Array (Multi Flexi) Text Q9 hp,st,sw 1st,2nd,3rd {Q9_hp_3rd} {Q9_hp_3rd.shown} {Q9_hp_3rd=='Peter'}
C Array (Yes/Uncertain/No) Radio-Buttons Q10 1-5 Y,N,U {Q10_1} {Q10_1.shown} {Q10_3=='Y'}
X Boilerplate Question Q11 {Q11.shown}
D Date Q12 {Q12} {Q12.shown}
* Equation Q13 {Q13} {Q13.shown} {Q13>5}
~124~ File Upload (records number of files uploaded) Q14 {Q14} {Q14>0}
G Gender Drop-Down List Q15 M,F {Q15} {Q15.shown} {Q15=='M'}
U Huge Free Text Q16 {Q16} {Q16.shown} {strlen(Q16)>100}
I Language Question Q17 {Q17} {Q17.shown} {Q17=='en'}
! List - Dropdown Q18 1-5 {Q18} {Q18.shown} {Q18==3}
L List Drop-Down/Radio-Button List Q19 A-Z {Q19} {Q19.shown} {Q19=='X'}
O List With Comment Drop-Down/Radio-Button List + Textarea Q20 A-F {Q20},{Q20comment} {Q20.shown} {Q20=='B'}
T Long Free Text Q21 {Q21} {Q21.shown} {strstr(Q21,'hello')>0}
M Multiple Choice Checkbox Q22 A-F, other {Q22_E}, {Q22_other} {Q22_E.shown}, {Q22_other.shown} {Q22_E=='Y'}
P Multiple Choice With Comments Checkbox + Text Q23 A-F {Q23_D}, {Q23_Dcomment} {Q23_D.shown} {!is_empty(Q23)}
K Multiple Numerical Question Q24 self,mom,dad {Q24_self} {Q24_self.shown} {Q24_self>30}
Q Multiple Short Text Q25 A-F {Q25_B} {Q25_B.shown} {substr(Q25_B,1,1)=='Q'}
N Numerical Question Type Q26 {Q26} {Q26.shown} {Q26 > 30}
R Ranking Style Q27 1-4 {Q27_1} {Q27_1.shown} {Q27_1==3}
S Short Free Text Q28 {Q28} {Q28.shown} {Q28=='mine'}
Y Yes/No Radio-Buttons Q29 {Q29} {Q29.shown} {Q29=='Y'}

The reserved 'this', 'self', and 'that' variables

Quite often, you want to evalute all parts of a question, such as counting how many subquestions have been answered, or summing the scores.  Other times, you want to process just certain rows or columns of a question (such as getting the row or column sums and storing them in the database).  These reserved variables make that process relatively painless.

The 'this' variable is used exclusively within the "Whole question validation equation" and "Sub-question validation equation" advanced question options.  It expands to the variable names of each of the cells within those questions.  So, if you want to make sure that each entry is greater than three, you would set the "Sub-question validation equation" to (this > 3).

The 'self' and 'that' variable are more powerful, and serve as macros which are expanded prior to processing equations.  The syntax choices are:

  • self
  • self.suffix
  • self.sub-selector
  • self.sub-selector.suffix

suffix is any of the normal qcode suffixes (e.g. NAOK, value, shown)

sub-selector is one of:

  • comments - only subquestions that are comments (e.g., from multiple choice with comment and list with comment)
  • nocomments - only subquestions that are not comments
  • sq_X - where X is a row or column identifier. Only subquestions matching pattern X are selected. Note that search is done on complete code identifier, then sq_X match and include subquestions nX, X, Xn (e.g. if you use sq_1, subquestions a1, 1a, 1, 11 or 001 was included). Put attention at dual scale question type where subquestions code are QCODE_SQCODE_1 and QCODE_SQCODE_1 and to ranking question type where subquestions code are QCODE_1,QCODE_2 ....
  • nosq_X - where X is a row or column identifier. Only subquestions not matching pattern X are selected. Note that search is done on complete code identifier, then nosq_X match and does not include subquestions nX, X, Xn

Examples:

  • Has any part of a question been answered?  {count(self.NAOK)>0}
  • What is the assessment score for this question?  {sum(self.value)}

You can also use these to get row and column totals.  Say you have a array of numbers with rows A-E and columns 1-5.

  • What is the grand total?  {sum(self.NAOK)}
  • What is the total of row B?  {sum(self.sq_B.NAOK)}
  • What is the total of column 3? {sum(self.sq_3.NAOK)}

The 'that' variable is like the 'self' variable, but lets you refer to other questions.  Its syntax is:

  • that.qname
  • that.qname.suffix
  • that.qname.sub-selector
  • that.qname.sub-selector.suffix

qname is the question name without any subquestion extensions.  So, say you create a question 'q1', that is its qname

Examples:

  • Has any part of question q1 been answered?  {count(that.q1.NAOK)>0}
  • What is the assessment score for q2?  {sum(that.q2.NAOK)}
  • What is the grand total of q3? {sum(that.q3.NAOK)}
  • What is the total of row C in q4?  {sum(that.q4.sq_C.NAOK)}
  • What is the total of column 2 in q4? {sum(that.q4.sq_2.NAOK)}

The 'self' and 'that' variables can be used in any relevance,  validation, or tailoring.

The one caveat is that when you use the Show Logic File feature, it will show you the expanded value of 'self' and 'that'.  This lets you see the actual equation that will be generated so that you (and Expression Manager) can validate that the variables exist.  This may seem confusing since you may see quite lenghty equations.  However, if you edit the question, you will see the original equation using 'self' and/or 'that'

Also note that you should not use these variables if (a) you want to explicitly name each variable used in an equation, or (b) use variables that do not have subquestions (e.g. single response questions).  In those cases, prefixing a variable with 'that' is overkill, and you run the risk of getting unexpected results.

Usage of NAOK

NAOK --> "Not Applicable" (NA) is alright (OK)

Using NAOK, means that all or some of the variables are irrelevant (e.g. "Not Applicable" (NA) is alright (OK)).

When you put some variable from question in any equation : if this question (or subquestion) is hidden by condition : this disable all equation.

For example : count(Q1_SQ1,Q1_SQ2,Q1_SQ3,Q1_SQ4) give always an empty string if one subquestion of Q1 is filtered. To count the number of checked subquestion in such question can be count(Q1_SQ1.NAOK,Q1_SQ2.NAOK,Q1_SQ3.NAOK,Q1_SQ4.NAOK). If the sub question is hidden :Expression manager return an empty string.

Without NAOK : if one question or one subquestion is hidden : Expression Manager return always an empty string, same to return false.

The .shown always use the NAOK system (empty string if hidden) but if you need the code of the answer : it's always a good idea to add .NAOK after the question code. Except if you need it and know what you do.

Another example and information is provided at Overriding Cascading Conditions

Access to Functions

Expression Manager provides access to mathematical, string, and user-defined functions, as shown below.  It has PHP and JavaScript equivalents for these functions so that they work identically on server-side (PHP) and client-side (JavaScript).  It is easy to add new functions.

Implemented Functions

The following functions are currently available:

Function Meaning Syntax
abs Absolute value number abs(number)
acos Arc cosine number acos(number)
addslashes Quote string with slashes string addslashes(string)
asin Arc sine number asin(number)
atan Arc tangent number atan(number)
atan2 Arc tangent of two variables number atan2(number, number)
ceil Round fractions up number ceil(number)
checkdate Returns true(1) if it is a valid date in gregorian calendar bool checkdate(month,day,year)
convert_value Convert a numerical value using a inputTable and outputTable of numerical values number convert_value(fValue, iStrict, sTranslateFromList, sTranslateToList)
cos Cosine number cos(number)
count count the number of answered (non-blank) questions in the list number count(arg1, arg12, ..., argN)
countif Count the number of answered questions in the list equal to the first argument number countif(matches, arg1, arg2, ... argN)
countifop Count the number of answered questions in the list which pass the criteria (arg op value) number countifop(op, value, arg1, arg2, ... argN)
date Format a local date/time string date(format [, timestamp=time()])
exp Calculates the exponent of e number exp(number)
fixnum Display numbers with comma as radix separator, if needed string fixnum(number)
floor Round fractions down number floor(number)
gmdate Format a GMT date/time string gmdate(format [, timestamp=time()])
html_entity_decode Convert all HTML entities to their applicable characters (always uses ENT_QUOTES and UTF-8) string html_entity_decode(string)
htmlentities Convert all applicable characters to HTML entities (always uses ENT_QUOTES and UTF-8) string htmlentities(string)
expr_mgr_htmlspecialchars Convert special characters to HTML entities (always uses ENT_QUOTES and UTF-8) string htmlspecialchars(string)
expr_mgr_htmlspecialchars_decode Convert special HTML entities back to characters (always uses ENT_QUOTES and UTF-8) string htmlspecialchars_decode(string)
idate Format a local time/date as integer string idate(string [, timestamp=time()])
if (Updated in 3.0.2 ) Excel-style if(test,result_if_true[,result_if_false = ""]) if(test,result_if_true[,result_if_false = ""])
implode Join array elements with a string string implode(glue,arg1,arg2,...,argN)
intval Get the integer value of a variable int intval(number [, base=10])
is_empty Determine whether a variable is considered to be empty bool is_empty(var)
is_float Finds whether the type of a variable is float bool is_float(var)
is_int Find whether the type of a variable is integer bool is_int(var)
is_nan Finds whether a value is not a number bool is_nan(var)
is_null Finds whether a variable is NULL bool is_null(var)
is_numeric Finds whether a variable is a number or a numeric string bool is_numeric(var)
is_string Find whether the type of a variable is string bool is_string(var)
join (New in 2.0 build 130129) Join elements as a new string join(arg1, arg2, ... argN)
list Return comma-separated list of non-blank values string list(arg1, arg2, ... argN)
listifop (New in 3.16.1 ) Return a 'glue'-separated list of the specified question property (retProp) from questions in the list which pass the criteria (cmpProp op value) string listifop(cmpProp, op, value, retProp, glue, sgqa1, sgqa2, ... sgqaN)
log The logarithm of number to base, if given, or the natural logarithm. number log(number,base=e)
ltrim Strip whitespace (or other characters) from the beginning of a string string ltrim(string [, charlist])
max Find highest value number max(arg1, arg2, ... argN)
min Find lowest value number min(arg1, arg2, ... argN)
mktime Get UNIX timestamp for a date (each of the 6 arguments are optional) number mktime([hour [, minute [, second [, month [, day [, year ]]]]]])
modulo-function The modulo function is not supported yet. You can use the floor() function instead floor(x/y)==(x/y)
nl2br Inserts HTML line breaks before all newlines in a string string nl2br(string)
number_format Format a number with grouped thousands string number_format(number)
pi Get value of pi number pi()
pow Exponential expression number pow(base, exp)
quoted_printable_decode Convert a quoted-printable string to an 8 bit string string quoted_printable_decode(string)
quoted_printable_encode Convert a 8 bit string to a quoted-printable string string quoted_printable_encode(string)
quotemeta Quote meta characters string quotemeta(string)
rand Generate a random integer, see this example int rand() OR int rand(min, max)
regexMatch compare a string to a regular expression bool regexMatch(pattern,input)
round Rounds a number to an optional precision number round(val [, precision])
rtrim Strip whitespace (or other characters) from the end of a string string rtrim(string [, charlist])
sin Sine number sin(arg)
sprintf Return a formatted string string sprintf(format, arg1, arg2, ... argN)
sqrt Square root number sqrt(arg)
stddev Calculate the Sample Standard Deviation for the list of numbers number stddev(arg1, arg2, ... argN)
str_pad Pad a string to a certain length with another string string str_pad(input, pad_length [, pad_string])
str_repeat Repeat a string string str_repeat(input, multiplier)
str_replace Replace all occurrences of the search string with the replacement string string str_replace(search, replace, subject)
strcasecmp Binary safe case-insensitive string comparison int strcasecmp(str1, str2)
strcmp Binary safe string comparison int strcmp(str1, str2)
strip_tags Strip HTML and PHP tags from a string string strip_tags(str, allowable_tags)
stripos Find position of first occurrence of a case-insensitive unicode string (starting by 0, return false if not found) int stripos(haystack, needle [, offset=0])
stripslashes Un-quotes a quoted string string stripslashes(string)
stristr Case-insensitive strstr string stristr(haystack, needle [, before_needle=false])
strlen Get string length int strlen(string)
strpos Find position of first occurrence of an unicode string (starting by 0, return false if not found) int strpos(haystack, needle [ offset=0])
strrev Reverse a string string strrev(string)
strstr Find first occurrence of a string string strstr(haystack, needle[, before_needle=false])
strtolower Make a string lowercase string strtolower(string)
strtotime Parse about any English textual datetime description into a Unix timestamp int strtotime(string)
strtoupper Make a string uppercase string strtoupper(string)
substr Return part of an unicode string string substr(string, start [, length])
sum Calculate the sum of values in an array number sum(arg1, arg2, ... argN)
sumifop Sum the values of answered questions in the list which pass the criteria (arg op value) number sumifop(op, value, arg1, arg2, ... argN)
tan Tangent number tan(arg)
time Return current UNIX timestamp number time()
trim Strip whitespace (or other characters) from the beginning and end of a string string trim(string [, charlist])
ucwords Uppercase the first character of each word in a string string ucwords(string)
unique Returns true if all non-empty responses are unique boolean unique(arg1, ..., argN)

Functions that are Planned or Being Considered

Other functions that are planned (or being considered) but which are not implemented yet include the following.  Some of these are for backwards compatability with another survey tool.

Syntax Meaning Comments
e() returns the value of e
formatDate(X,PAT) return the string value of date X formatted according to Java data format pattern PAT
formatNumber(X,PAT) return the string value of number X formatted according to Java number format pattern PAT
getAnsOption(X) Core plugin ExpressionAnswerOptions
getAnsOption(X,Y) Core plugin ExpressionAnswerOptions
getRelevance(X) returns the relevance equation for question X
getStartTime() returns the date corresponding to the system time when the interview was started
getType(X) returns the string name of the datatype - e.g. *NA* if isNA()
gotoFirst() jumps to the first relevant set of questions - this violates the normal flow of the system
gotoNext() jumps to the next set of relevant questions - this violates the normal flow of the system
gotoPrevious() jumps to the previous set of relevant questions - this violates the normal flow of the system
isAsked(X) returns true if the answer is neither *NA*, *INVALID*, nor *UNASKED*
isInvalid(X) returns true if the answer is of type *INVALID*
isNA(X) returns true if the answer is of type *NA*
isNotUnderstood(X) returns true if the answer if of type *HUH*
isRefused(X) returns true if the answer is of type *REFUSED*
isSpecial(X) returns true if the answer is of type *UNASKED*, *NA*, *REFUSED*, *INVALID*, *UNKNOWN*, or *HUH*
isUnknown(X) returns true if the answer is of type *UNKNOWN*
jumpTo(X) jump to the group containing the named question -- this violates the normal flow of the system
jumpToFirstUnasked() jump to the first unasked question thus bypassing previous answered questions this violates the normal flow of the system
lastIndexOf(X,Y) returns the last index (base 0) of string Y in string X. Returns -1 if Y is not contained within X
list(X,...) a string containing a comma separated list of the positive values with "and" separating the last two
mean(X,...) returns the mean of a list of values
numAnsOptions(X) returns the number of answer options that question X has
orlist(X,...) a string containing a comma separated list of the positive values, with "or" separting the last two
parseDate(X,PAT) returns the date value of string X parsed with Java date format pattern PAT
parseNumber(X,PAT) returns the numerical value of string X parsed with Java number format pattern PAT
showAllResponsesExcept( questionList,attributeList,attributeTitleList) questionList = pipe-delimited list of question identifiers; attributeList = pipe-delimited list of attributes (like question#, title, text, type - so you can decide what to show); attributeTitleList = pipe-delimited list of table headers, so can internationalize the report.
showTheseResponses( questionList,attributeList,attributeTitleList) questionList = pipe-delimited list of question identifiers; attributeList = pipe-delimited list of attributes (like question#, title, text, type - so you can decide what to show); attributeTitleList = pipe-delimited list of table headers, so can internationalize the report.

Expression Manager Knows Which Variables are Local

In order to properly build the JavaScript for page, Expression Manager needs to know which variables are set on the page, and what their JavaScript ID is (e.g. for document.getElementById(x)).  It also must know which variables are set on other pages (so that it can ensure that the needed <input type='hidden' value='x'> fields are present and populated).

Cascading Conditions

If any of the variables are irrelevant, the whole equation will be irrelevant (false).  For example, in the following table, N/A means that one of the variables was not relevant

Operator Example a b Result
+ (unary) +a N/A false
! !a N/A false
== (or eq) a == b N/A 5 false
== (or eq) a == b N/A 0 false
== (or eq) a == b N/A N/A false
!= (or ne) a != b N/A 5 false
!= (or ne) a != b N/A N/A false
!= (or ne) a != b N/A 0 false
> (or gt) a > b N/A 5 false
>= (or ge) a >= b N/A 5 false
< (or lt) a < b N/A 5 false
<= (or le) a <= b N/A 5 false
and a and b N/A 5 false
and a and b N/A N/A false
or a or b N/A N/A false
or a or b N/A 5 false
+ a + b N/A 5 false
* a * b N/A 5 false
/ a / b 5 N/A false
() (a) N/A false
(exp) (a && b) N/A 5 false
(exp) op (exp) (b + b) > (a && b) N/A 5 false
function sum(a,b,b) N/A 5 false
function max(a,b) N/A 5 false
function min(a,b) N/A 5 false
function implode(', ',a,b,a,b) N/A 5 false
function if(a,a,b) N/A 5 false
function is_empty(a) N/A false
function is_empty(a) 0 (or blank) true
function !is_empty(a) N/A false

Overriding Cascading Conditions

Say you want to show a running total of all relevant answers.  You might try to use the equation {sum(q1,q2,q3,...,qN)}.  However, this gets translated internally to LEMif(LEManyNA('q1','q2','q3',...,'qN'),,sum(LEMval('q1'),LEMval('q2'),LEMval('q3'),...,LEMval('qN'))).  So, if any of the values q1-qN are irrelevant, the equation will always return false.  In this case, the sum() will show 0 until all questions are answered.

To get around this, each variable can have a ".NAOK" suffix (meaning that Not Applicable is OK) added to it.  In such cases, the following behavior occurs.  Say you have a variable q1.NAOK

  1. q1 is not added to the LEManyNA() clause
  2. LEMval('q1') will  continue to check whether the response is relevant, and will return '' if it is not (so individual irrelevant responses will be ignored, but they will not void the entire expression).

So, the solution to the running total problem is to use the equation sum(q1.NAOK,q2.NAOK,q3.NAOK,...,qN.NAOK).

The use of the .NAOK suffix also lets authors design surveys that have several possible paths but then converge on common paths later.  For example, say subjects answer a survey in a way that is outside the normal range of responses.  The author could alert the subjects that they may not get valid results, and ask them whether they really want to  continue with the survey.  If they say Yes, then the rest of the questions will be shown.  The condition for the "rest of the questions" would check whether the initial responses were answered within the normal range OR whether the subject said Yes to the question that is only relevant if they answered outside the normal range.

How does Expression Manager Support Conditional Micro-Tailoring?

Here is an example of micro-tailoring (where Question Type=='expr' means an Equation):

Question Code Relevance Question Type Question
name 1 text What is your name?
age 1 text How old are you?
badage !is_empty(age) expr {(age<16) or (age>80)}
agestop badage message Sorry, {name}, you are too {if( (age<16),'young',if( (age>80),'old','middle-aged') ) } for this test.
kids !badage yesno Do you have children?
parents 1 expr {!badage && kids=='Y'}
numKids parents text How many children do you have?
kid1 parents && numKids >= 1 text How old is your first child?
kid2 parents && numKids >= 2 text How old is your second child?
kid3 parents && numKids >= 3 text How old is your third child?
kid4 parents && numKids >= 4 text How old is your fourth child?
kid5 parents && numKids >= 5 text How old is your fifth child?
sumage 1 expr {sum(kid1.NAOK,kid2.NAOK,kid3.NAOK,kid4.NAOK,kid5.NAOK)}
report parents yesno {name}, you said you are {age} and that you have {numKids}.  The sum of ages of your first {min(numKids,5)} kids is {sumage}

All of these questions can be on a single page (e.g. in the same group), and only the relevant questions will display.  Moreover, as you enter the ages of children, the sum() expression in the last question will dynamically update on the page.

Expression Manager provides this functionality by surrounding each expression with a named <span> element.  Every time a value changes, it recomputes the expression that should appear in that <span> element and regenerates the display.  You can have dozens, or even hundreds, of such tailored expressions on the same page, and the page will re-display all of them in a single screen refresh.

Mapping of LimeSurvey 1.91+ to Expression Manager Functionality

Old Feature New Feature Comments
Conditions Relevance You can use very complex conditional equations, and access a broader range of variables
Assessments Equation Any assessment scores can be re-structured into an Equation. This both ensures that the score is written to the database, and also lets you see dynamic changes to the score value on the current page
Replacements Expression Manager The core engine takes the input string and treats everything within curly braces as an Expression - so it handles all historical replacements types.  To avoid messing up embedded JavaScript, Expression Manager only processes content between curly braces as long as (a)  there is no leading or trailing whitespace within the curly braces - e.g. {expr} is an expression, but { expr}, {expr }, and { expr } are not expressions.  Furthermore, Expression Manager does not process content within its own strings (e.g. {list('hi','there {braces}')} generates "hi there {braces}").  It also ignores escaped curly braces (e.g. \{this is not an expression\})
Validation Expression Manager The plan is to take the current min/max Question Attributes and have Expression Manager process them.  That way the min/max values can be expressions themselves

Syntax Highlighting

To help with entering and validating expressions, EM provides syntax highlighting with the following features:

Types and Meanings of Syntax Highlighting

Color Sample Meaning Tooltip Comments
tan background Sample the whole equation none Anything within curly braces that is recognized as an equation (e.g. there is no leading or trailing whitepace) will be color-coded with a tan background to help distinguish it from surrounding text
bold red text Sample An error Some explanation on error Can be an unknow variable or an error in function, .... Survey can be totally broken, this don't show to public user.
blue text Sample function name meaning and allowable syntax function names, or things that should be functions since they are followed by an opening parenthesis, are presented in bold blue text. Tooltips show the meaning and allowable syntax for the function.
grey text Sample string none single and double-quoted strings are shown in grey text
cyan text Sample variable set on the same page, [name or SGQA code]: question; value; answerList showing codes for each value Any variable that is set on the same page to the current question is shown in cyan text, showning it can be updated in javascript. The tooltip shows its name (if you used INSERTANS:xxx) or SGQA code (if you used the new naming system), the actual question, and its current value (or blank if not set). If the question type expects responses from an enumerated value set, the mapping of the codes to display values is show.
green text Sample variable set on a prior page [name or SGQA code]: question; value; answerList showing codes for each value Any variable that is set on a prior page is shown in bold green text. The tooltip shows its name (if you used INSERTANS:xxx) or SGQA code (if you used the new naming system), the actual question, and its current value (or blank if not set). If the question type expects responses from an enumerated value set, the mapping of the codes to display values is show.
bold pink text Sample variable set on a later page in general : empty at survey start, but can be filled with index or move previous [name or SGQA code]: question; value; answerList showing codes for each value Any variable that is set on a next page is shown in bold pink text. The tooltip shows its name (if you used INSERTANS:xxx) or SGQA code (if you used the new naming system), the actual question, and its current value (or blank if not set). If the question type expects responses from an enumerated value set, the mapping of the codes to display values is show.
bold tan text Sample a lime replacement value the value Lime Replacement Strings (like {TOKEN:xxx}, {PRIVACY_MESSAGE}) are shown in bold tan text.
red text Sample assignment operator (=) warning message If you use one of the assignment operator (=) that operator will be displayed in red text. This is meant to help prevent accidental re-assignment of values when you really meant to check whether a == b instead of setting the value of a = b.
normal black text Sample punctuation none All other punctuation within the expression is shown as normal black text.
red-boxed text a bold red line surrounds the error syntax error description of the error Any detected syntax errors are shown by surrounding the error with a red box. The tooltip shows the error. Examples include unmatched parentheses, use of undefined functions, passing the wrong number of arguments to functions, poorly structured expressions (e.g. missing operators between variables), trying to assign a new value to a read-only variable, trying to assign values to non-variables, or using unsupported syntax. Note that the syntax error dectection system may only report one error in an expression even if there are multiple errors; however, if any errors are detected, at least one error will be shown.

Additional Reading

Expression Manager sample surveys

Use Cases and HowTos

Step-by-Step examples

Reference for Developers

RoadMap/Status/ToDo List