Actions

ExpressionScript How-to

From LimeSurvey Manual

Revision as of 10:20, 13 September 2018 by Bravehorse (talk | contribs) (Created page with "==実行時に評価値を計算し、その結果をアンケートデータに格納する==")


はじめに

LimeSurveyでは、新しいExpression Manager(EM)モジュールを使用して、より複雑な分岐、評価、検証、およびカスタマイズがサポートされています。LimeSurveyがサーバー内で行う置換、条件評価の管理方法を置き換えることができます。また、ランタイムデータベースの読み込みのほとんどが不要になるため、処理速度が大幅に向上します。


主な定義

  1. : 中括弧で囲まれたもの
    • 開く中括弧の直後または閉じる中括弧の直前に空白がない
    • 式の内容はEMが評価するため、数式、関数、複雑な文字列と日付処理を含めることができます。
  2. テーラリング: "パイピング"とも呼ばれますが、これは条件付きでテキストを変更するプロセスです。
    • すべての'置換フィールド'、参加者データ、回答データにアクセスできます。
    • 質問、回答、およびそのプロパティにも簡単にアクセスできます。
  3. 出現条件式: 質問を表示するかを制御する新しい質問属性
    • 出現条件式がある場合、その出現条件が真と評価された場合にのみ質問が表示されます。
    • 内部では、すべてのarray_filterコマンドとarray_filter_excludeコマンドがサブ質問レベルの出現条件になります。
  4. SGQA:  LimeSurvey 1.91以前の変数の命名方法です。
    • アンケート(Survey)-グループ(Group)-質問(Question)-回答(Answer)の略です。
    • SGQA変数名は123X5X382X971のようなもので、サブ質問の接尾辞がつくことがあります。
    • これらの変数名は、基礎となるS/Q/G/Aデータベースコードに固有のものであるため、しばしば変更する必要があります。
  5. 質問タイプ: データベースに計算やレポートを保存する新しい質問タイプ
    • これはテキストを表示する質問のようなものですが、"この質問をいつも隠す"の設定をしても、その内容はデータベースに保存されます。
  6. 質問コード: EMで使用することが望まれる変数
    • これは質問の目的を示すわかりやすい名前で、複雑なロジックを読みやすくします。
    • 有効な質問コードとして数字で始まるものは使用できないので、質問コードを使用して質問の番号を付けるときは、単に「q1」または「q1a」または「g1q2」を使用してください。
    • これはSPSSまたはRにデータをエクスポートすると変数名になります。したがって、統計分析を行う場合は、固有の質問コードのみを作成する必要があります。


構文ハイライト

式の入力と検証を支援するために、EMでは以下のような構文強調表示機能を提供しています。


構文ハイライトの種類と意味

サンプル 意味 ツールチップ コメント
黄褐色の背景 サンプル 式全体 なし 式として認識される中括弧内のもの(先頭または末尾の空白がない)は、周囲のテキストと区別するのに役立つ黄褐色の背景で色分けされます。
太字青色のテキスト サンプル 関数名 関数の意味と構文 関数名、または開く括弧が続くので関数と思われるものは、太字の青いテキストで表示されます。ツールチップには、その機能の意味と許容される構文が表示されます。
灰色のテキスト 'サンプル' 文字列 なし シングルもしくはダブルクォートで囲まれた文字列が灰色のテキストとして表示されます。
太字栗色のテキスト サンプル 同じページの後続の質問にセットされた変数 [名前またはSGQAコード]: 質問; 値; それぞれの値のコードが示された回答リスト 同じページの後続の質問にセットされた変数は太字栗色のテキストで表示されます。この色付き表示は、質問の順序にかかわるエラーの可能性を作成者に警告するものですが、動的レポートを作成するページなど、こうした変数の使い方を必要とする場合があるので許容されています。ツールチップには、名前(INSERTANS:xxxを使用した場合)またはSGQAコード(新しい命名システムを使用した場合)、実際の質問、および現在の値(設定されていない場合は空欄)が表示されます。列挙された値セットからの選択を期待する質問タイプの場合、コードの表示値へのマッピングが表示されます。
太字水色のテキスト サンプル 同じページの先行する質問にセットされた変数 [名前またはSGQAコード]: 質問; 値; それぞれの値のコードが示された回答リスト 同じページの先行する質問にセットされた変数は太字水色のテキストで表示されます。ツールチップには、名前(INSERTANS:xxxを使用した場合)またはSGQAコード(新しい命名システムを使用した場合)、実際の質問、および現在の値(設定されていない場合は空欄)が表示されます。列挙された値セットからの選択を期待する質問タイプの場合、コードの表示値へのマッピングが表示されます。
太字緑色のテキスト サンプル 先行するページでセットされた変数 [名前またはSGQAコード]: 質問; 値; それぞれの値のコードが示された回答リスト 先行するページでセットされた変数は太字緑色のテキストで表示されます。ツールチップには、名前(INSERTANS:xxxを使用した場合)またはSGQAコード(新しい命名システムを使用した場合)、実際の質問、および現在の値(設定されていない場合は空欄)が表示されます。列挙された値セットからの選択を期待する質問タイプの場合、コードの表示値へのマッピングが表示されます。
太字桃色のテキスト サンプル 後続のページでセットされた変数 [名前またはSGQAコード]: 質問; 値; それぞれの値のコードが示された回答リスト 後続のページでセットされた変数は太字桃色のテキストで表示されます。変数が宣言される前に使用された場合のエラーです。ツールチップには、名前(INSERTANS:xxxを使用した場合)またはSGQAコード(新しい命名システムを使用した場合)、実際の質問、および現在の値(設定されていない場合は空欄)が表示されます。列挙された値セットからの選択を期待する質問タイプの場合、コードの表示値へのマッピングが表示されます。
太字の黄褐色のテキスト サンプル LimeSurveyの置換値 LimeSurveyの置換文字列({TOKEN:xxx}、{PRIVACY_MESSAGE}など)は太字の黄褐色のテキストとして表示されます。 ツールチップには現在の値が表示されます。
赤色のテキスト サンプル 代入演算子 注意喚起メッセージ 代入演算子(=,+=,-=,*=,/=)のいずれかを使用すると、代入演算子が赤色のテキストで表示されます。これは、aとbは等しいことを確認しようとしているとき、誤ってbの値をaに代入するようなことを防ぐのに役立ちます。
通常の黒色のテキスト サンプル 句読点 なし 式の内の他の句読点はすべて、通常の黒文字で表示されます。
赤枠で囲まれたテキスト サンプル 構文エラー エラーの説明 検出された構文エラーは、エラーを赤い枠線で囲んで表示されます。ツールチップにエラーが表示されます。例としては、括弧の不一致、未定義関数の使用、関数に渡す引数の数の誤り、構造化が不十分な式(変数間の演算子の欠落など)、読み取り専用変数に値を代入しようとする、変数でないものに値を代入しようとする、サポートされていない構文を使用するなどです。構文エラー検出システムは、複数のエラーがあっても式内の1つのエラーだけを報告することがあります。ただし、エラーが検出された場合は、少なくとも1つのエラーが表示されます。
 Hint: To be used in javascript, url etc .... a variable must be static in the page. Then the expression must be contain only variable in other page (Green variable)


The following screenshots give examples,  but do not show the values of the tooltips.  If you install the demo and hover the mouse over any of bold colored words, you will see an informative tooltip.

Note, because of this syntax highlighting, it is very easy to compose correct expressions, even ones that are complicated.  Although the LimeSurvey team plans to try to build an Expression Builder GUI, you can use the existing syntax-highlighting to quickly identify and fix typos.  You can also use the tool-tips to validate the accuracy of your expressions (e.g. confirm you have selected the desired variable(s).

In each of the examples, there are three columns:

  1. Source - this is the raw text that you would enter into the LimeSurvey Question field
  2. Pretty Print - this is the syntax-highlighted equivalent of what you entered
    • Note that Expressions are shown with a tan background, but not surrounded by curly braces in this highlighting.
    • Since EM supports recursive substitution, showing curly braces in the highlighting would cause syntax errors
  3. Result - this is the output generated when EM processes the source
    • Everything that can be properly substituted is
    • Expressions with errors are shown in-line, with syntax highlighting.  Errors are surrounded by a red-lined box.

適切な構文

Here are examples of proper syntax:

  1. Values: shows that known variables are color coded according to whether are set on the current page.  Old-style INSERTANS:xxxx gets its own color-coding style
  2. Question Attributes: shows that dot notation can access some properties of questions
  3. Math: shows that basic and complex calculations are supported
  4. TextProcessing: shows some of the available text-processing functions
  5. Dates: shows two of the available date-related functions
  6. Conditional: shows use of if() function to choose between two choices.  These can be nested.
  7. Tailored Paragraph: Shows a more typical example.  You can completely customize a report based upon prior values
  8. EM processes within strings:  Shows that it can do substitutions within strings.  This example generates a tailored image name.
  9. EM doesn't process curly braces like these:  Shows that if the curly braces are escaped, or there is white space between the expression and the curly braces, EM ignores it.

**This is critical for embedding custom JavaScript.

エラーを含むEM構文

Here are examples of common errors when typing EM expressions.  Note that the tooltips provide additional information.

  1. Inline Javascript that forgot to add spaces after curly brace
    • Since "document.write" appears right after a curly brace, EM thinks it is an expression, and red-boxes "document" and "write" since they are undefined variable and functions, respectively
  2. Unknown/Misspelledd Variables, Functions and Operators
    • Here we forgot that we are using the variable name "gender" instead of "sex", but EM catches that error.  It also red-boxes '++', since that is not a supported operator.
  3. Warns if use = instead of eq, or perform value assignments
    • Note that the '=' and '+=' are in red text instead of black.  If you hover the mouse over them, you will see warnings that you are assigning a value.
  4. Wrong number of arguments for functions
    • if() takes 3 arguments, but has been given 4, so hovering over the red-boxed "if" will explain the error and show the supported syntax
    • sum() takes an unlimited number of arguments, but we had a trailing comma before the closing parentheses, so that is red-boxed
  5. Mismatched parentheses
    • This is one of the most common errors when writing expressions.
    • This shows two examples of missing closing parentheses, and one example of having one too many closing parentheses.
  6. Unsuported syntax
    • If you use an operator or punctuation that EM does not support, it will red-box it.
  7. Invalid assignments
    • Some variables are readWrite and can have their values changed. Others are read-only
    • If you try to change the value of a read-only variable, you can't.  EM will red-box the attempt.
    • If you try to assign a value to an equation or a string, you will also get an error


"Live" examples of Syntax Highlighting with active tooltips

SourcePretty PrintResult
Here is an example of OK syntax with tooltips
Hello {if(gender=='M','Mr.','Mrs.')} {surname}, it is now {date('g:i a',time())}. Do you know where your {sum(numPets,numKids)} chidren and pets are?
Here is an example of OK syntax with tooltips
Hello if(gender == 'M','Mr.','Mrs.') surname, it is now date('g:i a',time()). Do you know where your sum(numPets,numKids) chidren and pets are?
Here is an example of OK syntax with tooltips
Hello Mr. Smith, it is now 6:07 am. Do you know where your 3 chidren and pets are?
Here are common errors so you can see the tooltips
Variables used before they are declared: {notSetYet}
Unknown Function: {iff(numPets>numKids,1,2)}
Unknown Variable: {sum(age,num_pets,numKids)}
Wrong # parameters: {sprintf()},{if(1,2)},{date()}
Assign read-only-vars:{TOKEN:ATTRIBUTE_1+=10},{name='Sally'}
Unbalanced parentheses: {pow(3,4},{(pow(3,4)},{pow(3,4))}
Here are common errors so you can see the tooltips
Variables used before they are declared: notSetYet
Unknown Function: iff(numPets > numKids,1,2)
Unknown Variable: sum(age,num_pets,numKids)
Wrong # parameters: sprintf(),if(1,2),date()
Assign read-only-vars:TOKEN:ATTRIBUTE_1+=10,name='Sally'
Unbalanced parentheses: pow(3,4,(pow(3,4),pow(3,4))
Here are common errors so you can see the tooltips
Variables used before they are declared: notSetYet
Unknown Function: iff(numPets > numKids,1,2)
Unknown Variable: sum(age,num_pets,numKids)
Wrong # parameters: sprintf(),if(1,2),date()
Assign read-only-vars:TOKEN:ATTRIBUTE_1+=10,name='Sally'
Unbalanced parentheses: pow(3,4,(pow(3,4),pow(3,4))
Here is some of the unsupported syntax
No support for '++', '--', '%',';': {min(++age, --age,age % 2);}
Nor '|', '&', '^': {(sum(2 | 3,3 & 4,5 ^ 6)}}
Nor arrays: {name[2], name['mine']}
Here is some of the unsupported syntax
No support for '++', '--', '%',';': min( ++ age, -- age,age % 2) ;
Nor '|', '&', '^': (sum(2 | 3,3 & 4,5 ^ 6)}
Nor arrays: name [ 2 ] ,name [ 'mine' ]
Here is some of the unsupported syntax
No support for '++', '--', '%',';': min( ++ age, -- age,age % 2) ;
Nor '|', '&', '^': (sum(2 | 3,3 & 4,5 ^ 6)}
Nor arrays: name [ 2 ] ,name [ 'mine' ]

テーラリングの例({INSERTANS:xxx}の拡張)

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

'Mr.'か'Mrs.'を使い分けるにはif()関数を使用します。

構文は、if(test,do_if_true,do_if_false)です。

# コード 質問 タイプ
1 gender 性別は? 性別
2 example1 Dear {if(gender=='M','Mr.','Mrs.')} Smith, ... テキスト表示

使用ビュー:

案内メールにおける"Dear {Mr}/{Mrs} Smith..."

トークンテーブルの属性を使用して、上記の例を案内メールに使用できます。電子メールの中で'Mr.'または'Mrs.'を使い分けるにはif()関数を使用します。

構文は、if(test,do_if_true,do_if_false)です。

# 属性

案内メールのテキスト:

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

あなたはアンケートに招待されました。

http:/...

電子メールビュー:

計算 / 評価の例

実行時に評価値を計算し、その結果をアンケートデータに格納する

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

It also shows that all of these 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

Here are screen shots 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 substitions within a Question.  However, you can also put substitutions within Help, Group header display, the Welcome message, and the End message.

For this question, since the relevance is {numKids >= 2), it will only be visible if the respondant reports that they have at least two children.

Note that this question uses the new Equation type, and that despite being "Always hidden", the result will be computed and stored to the database.

Also note that is uses the .NAOK suffix for each variable.  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 they had 4 children (e.g. if all of the variables are relevant).  By using .NAOK, that 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 person initially says they have 3 children, and enters ages for each, then changes their mind and says they have 2, we don't want to see the sum of the 3 entered values - see below for an example of this.

Each separate Expression is color coded with a tan background.  As you can see, 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 screen shots 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, is says, "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 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, and the display instantly changes 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.

Note, if I were to change the number of kids back to 3, I would see the value of 5.5 I entered, 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 come back, then say  that I had 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 uses two of EM's features:  Relevance and Tailoring.

Rather than summarizing the questions as a table, the actual LimeSurvey group file is attached so you can try it yourself.

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 rest of the questions appear.

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

Here is the bottom of the page, which shows that you can either use {INSERTANS:xxxx} or the newer naming system interchangeably.

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.  Here is an example:

Here is the group file for these examples:

limesurvey_group_33.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:

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

Here is the logic file for the group.  As you can see in the iftest 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 three closing parentheses after "already an adult!", but there are only two.

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, it looks like this:

In the future, we hope to have to ability to dynamically syntax-highlight these equations while you are editing them. Most programming  editors, for example, will highlight the matching parentheses or curly braces.  For now, however, you just have to count opening and closing if parentheses (the same way you might in Excel), save your best guess, and check the syntax highlighting for errors.