Triggers: Difference between revisions

Jump to navigation Jump to search
2,211 bytes added ,  20 November 2016
m
no edit summary
mNo edit summary
mNo edit summary
Line 360: Line 360:
     newMember["Type"] = e.field("Type");
     newMember["Type"] = e.field("Type");
     members.create(newMember);
     members.create(newMember);
}
</source>
<br/>
-----
<br/>
===== Ensuring unique non-Name field =====
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 some other 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 the entries in the library
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>
</source>

Navigation menu