JavaScript field: Difference between revisions

m
no edit summary
mNo edit summary
mNo edit summary
Line 68: Line 68:


== 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>


Line 109: Line 98:
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>
</source>


Line 177: Line 166:


result;                            // The result is the MAXIMUM
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 cost = 0;
var items = field('Items');
for (var i in items)
    cost += items[i].field('Quantity') * items[i].field('Price');
</source>
</source>