Skip to content

HOW TO Get unique values for fields

Eric BREHAULT edited this page Sep 23, 2016 · 1 revision

Like UNIQUE constraint in SQL, prevent saving when the field's value is not unique.

Prerequisites: The target field must be indexed (field settings -> Add to index)

Go to the target field settings. Enter the following code in the “Validation Formula” field. Don't forget to change the “FIELD_NAME”.

db = context.getParentDatabase()
ix = db.getIndex()
docs = ix.dbsearch({'FIELD_NAME': context.FIELD_NAME})
if len(docs) > 0:
    if context.isNewDocument():
        return 'Cannot save: duplicate value'
    elif docs[0].id != context.id:
        return 'Cannot save: duplicate value'
return ''

That's all!

Note: If you need to return Unicode messages, do not prefix them with “u”.