Triggers: Difference between revisions

Jump to navigation Jump to search
7,668 bytes removed ,  25 January 2017
m
no edit summary
mNo edit summary
mNo edit summary
Line 277: Line 277:


=== Libraries Examples ===
=== Libraries Examples ===
-----
See '''[[Trigger Examples#Libraries Examples]]'''.
==== Data Validation ====
Using scripts, you can check the correctness of input data and deny saving of data that fail the test. For example, perhaps a field integer values ​​are allowed only from 0 to 200.
 
:; Add a Create trigger: Set Event to '''Creating a new entry''', Phase to '''Before saving the entry'''. It will run synchronously.
:; Add an Update trigger: Set Event to '''Updating an entry''', Phase to '''Before saving the entry'''. It will run synchronously.
:'''Trigger script:'''
<source lang="javascript">
var num = entry().field("Number"); // Get value of field Number
if (num < 0 || num > 200) {        // Test for value matching allowable range
message("Wrong range");          // If value is outside range, display message
cancel();                        // Cancel the operation
}
</source>
 
:; Set default values: If default values cannot be set using the user interface, they can be set using a script.
<br/>
-----
===== Previous value of another field =====
Suppose there is a library containing daily mileage of daily walks or use of a car or bicycle. Suppose the library has a StartingMileage field and a Mileage field. When an entry is created, the field StartMileage must get data from the field Mileage in the previous entry.
 
:; Add a new trigger: Set Event to '''Creating an entry''' and Phase to '''Open the Entry Edit card'''. It will run synchronously.
 
:'''Trigger script:'''
<source lang="javascript">
var entries = lib().entries();                  // Get current library & array of its entries
if (entries.length > 0) {                        // Check that array is not empty;
                                                //  otherwise exit,
                                                //  since there is no previous entry.
prevMileage = entries[0].field("Mileage");      // The array is sorted newest to oldest,
                                                //  so newest entry in the array
                                                //  on top with index of 0.
entryDefault().set("StartMileage", prevMileage); // Set value of field Mileage
                                                //  from the previous entry
                                                //  as default value for field StartMileage.
}
</source>
<br/>
-----
 
===== Beginning of the next day =====
Suppose you need to identify the beginning of a new day in the DateTime field. (The script requires connection of the JavaScript library '''moment.js''' [http://momentjs.com/ moment.js].)
 
:; Add new trigger: Set Event to '''Creating an entry''' and Phase to '''Opening an Entry Edit card'''. It will run synchronously.
:'''Trigger script:'''
<source lang="javascript">
var m = moment().add(1,'d'); // Using the moment.js library function moment(),
                            //  get the current time, and add 1 day
m.hour(8).minute(0);        // Set the time to hour 8 and minute 0
entryDefault().set("Date",
    m.toDate().getTime());  // Use that as the default value for the field Date
</source>
<br/>
-----
 
===== New entry in one library triggers new entry in another =====
Suppose that after a new application for membership is validated, a new member should be created. We have libraries Applications & Members. After a new Applications entry is entered and before it is saved, we want to validate the application, and if it passes, we want to create a new entry in Members.
 
:; Fields: Library Applications has fields '''Date''', '''Name''', City, Years in city, Type.<br/> Library Members has fields '''Name''' & Type.
:; Set library permission: The Applications library must be permitted to access other libraries via ''libByName()''.<br/>Within Triggers, press the shield icon to view Permission settings.
:; Add new trigger: Add a new trigger to the Applications library.<br/>Set Event '''Creating a new entry''', Phase '''Before saving the entry'''.<br/>(A similar trigger could be set for Event '''Updating an entry''' Phase '''Before saving the entry''', but only if a change in a field value is to trigger the add of the new member.)
 
:'''Trigger script:'''
<source lang="javascript">
// Get the application entry that's being saved and call it e
//    (because you may use it a lot)
// With that, you can readily reference fields
//    in the new application entry about to be saved
 
var e = entry();
 
// If you have any checks on the values of fields the user entered,
//    you could do them here
// If any validations fail, call cancel() to forestall the save
// The user remains in the Entry Edit card
//    and will be advised the application does not pass criteria
 
if (e.field("Years in city") <== 2) {  // Sample field validation
    message("Application inadequate"); // You'll want more
    cancel(); // This will abort the save, but continue the script
}
 
else {      // Add a new member only if application is adequate
 
// From here on, the new application will be saved,
//    so we must also create the new member entry
 
// To create the new member, we need to reference Members
 
    var members = libByName("Members"); // This requires permission (see above)
 
// Start a new entry for Members
 
    var newMember = new Object();
 
// Set member fields from application data and add the new Members entry
 
    newMember["Name"] = e.field("Name");
    newMember["Type"] = e.field("Type");
    members.create(newMember);
}
</source>
<br/>
-----
<br/>
===== Ensuring unique non-Name field value =====
The goal is to ensure that a particular field value is unique within the library.
 
The ideal way to do this is to make the field the one and only Entry Name field and then set the Entry Name to be unique. Then, Memento will take care of ensuring this for you.
 
To do this, go in the Library Edit screen to the MAIN tab of the library and turn on the switch "The Entry Name is unique". Then go to the FIELDS tab and ensure that your field and only that field has the role Entry Name. Do that by editing the field, and under Display Options, you'll see "Display in the list as"; the choices will include Entry Name.
 
Now, if your library needs some other Entry Name, and you nevertheless want to ensure that a different field is unique within the library, then, yes, you'll need some code.
 
The best way, if you're just starting to enter entries into your library, is to make sure they're unique from the outset, so from the Entries List screen, pick Triggers from the menu. Press the + (plus) button to add a trigger, set the Event to "Creating a new entry" and the Phase to "Before saving the entry".
 
:; Fields: The field in the current library &mdash; that is to be unique among the entries of the library &mdash; is ''myField''.
:; Add new trigger: Add a new trigger to the library.<br/>Set Event '''Creating a new entry''', Phase '''Before saving the entry'''.<br/>(A similar trigger could be set for Event '''Updating an entry''' Phase '''Before saving the entry''' &mdash; for instance, if the library already has entries in which ''myField'' may not be unique.)
 
:'''Trigger script:'''
<source lang="javascript">
var myField = entry().field("myField");            // Value of myField
var entries = lib().entries();                    // Array containing all entries
 
var unique = true;                                // Presuming, initially
for (var ent = 0; ent < entries.length; ent++) {  // Loop through all entries
    if (entries[ent].field("myField") === myField) // If there is ever a match,
        unique = false;                            // Remember it
}
 
if (!unique) { // If not unique,
    cancel(); // Disallow the save
    message("myField is not unique. Try again.");  // Tell the user
}
</source>
<br/>
<br/>
-----
-----

Navigation menu