JavaScript field: Difference between revisions

From Memento Database Wiki
Jump to navigation Jump to search
No edit summary
 
(39 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{Stamp|2016-08-30|3.9.7|1.0.3}}
{{Stamp|2023-08-12|5.0|2.0}}
The value of the field will depend on the result of execution of the script preset in the settings of the field and executed in the entry context.
{{BannerMenu}}
{{PageTitle|JavaScript field}}
 
The value of the field will be the result of execution of the script defined in the field and executed in the entry context.


'''[https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7 JavaScript 1.7]''' is used for scripts. The current version supports only core methods of the language.
'''[https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7 JavaScript 1.7]''' is used for scripts. The current version supports only core methods of the language.


A script may consist of multiple operations but only the result of the last operation will be entered into the field. Example:
A script may consist of multiple operations, but only the result of the last operation will be entered into the field. For example:
<source lang="javascript">
<source lang="javascript">
var i = 1 + 1
var i = 1 + 1 // Result would be 2, if this were the final statement,
i + 1
i + 1         //  but instead, this is the final statement, so the result will be 3
Result will be: 3
</source>
</source>
{{FieldNameHint}}
== Script ==
; Script itself
: JavaScript script. The context of the script is the [[Triggers#Object Entry|'''Entry object''']]. The value returned is the last value assigned or expressed.
; JavaScript Libraries
: Choose additional JavaScript Libraries to be loaded. At this time, only moment.min.js is available.
; Execute script in real time:
:; No (default)
:: Script will run only upon edit. Performance will be enhanced.
:; Yes
:: Script will run upon edit or display.
== Display Options ==
{{FieldRoleRNDS}}
{{FieldOnCard}}
{{FieldFont}}
{{FieldDepend}}


== Fields of an entry ==
== Fields of an entry ==
Function '''''field("[field name]")''''' is used to get access to the values of other entry fields.
Function [[Triggers#field(name)|'''''field("fieldName")''''']] is used to get access to the values of entry fields.
The type of the JavaScript object returned by the function depends on the field type.
The type of the JavaScript object returned by the function depends on the field type.


Compatibility of Memento field types and JavaScript objects is shown in the table:
Compatibility of Memento field types and JavaScript objects is shown in the table:
{| class="wikitable"
{{FieldTypeReturnValues}}
|-
! Field type !! JavaScript object
|-
| Text , Hyperlink, Password, Phone, Email, Calculation (string result) , Single-choice list , Radio buttons || [https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String '''String''']
|-
| Integer, Real number, Rating, Currency, Calculation (number result) || [https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number '''Number''']
|-
| Date , Date/Time, Time || [https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date '''Date''']
|-
| Boolean || [https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean '''Boolean''']
|-
| Multiple-choice list, Checkboxes || [https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array '''Array of String''']
|-
| Link to entry || Array of entries. Each array element has method field for access to values of linked entry.
|}


== Time of script execution ==
== Time of script execution ==
A script can be executed both when an entry is created or changed and when it is displayed.<br />
A script can be executed both when an entry is created or changed and when it is displayed.
 
The time of script execution is set by the toggle button ''Execute script real time'' on the field edit screen.
The time of script execution is set by the toggle button ''Execute script real time'' on the field edit screen.
It is reasonable to enable this option if your script contains functions that depend on the current time. Online execution in case of a large number of entries can significantly increase the time required to open the library.
It is reasonable to enable this option if your script contains functions that depend on the current time.
Online execution in case of a large number of entries can significantly increase the time required to open the library.


== Functions to work with the date ==
== Functions to work with the date ==
You can enable integrated library [http://momentjs.com/ '''moment.js'''] to work with the date and time. Click '''''JavaScript Libraries''''' and choose '''''moment.min.js'''''.
You can enable the integrated library [http://momentjs.com/ '''moment.js'''] to work with the date and time. Click '''''JavaScript Libraries''''' and choose '''''moment.min.js'''''.


Some examples. If record contains the data field whose value is 18 March 2016 14:55
Some examples. If an entry contains the field Date whose value is 18 March 2016 14:55


Example of Format dates
'''Example of date formats'''
<source lang="javascript">
<source lang="javascript">
moment(field('Date')).format('MMMMM Do YYYYY') //March 18th 2016
moment(field('Date')).format('MMMMM Do YYYYY')     // March 18th 2016
moment(field('Date')).format('dddd') //Friday
moment(field('Date')).format('dddd')               // Friday
moment(field('Date')).format('dddd [Escaped] YYYY') //Friday Escaped 2016
moment(field('Date')).format('dddd [Escaped] YYYY') // Friday Escaped 2016
moment(field('Date')).format('HH:mm') //14:55
moment(field('Date')).format('HH:mm')               // 14:55
</source>
</source>


Example of Relative Time
'''Example of relative time'''
<source lang="javascript">
<source lang="javascript">
moment(field('Date')).fromNow() //11 minutes ago
moment(field('Date')).fromNow()                     // 11 minutes ago
moment(field('Date')).startOf('day').fromNow() //15 hours ago
moment(field('Date')).startOf('day').fromNow()     // 15 hours ago
</source>
</source>


Example of Calendar Time
'''Example of calendar time'''
<source lang="javascript">
<source lang="javascript">
moment(field('Date')).calendar() //Today at 2:55 PM
moment(field('Date')).calendar()                   // Today at 2:55 PM
moment(field('Date')).add(1 , 'days').calendar() //Tomorrow at 2:55 PM
moment(field('Date')).add(1 , 'days').calendar()   // Tomorrow at 2:55 PM
</source>
</source>


More information about library features on '''http://momentjs.com'''
More information about library features on '''[http://momentjs.com]'''


== Examples ==
== Examples ==
==== Example: Sum ====
==== Example: Product ====
Entries contain fields: Price, Count.
The library contains the fields Price and Count.
We add a JavaScript field "Sum" by using the following script:
The JavaScript field '''Total price''' can be computed as follows:
<source lang="javascript">
<source lang="javascript">
field('Price')*field('Count')
field('Price')*field('Count');
</source>
</source>


==== Example: Percentage ====
==== Example: Percentage ====
Entries contain fields: Count, Total.
The library contains the fields Count and Total.
We add a JavaScript field "Percentage" by using the following script:
The JavaScript field '''Percentage''' can be computed as follows:
<source lang="javascript">
<source lang="javascript">
var total = field('Total')
var total = field('Total');
if (total > 0)
if (total > 0)
   field('Count')*100/total + ' %'
   field('Count')*100/total + ' %';
else
else
   'none'
   'None';
</source>
</source>


==== Example: Days ====
==== Example: Days ====
Entries contain fields: StartDateTime, EndDateTime.
The library contains DateTime (or Time) fields Start and End.
We add a calculating field "Days" by using the following script:
The JavaScript field '''Days''' can be computed as follows:
<source lang="javascript">
<source lang="javascript">
moment(field('End')).diff(field('Start') , 'days')
moment(field('End')).diff(field('Start') , 'days');
</source>
 
==== Example: References ====
There’s library Order – with orders and library Item – with items. Library Order contains a link to library Item. Library Item contains field Price.
To calculate the cost of the order, let’s add script field Sum using the following script:
<source lang="javascript">
var sum = 0
var items = field('Item')
for(var i in items) {
  sum = sum + items[i].field('Price')
}
</source>
</source>


==== Example: Birthday====
==== Example: Birthday====
We have birthday field. If a person younger than 18 years we want displaying string "youth", else "adult".
We have a birthday field. If a person is younger than 18 years old, we want to display the string "youth", otherwise the string "adult".
<source lang="javascript">
<source lang="javascript">
var years = moment().diff(field('Birthday') , 'years' )
var years = moment().diff(field('Birthday') , 'years' )
if (years < 18)
if (years < 18)
   'Youth'
   'Youth';
else
else
   'Adult'
   'Adult';
</source>
 
=== Examples of calculations on linked entries ===
If you have a many-to-many Link To Entry field &mdash; linking the current entry to zero or more entries in another library &mdash; and if you have an amount field in that other library, you may want to perform calculations on that field across those entries, in similar fashion to Memento aggregation functions.
 
==== Example: Sum of linked amounts ====
<source lang="javascript">
var amountField = "Amount";        // CHANGE Amount to your amount field name
var linkedEntries = field("Them"); // CHANGE Them to your link field name
var numLE = linkedEntries.length;  // The number of linked entries
 
// Loop through linked entries, creating the sum
for (var lex = 0, result = 0; lex < numLE; lex++)
    result += linkedEntries[lex].field(amountField);
 
result;                            // The result is the SUM
 
</source>
 
==== Example: Average of linked amounts ====
<source lang="javascript">
var amountField = "Amount";        // CHANGE Amount to your amount field name
var linkedEntries = field("Them"); // CHANGE Them to your link field name
var numLE = linkedEntries.length;  // The number of linked entries
 
// Loop through linked entries, creating the sum
for (var lex = 0, result = 0; lex < numLE; lex++)
    result += linkedEntries[lex].field(amountField);
 
if (numLE != 0)
    result / numLE;                // The result is the AVERAGE
</source>
 
==== Example: Minimum of linked amounts ====
<source lang="javascript">
var amountField = "Amount";        // CHANGE Amount to your amount field name
var linkedEntries = field("Them"); // CHANGE Them to your link field name
var numLE = linkedEntries.length;  // The number of linked entries
var temp;
 
// Loop through linked entries, finding the MINIMUM
for (var lex = 0, result = 0; lex < numLE; lex++) {
    temp = linkedEntries[lex].field(amountField);
    if (temp < result)
        result = temp;
    }
 
result;                            // The result is the MINIMUM
</source>
</source>


== References ==
==== Example: Maximum of linked amounts ====
You can find a full description of the language [https://developer.mozilla.org/docs/Web/JavaScript here].
<source lang="javascript">
The implementation is based on [https://www.mozilla.org/rhino/ Rhino library].
var amountField = "Amount";        // CHANGE Amount to your amount field name
var linkedEntries = field("Them"); // CHANGE Them to your link field name
var numLE = linkedEntries.length;  // The number of linked entries
var temp;
 
// Loop through linked entries, finding the MAXIMUM
for (var lex = 0, result = 0; lex < numLE; lex++) {
    temp = linkedEntries[lex].field(amountField);
    if (temp > result)
        result = temp;
    }
 
result;                            // The result is the MAXIMUM
</source>
 
==== Example: Order containing items ====
The library Orders contains orders and the library Items contains items. Orders contains a link Items to library Items. Items contains the fields Quantity and Price.
To calculate the cost of the order, the JavaScript field '''Cost''' can be computed as follows:
<source lang="javascript">
var items = field('Items');        // CHANGE Items to your link field name
var cost = 0;
for (var i in items)
    cost += items[i].field('Quantity') * items[i].field('Price');


{{FieldNameHint}}
cost;                              // The result is the COMPUTED COST
</source>


== Script ==
==== Example: Controlling entry color ====
The color of an entry in the Entries List screen can be controlled using a JavaScript field. The JavaScript field merely returns a color string in the form "#RRGGBB", where RR is the hexadecimal (hex) value of the red component of the color, GG the hex value for the green component, and BB the hex value of the blue component. The user must identify the JavaScript field by editing the library and selecting the field for the Entry color parameter on the MAIN tab.


; Script itself
You could have many entries with distinct colors indicating things like regions, categories, ranges, etc.
: JavaScript script. Value returned is the last value assigned or the value in a Return statement.


; JavaScript Libraries
For example, suppose you have an numeric field and want to color entries red if the field is negative and green if it is positive. Here's how you would do it...
: Choose additional JavaScript Libraries to be loaded. At this time, only moment.min.js is available.


; Execute script in real time:
Create a JavaScript field, called anything, say "Color of entry". Maybe you have a Currency field called "Amount". You can set the script to be something like...
:; No (default)
:: Script will run only upon edit. Performance will be enhanced.
:; Yes
:: Script will run upon edit or display.


== Display Options ==
<source lang="JavaScript">
var amount = field("Amount");
if (amount < 0) "#FF0000";      // Red
else if (amount > 0) "#00FF00"; // Green
</source>


{{FieldRoleRNDS}}
Now, go to the MAIN tab of the Library Edit screen. Tap Entry color and select your new JavaScript field, Color of entry.


{{FieldOnCard}}
So, if your Amount field is negative, it will show in the entries list with a red bar on the left.
If it is positive, it'll show with a green bar on the left.
Otherwise it's zero, in which case it will have no bar on the left (barcolor dictated by the theme you're using -- white if you're using the light theme and black if using the dark theme).


{{FieldFont}}
== References ==
You can find a full description of the language [https://developer.mozilla.org/docs/Web/JavaScript '''here'''].
The implementation is based on the [https://www.mozilla.org/rhino/ '''Rhino library'''].


{{FieldDepend}}
== JavaScript links ==
{{Template:JavaScriptLinks}}


[[Category:Spec]]
[[Category:en]] [[Category:Spec]] [[Category:Sc]]

Latest revision as of 08:20, 23 August 2023

« Page as of 2023-08-12, editions Mobile 5.0, Desktop 2.0 »

Wiki
Home
About
Wiki | Memento
Getting started
Wiki | Memento
Indexes
Mobile | Desktop | Scripting
Support
Wiki | Memento
JavaScript field

The value of the field will be the result of execution of the script defined in the field and executed in the entry context.

JavaScript 1.7 is used for scripts. The current version supports only core methods of the language.

A script may consist of multiple operations, but only the result of the last operation will be entered into the field. For example:

var i = 1 + 1  // Result would be 2, if this were the final statement,
i + 1          //   but instead, this is the final statement, so the result will be 3
Name
Textual, case-insensitive field identifier that can include spaces; it's best to avoid characters that can be used as operators, though (standard across all field types)
Hint
Textual, case-insensitive field identifier that can include spaces

Script

Script itself
JavaScript script. The context of the script is the Entry object. The value returned is the last value assigned or expressed.
JavaScript Libraries
Choose additional JavaScript Libraries to be loaded. At this time, only moment.min.js is available.
Execute script in real time
No (default)
Script will run only upon edit. Performance will be enhanced.
Yes
Script will run upon edit or display.

Display Options

Display in the list as
Select among the following roles for the current field in the entries list:
  • As a Regular field
  • As an Entry Name
  • As an Entry Description
  • As an Entry Status
The field name
Display the name of the field in the card entry (By default, On). By this, it is meant that the field name will or will not be displayed on either the Entry View card or the Entry Edit card.
Font
Choices are:
  • Family: Regular, Light, Condensed, Thin, Medium. By default, Regular.
  • Style: Normal, Bold, Italic, Bold Italic. By default, Normal.
  • Size: By default, 18. Direct entry to change.
  • Color: By default, White. Palette of 20 colors, backed up by a continuously variable color chooser.
Dependencies
Ability to add one or more visibility dependencies upon fields with qualifying types.

Fields of an entry

Function field("fieldName") is used to get access to the values of entry fields. The type of the JavaScript object returned by the function depends on the field type.

Compatibility of Memento field types and JavaScript objects is shown in the table:

Field Type Return Values
Field type JavaScript object Examples
Text , Hyperlink, Password, Phone, Email, Barcode, Radio buttons, Single-choice list, Calculation (string result) String "abc"
Integer, Real number, Integer values, Rating, Currency, Calculation (number result) Number 42, 42.1
Date , DateTime, Time Date
Checkbox (Boolean) Boolean true, false
Checkboxes, Multiple-choice list Array of strings ["Shirts", "Pants", "Socks"]
Image Array of strings ["file:///storage/emulated/0/DCIM/image01.png", "file:///storage/emulated/0/DCIM/image02.png"]
Link to entry Array of entries
Each array element has a method field() for access to values of fields of entries of the linked library. Example:
field("localField")[i].field("remoteField")
[e1, e2, e3, ...]

Time of script execution

A script can be executed both when an entry is created or changed and when it is displayed.

The time of script execution is set by the toggle button Execute script real time on the field edit screen. It is reasonable to enable this option if your script contains functions that depend on the current time. Online execution in case of a large number of entries can significantly increase the time required to open the library.

Functions to work with the date

You can enable the integrated library moment.js to work with the date and time. Click JavaScript Libraries and choose moment.min.js.

Some examples. If an entry contains the field Date whose value is 18 March 2016 14:55

Example of date formats

moment(field('Date')).format('MMMMM Do YYYYY')      // March 18th 2016
moment(field('Date')).format('dddd')                // Friday
moment(field('Date')).format('dddd [Escaped] YYYY') // Friday Escaped 2016
moment(field('Date')).format('HH:mm')               // 14:55

Example of relative time

moment(field('Date')).fromNow()                     // 11 minutes ago
moment(field('Date')).startOf('day').fromNow()      // 15 hours ago

Example of calendar time

moment(field('Date')).calendar()                    // Today at 2:55 PM
moment(field('Date')).add(1 , 'days').calendar()    // Tomorrow at 2:55 PM

More information about library features on [1]

Examples

Example: Product

The library contains the fields Price and Count. The JavaScript field Total price can be computed as follows:

field('Price')*field('Count');

Example: Percentage

The library contains the fields Count and Total. The JavaScript field Percentage can be computed as follows:

var total = field('Total');
if (total > 0)
   field('Count')*100/total + ' %';
else
   'None';

Example: Days

The library contains DateTime (or Time) fields Start and End. The JavaScript field Days can be computed as follows:

moment(field('End')).diff(field('Start') , 'days');

Example: Birthday

We have a birthday field. If a person is younger than 18 years old, we want to display the string "youth", otherwise the string "adult".

var years = moment().diff(field('Birthday') , 'years' )
if (years < 18)
   'Youth';
else
   'Adult';

Examples of calculations on linked entries

If you have a many-to-many Link To Entry field — linking the current entry to zero or more entries in another library — and if you have an amount field in that other library, you may want to perform calculations on that field across those entries, in similar fashion to Memento aggregation functions.

Example: Sum of linked amounts

var amountField = "Amount";        // CHANGE Amount to your amount field name
var linkedEntries = field("Them"); // CHANGE Them to your link field name
var numLE = linkedEntries.length;  // The number of linked entries

// Loop through linked entries, creating the sum
for (var lex = 0, result = 0; lex < numLE; lex++)
    result += linkedEntries[lex].field(amountField);

result;                            // The result is the SUM

Example: Average of linked amounts

var amountField = "Amount";        // CHANGE Amount to your amount field name
var linkedEntries = field("Them"); // CHANGE Them to your link field name
var numLE = linkedEntries.length;  // The number of linked entries

// Loop through linked entries, creating the sum
for (var lex = 0, result = 0; lex < numLE; lex++)
    result += linkedEntries[lex].field(amountField);

if (numLE != 0)
    result / numLE;                // The result is the AVERAGE

Example: Minimum of linked amounts

var amountField = "Amount";        // CHANGE Amount to your amount field name
var linkedEntries = field("Them"); // CHANGE Them to your link field name
var numLE = linkedEntries.length;  // The number of linked entries
var temp;

// Loop through linked entries, finding the MINIMUM
for (var lex = 0, result = 0; lex < numLE; lex++) {
    temp = linkedEntries[lex].field(amountField);
    if (temp < result)
        result = temp;
    }

result;                            // The result is the MINIMUM

Example: Maximum of linked amounts

var amountField = "Amount";        // CHANGE Amount to your amount field name
var linkedEntries = field("Them"); // CHANGE Them to your link field name
var numLE = linkedEntries.length;  // The number of linked entries
var temp;

// Loop through linked entries, finding the MAXIMUM
for (var lex = 0, result = 0; lex < numLE; lex++) {
    temp = linkedEntries[lex].field(amountField);
    if (temp > result)
        result = temp;
    }

result;                            // The result is the MAXIMUM

Example: Order containing items

The library Orders contains orders and the library Items contains items. Orders contains a link Items to library Items. Items contains the fields Quantity and Price. To calculate the cost of the order, the JavaScript field Cost can be computed as follows:

var items = field('Items');        // CHANGE Items to your link field name
var cost = 0;
for (var i in items)
    cost += items[i].field('Quantity') * items[i].field('Price');

cost;                              // The result is the COMPUTED COST

Example: Controlling entry color

The color of an entry in the Entries List screen can be controlled using a JavaScript field. The JavaScript field merely returns a color string in the form "#RRGGBB", where RR is the hexadecimal (hex) value of the red component of the color, GG the hex value for the green component, and BB the hex value of the blue component. The user must identify the JavaScript field by editing the library and selecting the field for the Entry color parameter on the MAIN tab.

You could have many entries with distinct colors indicating things like regions, categories, ranges, etc.

For example, suppose you have an numeric field and want to color entries red if the field is negative and green if it is positive. Here's how you would do it...

Create a JavaScript field, called anything, say "Color of entry". Maybe you have a Currency field called "Amount". You can set the script to be something like...

var amount = field("Amount");
if (amount < 0) "#FF0000";      // Red
else if (amount > 0) "#00FF00"; // Green

Now, go to the MAIN tab of the Library Edit screen. Tap Entry color and select your new JavaScript field, Color of entry.

So, if your Amount field is negative, it will show in the entries list with a red bar on the left. If it is positive, it'll show with a green bar on the left. Otherwise it's zero, in which case it will have no bar on the left (barcolor dictated by the theme you're using -- white if you're using the light theme and black if using the dark theme).

References

You can find a full description of the language here. The implementation is based on the Rhino library.

JavaScript links

W3Schools
JavaScript Tutorial A pleasant, fairly complete, and useful tutorial on JavaScript
Best on a computer or tablet in landscape. On a phone or tablet in portrait, scroll to the bottom for navigation.
Mozilla Developer Network
JavaScript Guide Shows you how to use JavaScript, gives an overview of the language, and presents its capabilities & features
JavaScript Reference The entire JavaScript language described in detail
Introduction to JavaScript Introduces JavaScript and discusses some of its fundamental concepts
JavaScript Tutorial A re-introduction. JavaScript is often derided as being a toy, but beneath its simplicity, powerful language features await.
JavaScript 1.7 The JavaScript release upon which Memento is currently based
About JavaScript Jumping off point in learning about JavaScript