Assume we have a form called "Department Master Form", which has two Text, Editable fields -- Dept_Code and Dept_name. Now the requirement is, Dept_Code should be Unique and Not Null for each record (document) we create, thus Dept_Code is the Primary Key field.
In any RDBMS, this implementation is quite straightforward by just declaring the Dept_Code column as Primary Key when creating the "Department Master" table.
To implement in Notes
1. Create a view (e.g. Department Master View) with first sorted column as the Primary Key column, in this case Dept_Code is the first sorted column for this view.
2. In the form (Department Master Form) QuerySave event, write script to do the following things:
2a. Check that the Key field value (i.e. Dept_Code) in the Current Document is Not Null;
2b. If Key value (Dept_Code) of Current Document (Document you are currently Editing / Creating) is the same as Key value of an Existing Document (Document saved earlier in the database), compare their Universal ID's. If Universal ID's match (You are Editing an Existing Document), allow saving the Current Document. If UniversalID's for these two documents is different, raise Primary Key Voilation message.
The below code in QuerySave event of "Department Master Form" achieves point 2 above.
'' Code in Code field below Extension 1:
The same code can be extended to cater for Primary Key with multiple field values (Combination Primary Key).
Lets say, Dept_Code and Section_Code fields in the form "Department Master Form" make the Combination Primary Key. Modify the view to have multiple sorted columns - Sort by Dept_Code then by Section_Code, and change the QuerySave script to include Not Null validation for both fields. Also, change the line Set existingdoc = view.GetDocumentByKey( Key, True ) to... Set existingdoc = view.GetDocumentByKey( KeyArray, True ) where KeyArray stores all fields in Primary Key in that order.
In the present example, KeyArray will have 2 values as Dim KeyArray(0 to 1) As Variant KeyArray(0) = Cstr(currentdoc.Dept_Code(0)) KeyArray(1) = Cstr(currentdoc.Section_Code(0))
Extension 2: (Case Insensitive Keys) You can even extend the script to take care of the Case of the key fields values. Values like "D0001" and "d0001" for Dept_Code field can always be saved and compared as "D0001".
Thanks and Happy Reading :)
This was first published in November 2000