Chapter 13. Script Triggers

A script trigger enables a developer to specify that a script execute whenever a particular action is performed. Before FileMaker Pro 10, when the script trigger feature was first introduced, scripts were generally initiated either by clicking a button or selecting a menu item. With the exception of the file open and close preferences, initiating a script based on an event previously required the use of a plug-in.

Setting Script Triggers

FileMaker Pro 12 supports 19 script triggers for actions in three major areas:

1. File events, such as opening or closing a window

2. Layout events, such as loading a record or layout

3. Object events, such as entering or exiting a field

For each script trigger event, you specify the script to execute and optionally pass to it a script parameter, which is defined by literal text or dynamically by calculation. For layout and object events, you also specify the mode in which the script fires (Browse, Find, and/or Preview). You can disable a script trigger without deleting it by simply unchecking all the modes.

Script triggers for File, Layout, and Object events are each configured in their own settings dialog.

File Events

A script trigger can be specified for each supported file action within the File, File Options menu item on the Script Triggers tab, as shown in Figure 13.1. There are four file-level script triggers; all are related to the opening or closing of a window. Note that with FileMaker 12, the long-existing File Options for executing a script when a file is opened or closed have been converted to the more appropriately named script triggers OnFirstWindowOpen and OnLastWindowClose. This makes it more evident that the script does not run when a file is opened by another file with the option “Open Hidden”, but instead is performed only when the first window is created.

Image

Figure 13.1. The Script Triggers tab of the File Options dialog enables you to define script trigger execution for file events.

Layout Events

Script triggers can be assigned to layout specific actions as part of the layout’s setup. After entering Layout mode while viewing the layout, select Layout, Layout Setup and choose the Script Triggers tab, shown in Figure 13.2. You can assign different scripts to trigger for each layout, one script per layout event.

Image

Figure 13.2. The Script Triggers tab of the Layout Setup dialog enables you to configure triggers for layout events. FileMaker Pro 12 supports nine layout script triggers.

Layouts that are configured with a script trigger display a star on the layout icon in the Manage Layouts window, as shown in Figure 13.3. This indicator is also presented by the Go to Layout script step within the Specify Layout dialog.

Image

Figure 13.3. The Manage Layouts dialog displays a red starburst to indicate layouts that are configured with a script trigger.

Object Events

Individual layout objects may be assigned an event script trigger. You may assign triggers to many different types of layout objects, including fields, text-based buttons, tab controls, web viewers, and portals.

To configure a script trigger for an object, you must first enter Layout mode while viewing the layout that contains the object. Next, select the object to which you want to assign a script trigger and choose Format, Set Script Triggers or choose Set Script Triggers from the object’s contextual menu. You can display the contextual menu by right-clicking (Control-clicking on a Mac) an object; the Set Script Triggers dialog displays (see Figure 13.4).

Image

Figure 13.4. The Set Script Triggers dialog enables you to configure the script triggers for the selected object. FileMaker Pro 12 supports seven object triggers.

While you’re working in Layout mode, objects that are configured with one or more script triggers are marked with a badge, either Image, depending on the size of the object. To make the badges visible (or to hide them), select View, Show, Script Triggers.

You may set script triggers for multiple objects at the same time by selecting them all before opening the Script Triggers dialog. If you see a minus sign (“–”) in the check box for a given script trigger, it indicates the objects selected have different trigger settings. Changes you make are applied to the individual triggers you modified, whereas the original settings for the other triggers are left as originally specified. For example, assume two fields have the following properties: Field A is configured with only an OnObjectKeystroke script trigger, and field B has only an OnObjectEnter script trigger. Assume next that the developer selects both fields and then opens the Script Trigger dialog. If she now assigns a script for the OnObjectExit event and makes a change to the OnObjectEnter trigger, these two triggers are updated for both objects while each retains its previous setting for the keystroke event.

Activating Script Triggers

A script trigger can be invoked only by direct operations. Script steps and menu commands that initiate a bulk function—such as Import Records, Replace Field Contents, and Relookup Field Contents—do not activate a script trigger. Likewise, spell check operations for all fields in a record or all records do not activate script triggers, with the following exceptions:

• When a field is active while the spell check operation begins, the OnObjectExit trigger executes.

• If a field is active at the end of the spell check operation, the OnObjectEnter trigger fires for that field.

Script triggers are fully supported by FileMaker Go. Instant Web Publishing (IWP) and Custom Web Publishing (CWP) can activate script triggers only by scripted actions, not direct user interaction. For example, a script that navigates to a layout that has an OnLayoutEnter script trigger will still trigger when using IWP or CWP.

Apple Events that apply directly to, or work through, layout objects trigger scripts; however, Apple Events that bypass the layout do not activate script triggers. Finally, schema changes that modify field data do not trigger scripts.

Timing of Script Triggers

Script triggers are activated by some discrete event, such as typing a character or navigating to a layout. For some script triggers, the event occurs and then the script trigger activates; for others, the trigger activates and then the event occurs. Broadly then, you can categorize script triggers as either being “before event” triggers or “after event” triggers. This distinction is important because it is possible for the “before event” triggers to suppress the event from occurring.

For example, OnWindowOpen activates its script after a window is opened. The script can have no effect on the window’s creation. On the other hand, OnObjectExit activates its script before the exit event, which means that the script can determine whether the event takes place. When the script’s result is False, the event is canceled, whereas a True result allows the event to proceed. You specify a script result by using the Exit script step. FileMaker considers the keyword value True or the number 1 to be a true result. The keyword value False or the number 0 is considered a false result. Note that all scripts that exit without explicitly returning a result are also considered true.

It is important to keep in mind that a single user interaction can conceivably activate multiple script triggers. Likewise, the steps performed by one triggered script may in turn cause the execution of another script trigger. For example,

• Opening a new window activates OnWindowOpen, OnLayoutEnter, and OnRecordLoad script triggers.

• Changing layouts activates the OnLayoutEnter and OnRecordLoad script triggers.

• Performing a find activates the OnModeExit/Enter and OnRecordLoad script triggers.

Table 13.1 documents the order in which script triggers execute when initiated by a single action. Pay close attention to this sequence along with whether the script fires before or after the event that triggers it.

Table 13.1. Order and Timing of Script Triggers

Image

OnObjectSave is the one script trigger that is performed after its event yet is also affected by the script’s result. The reason is that it initiates the script after the object’s data is validated and saved but before the object is exited. It is similar to the OnObjectExit trigger, but it executes only when the object has been successfully changed. The script result determines only if the object is exited, not whether the data is saved.

For object script triggers that perform before the event, FileMaker executes the script only one time as long as the triggering object remains active. However, if during the execution of the script, the object is exited and then reentered and the script returns True, the script trigger fires again, leaving the user in an endless loop. To avoid this fate, you are advised to trap for this event and exit the script with a False result, or prevent the exit of the object during script execution in the first place.

For instance, suppose you want to track a user’s navigation and so configure each layout with the OnRecordEnter script trigger. The associated script quickly switches to a NavLog layout, creates a record to log the action, and then returns the original layout. The act of returning to the original layout causes the OnRecordEnter script trigger to execute again, leaving the user in an infinite loop. Manage the situation by adding a few steps to the beginning and end of your script as follows:


Examples:

//Begin by immediately checking if the script is already running
If [ $$SCRIPT_RUNNING = 1]
   Exit Script [Result: False]
End If
#
// Set a global variable to indicate we are running the script
Set Variable [$$SCRIPT_RUNNING; VALUE:1]
#
#   *** << INCLUDE YOUR SCRIPT STEPS HERE >> ***
#
// End by clearing the variable
Set Variable [$$SCRIPT_RUNNING; VALUE:""]
Exit Script [Result: True]


Regardless of the methodology you use, it is imperative that you test your scripts thoroughly.

Scripting for Script Triggers

As with any script the user executes, a script initiated by a script trigger is executed with the user’s current privileges, unless the Run Script with Full Access Privileges option is specified.

Although any script can be called by a script trigger, naming scripts especially for the event and object, and organizing them into a Trigger folder can make a system much easier to manage.

FileMaker Pro Advanced 12 provides a feature that can disable all the script triggers for a file, which can be helpful when you are debugging or troubleshooting issues. It is accessed on the Script Debugger from a new button, Enable/Disable Script Triggers, located in the upper-right corner of the window. A user must have [Full Access] privileges to enable or disable script triggers in this way. As shown in Figure 13.5, the Script Debugger also indicates the script trigger that initiated the running script, in this case an OnRecordCommit event.

Image

Figure 13.5. The Script Debugger includes a button to enable or disable script triggers. It also indicates the type of script trigger that initiated the running script.

Because there is no script step that can dynamically disable all script triggers, it is a best practice to include a subroutine at the top of every script initiated by a script trigger that immediately exits the script when some type of indicator flag is set. This indicator flag could be in the form of a global variable or global field. It could even be abstracted further by calling a custom function or subscript that in turn tests for the indicator’s value. In any case, it can be handy when performing complex automated routines to be able to toggle the script trigger execution to help alleviate unforeseen behaviors.

It can also be a good idea to create separate layouts that include no script triggers of any kind so that you can perform your scripted routines without the interference caused by unexpected scripts being triggered.

Tab Control Objects

FileMaker Pro 12 introduced a new object script trigger called OnTabSwitch that is invoked when the user attempts to switch the active tab, either manually or by script. Although the OnObjectModify trigger can also be applied to a tab control object, it activates the script after the user changes tabs, whereas this new trigger executes before the tab is switched.

Two new functions also are handy when creating the script for the OnTabSwitch trigger: Get (TriggerCurrentTabPanel) and Get (TriggerTargetTabPanel), which return the index and object name of the current tab panel and destination tab panel, respectively. You can read more about this trigger in the “Script Trigger Reference” section later in this chapter and learn more about the functions in Chapter 10, “Calculation Functions.”

Instant and Custom Web Publishing

Script triggers are only partially supported when a database file is accessed by IWP or CWP. Script triggers do not activate when a user directly interacts with an object, such as exiting a field or selecting a tab. However, when a running script includes steps that interact with an object, such as Go to Field or Insert Calculated Result, script triggers activate. Because of this behavior, it is advisable to refrain from using script triggers with layouts accessed by IWP.

Script Trigger Reference

Description:

The OnFirstWindowOpen script trigger executes each time the first window of a file is opened. It activates when you initially open the file as well as when the initial window is opened for a file that was previously opened as hidden by another file.

Before FileMaker Pro 12, this trigger was the File Open script specified in the File Options dialog. When a file created with an earlier version is converted to FileMaker Pro 12, the File Open script option is converted to the OnFirstWindowOpen script trigger.

It is possible for this trigger to fire multiple times during a session if the last window of the file is closed, but the file remains open because it is referenced by another open file. Should the now-hidden file be directed to open a window, OnFirstWindowOpen executes again.

It is considered a best practice to use the OnFirstWindowOpen trigger to set up the user’s initial context including the window position and size, initial layout, found set, and sort order and to initialize global fields.


Examples:

// Display the main menu
Go to Layout ["Main Menu" (Resources)]
Show/Hide Toolbars [Show]
Set Zoom Level [100%]
If [Abs ( Get ( SystemPlatform ) ) = 2]
    Adjust Window [Maximimize]
Else
    Adjust Window [Resize to Fit]
End If


Description:

The OnLastWindowClose script trigger activates whenever the user attempts to close the last window of a file. The script executes even if the file remains open, such as when the file is referenced by another file.

Before FileMaker Pro 12, this trigger was the File Close script specified in the File Options dialog. When a file created with an earlier version is converted to FileMaker Pro 12, the File Close script option is converted to the OnLastWindowClose script trigger.

The OnLastWindowClose trigger is especially useful for clearing global fields because they default to the value they contained when the file was last closed while hosted locally. The following script demonstrates a methodology for clearing global fields when the file is hosted locally.


Examples:

//Clear global fields when open locally to initialize values
If[IsEmpty ( Get ( HostApplicationVersion) )]
    Set Field [Resource::Account_g; ""]
End If


Description:

The OnLayoutEnter script trigger activates after a layout loads. This occurs when opening a window or switching to a new layout. Note that the script step New Window creates the new window and displays the currently viewed layout. This activates an OnLayoutEnter script trigger before proceeding with the other script steps for navigating to a new layout, and so on.

One typical use of the OnLayoutEnter script trigger is for automatically sorting the records of a list layout, thereby ensuring users are always presented a complete report with subsummary parts.


Examples:

//Dynamic sort the layout's data whenever it loads
Go to Next Field
Sort Records by Field [Ascending]


Description:

OnLayoutExit activates before a layout is exited. A layout is exited by switching to another layout or closing a window. When the activated script exits with a False result, the user remains on the current layout. Note that simply making a different window active does not constitute exiting a layout.

OnLayoutExit is useful for checking that the user has completed everything he needs to do on the current layout before moving on.

Many users would like their database to behave more like a browser and provide a Back button for retracing their steps after drilling into a record’s detail. One great use of the OnLayoutExit trigger is to record a user’s navigation to support a Back button, as shown in the following example. The navigation history is stored as a carriage-return delimited list in a global variable. Each window’s history is stored in the variable’s repetition that corresponds to the window’s name, so a window whose name ends in 2 is stored in the second repetition and so on. (See the example for OnWindowClose for another script related to supporting a Back button.)


Examples:

//Store navigation history to support a back/forward button
Set Variable [$winNum; Value: Let ( [ winName = Get ( WindowName ) ; winValues = Substitute ( winName ; " - " ; ¶ ) ; lastVal = ValueCount ( winValues ) ; winNum = GetAsNumber ( GetValue ( winValues ; lastVal ) )]; Case ( IsEmpty ( winNum ) ; 1 ; winNum )  )]
Set Variable [ $$BACK_STACK[$winNum]; Value: Case ( not IsEmpty ( $$BACK_STACK[$winNum] ) ; $$BACK_STACK[$winNum] & ¶ ) & Get ( LayoutName ) ]


Description:

The OnLayoutKeystroke script trigger is activated with each individual keystroke typed into a keyboard or Input Method Editor (IME). An IME is an application that can enter the many different characters used in East Asian written languages without the need of a special keyboard. All keystrokes cause the script trigger to activate, including those normally used for navigation. However, data entry by way of a drop-down list, pop-up menu, calendar picker, check box, or radio button does not active this trigger. Likewise, script steps that insert data into fields do not active this script trigger, even those that require the field be present on the layout.

Keystrokes are evaluated first by the operating system and then by the FileMaker Pro application itself before being passed to the database file. As such, a key combination that is a System or FileMaker command shortcut does not activate either of the keyboard script triggers.

The script trigger is activated before the keystroke is processed, so when the triggered script returns a False result, the event (also known as the keystroke) is suppressed. If the active object is configured with both OnLayoutKeystroke and OnObjectKeystroke script triggers, the layout trigger activates first and its script must exit with a True result to activate the object’s trigger.

The Get(TriggerKeystroke) function returns the characters that activated the script trigger. You can then use the Code function to translate this into a Unicode value. Table 13.2 lists some common keystrokes.

Table 13.2. Common Keystrokes and Their Unicode Value

Image

OnLayoutKeystroke can be used on a table view layout to mimic a spreadsheet’s navigation, which makes use of the arrow keys to move between cells.


Examples:

//While in Table view, use arrow keys for record and field navigation
If [Get ( LayoutViewState ) = 2  //table view]
    Set Variable [$code; Value:Code ( Get ( TriggerKeystroke ) ) ]
    If [$code = 29  //up arrow]
        Go to Record/Request/Page[Previous]
    Else If [$code = 31  //down arrow]
        Go to Record/Request/Page [Next]
    Else If [$code = 30  //right arrow]
        Go to Next Field
    Else If [$code = 28  // left arrow]
        Go to Previous Field
    End If
End If


Description:

The OnModeEnter script trigger activates after switching modes (Browse, Find, or Preview), either manually or by a script step.

You can use OnModeEnter to navigate to a specially formatted layout when the user enters Find mode. It is also handy for automatically sorting data when the user enters Preview mode, as shown in the following example.


Examples:

// When user enters Preview Mode, sort the data
If [Get (WindowMode ) = 2  //Preview Mode]
    Sort Records [Restore; No dialog]
End If


Description:

The OnModeExit script trigger activates when the user attempts to exit the current mode. When the triggered script returns a True result, the mode change is carried out, but a False result cancels the event.

You can use OnModeExit to run a script when leaving Find mode to log the user’s searches. Another purpose is to append the search request with additional criteria when exiting Find mode to omit records that are flagged for deletion. Use it when exiting Preview mode to give the user the option to print the report.


Examples:

//When user exits Find Mode, try to show list view to display the result
If [Get (WindowMode ) = 1  //Find Mode]
    Set Error Captute [On]
    Set Variable [$layoutName ; Value:Substitute ( Get ( LayoutName ) ; "Detail" ; "List" )]
    Go to Layout [$layoutName]
End If
Exit Script [Result: True]


Description:

The OnObjectEnter trigger executes when a specific layout object becomes active by either a user or a script interacting with the object. A user can accomplish this by clicking the object, tabbing to the object, or tabbing between the repetitions of a repeating field. This trigger can also be activated by a script step that causes an object to be entered.

OnObjectEnter can be configured for a chart object. Use it to auto save the chart as a picture file by temporarily copying and pasting the chart into a container field before exporting the field’s contents. This trigger can also be configured to a Web Viewer object, which is handy for displaying a modal dialog window where the user is prompted to enter criteria for the site.

When this trigger is applied to a portal object, it fires each time a different portal row becomes active. Although tab control objects and buttons also can be assigned the OnObjectEnter trigger, it does not activate when the object is clicked or otherwise becomes active.

The following example is configured as the OnObjectEnter trigger for the Employee’s Spouse field. It requires the value to be empty when the Employee’s Marital Status is "Single".


Examples:

//Prohibit entry of value in a field that should remain empty based on other fields
// Trigger applied to the Employee::Spouse field
If [Employee::Marital_Status = "Single"]
    Go to Next Field
End If


Description:

The OnObjectExit script trigger fires before the active object is exited, by either a user or a script interacting with the object. A user can accomplish this by clicking another object, tabbing away from the object, attempting to tab between the repetitions of a repeating field, attempting to move between rows in a portal object, or by requesting a dialog box, such as the print dialog, that would usually cause the field to be exited. This trigger also can be activated by a script step that attempts to activate a different object.

OnObjectExit can be applied to fields, web viewers, charts, and portal objects. When this trigger is applied to a portal object, it fires each time a portal row is exited. Although tab control objects and buttons can also be assigned the OnObjectExit trigger, it does not activate when the object is clicked or otherwise becomes active. Note that scrolling does not change the active object and so does not initiate this script trigger.

This trigger is especially useful for guiding data entry by skipping fields that are not needed based on the user’s entry in other fields.


Examples:

//Skip the explanation field when responded NO
If [MedHistory::HospitalStayLastYear = "No"]
    Go to Field [MedHistory::HeartCondition]
Else
    Go to Field [MedHistory::HospitalStayLastYear_explain]
End If


Description:

The OnObjectKeystroke script trigger executes whenever the object is active and receives one or more characters, either by a keyboard or by an Input Method Editor (IME). An IME is an application that can enter the many different characters used in East Asian written languages without the need of a special keyboard. All keystrokes cause the script trigger to activate, including those normally used for navigation. However, data entry by way of a drop-down list, pop-up menu, calendar picker, check box, or radio button does not activate this trigger. Likewise, script steps that insert data into fields do not activate this script trigger, even those that require the field be present on the layout.

Keystrokes are processed first by the operating system and then by the FileMaker Pro application itself before being passed to the database file. As such, a key combination that is a System or FileMaker command shortcut does not activate either of the keyboard script triggers.

OnObjectKeystroke is activated before the keystroke is processed, so when the triggered script returns a False result, the event is canceled. If the active object is configured with both the OnLayoutKeystroke and OnObjectKeystroke script triggers, the layout trigger activates first and its script must exit with a True result to also activate the object’s trigger.

You can determine which characters were input using the Get(TriggerKeystroke) function; use the Code function to translate this into a Unicode value. Refer to Table 13.2 for a table of common keystrokes.

The OnObjectKeystroke script trigger activates when applied to field, button, chart, and tab control objects. You also can assign it to a web viewer, but it does not fire the script.

This trigger is useful for directing the user’s entry into a fixed-width field by automatically tabbing to the next field when data entry is completed. In the following example, the user’s cursor is automatically moved to the next field when the proper number of characters has been entered in each field that stores a serial number.


Examples:

//For Serial Number field, move to next field when length is 5
//Wire to each of the 4 fields that make up the serial number
Set Variable [$key; Value:Get (TriggerKeystroke)]
Set Variable [$code; Value:Code ($key)]
If [$code=8 or $code=9 or $code=127  //backspace, tab, or delete]
    Exit Script [Result: True]
Else If [$code ≥ 27 and $code ≤ 31 //arrow keys]
    Exit Script [Result: True]
Else If [Length (Contact::Serial_Number_1) ≥ 5]
    Go to Next Field
    Exit Script [Result: True]
End If


Description:

The OnObjectModify script trigger activates whenever an object’s value is changed through direct interaction. In contrast to the OnObjectKeystroke script trigger, this trigger executes when modifying the value using a pop-up menu, drop-down list, check box, radio button, and calendar picker as well as cut, copy, and paste commands.

Changes made to a field from the Show Custom Dialog script step, however, do not activate OnObjectModify. Likewise, with the script steps that modify a field value directly, such as Set Field, Set Field by Name, and Set Web Viewer, the trigger does not run. However, the script step Insert Text and others that work on a layout object that is a field activate the OnObjectModify trigger. It also fires when applied to a tab control and the tab is switched. Whereas the interface allows the OnObjectModify trigger to be assigned to a calculation or summary field, the trigger does not activate when the value changes.

The OnObjectModify script trigger has many applications. It is useful for formatting the user’s entry of a phone number or Social Security number. When applied to a tab control object, it triggers each time the active tab is changed.

The following script example is activated by an OnObjectModify trigger attached to a global field that filters a list view of records based on the value entered.


Examples:

//This example will filter the record list based on global field entry in header
Set Variable [$cursorPosition; Value:Get ( ActiveSelectionStart)]
Commit Records/Requests[]
If[IsEmpty ( Resource::Company_Filter_g )]
    Show All Records
Else
    Enter Find Mode []
    Set Field [Company::Name; Resource::Company_Filter_g]
    Perform Find []
End If
// Restore cursor to original position
Go to Field [Resource::Company_Filter_g]
Set Selection [Resource::Company_Filter_g; Start Position: $cursorPosition]


Description:

OnObjectSave executes after the object data has been validated and saved, but before the field is exited. It is the one script trigger that is performed after its event yet is also affected by the script’s result. The reason is that the trigger initiates the script after the object’s data is validated and saved, but before the object is exited. It is similar to the OnObjectExit trigger, but executes only when the object has been successfully changed. The script result simply determines if the object is exited, not whether the data is saved.

One use for this trigger is to clear the values of fields that are no longer appropriate based on other field values. In the following example, the explanation field is cleared when the HospitalStayLastYear field is set to no.


Examples:

//Clear Explanation field value when the Yes/No radio button is No
If [MedHistory::HospitalStayLastYear = "No" and not IsEmpty (MedHistory::HospitalStayLastYear_explain )]
    Set Field [MedHistory::HospitalStayLastYear_explain; ""]
End If


Description:

The OnObjectValidate trigger executes before the active object is validated and saved. As such, it fires only when the selected field data has been changed. This trigger can be useful for performing prevalidation on a field value in an effort to correct obvious issues and/or deliver a more specific message to the user. For instance, the following example illustrates a simple script for removing spaces from an email address before it is evaluated by the field’s validation calculation.


Examples:

//Remove spaces from user's email address entry before validation
Set Field [Contact::Email; Substitute ( Contact::Email ; " " ; "" )]


Description:

The OnRecordCommit script trigger activates before a record that has been changed is committed. Many actions can cause this trigger to activate. The user, after modifying a record, can do any of the following: move to another record, press the Enter key, click the layout outside the activated record, or immediately access the Manage Database dialog. OnRecordCommit also triggers when a script step, after modifying a record, moves focus to a different record or performs the Commit Records/Requests script step.

Assume, for example, that users want to avoid accidentally making changes to their records, preferring instead to click an Edit button before making data changes and then a Save button to commit the changes or a Cancel button to revert the record. The Edit button would call a script that adds the active window’s name to the variable $$EDIT_MODE. The Save button would call another script that removes the current window’s name from the variable $$EDIT_MODE and performs the Commit Record step. The Cancel button would also clear the global variable but revert the record instead of committing. The following example prevents the record from committing until the user clicks the Save button.


Examples:

//This script keeps the record open until the user clicks the Save button on screen
If [FilterValues ( $$EDIT_MODE ; Get (WindowName ) )]
    Exit Script [Result:False]
Else
    Exit Script [Result:True]
End If


Note this example is not intended to secure the data, but rather only to protect the user from himself when working with this layout.

Description:

The OnRecordLoad script trigger executes every time a record is made current or entered. This situation can occur when the user or script switches the record or layout, opens a new window, performs a find, or creates or deletes a record.

OnRecordLoad is handy for refreshing aggregate values stored for a record. In the following example, OnRecordLoad can be used to dynamically display the proper tab of a tab control that corresponds to a field’s value.


Examples:

//Switch the hidden tab displayed to correspond to the Company Type
If [Company::Type = "Vendor"]
    Go to Object [Object Name: "TAB__Vendor"]
Else If [Company::Type = "Client"]
    Go to Object [Object Name: "TAB__Client"]
Else
    Go to Object [Object Name: "TAB__Blank"]
End If


Description:

The OnRecordRevert script trigger is performed before record changes are reverted. It therefore fires only when the record contains uncommitted changes. You can revert a record by selecting Records, Revert Record or by running a script containing the Revert Record step. The OnRecordRevert trigger also fires when the record is reverted following a validation error dialog.

One use for this script trigger is to display an additional confirmation dialog when the user attempts to revert a record, as illustrated in the following example.


Examples:

//Display an additional confirmation dialog when revert record
Show Custom Dialog ["Revert Record"; "Are you sure you want to revert... all of your changes will be lost?"]
//buttons are Default Button: Revert Record;  Button 2: Cancel
Exit Script [Result; Case ( Get ( LastMessageChoice ) = 2 ; False ; True )]


Description:

The OnTabSwitch script trigger, new in FileMaker Pro 12, executes when a user or script attempts to change the active tab. This trigger applies to the entire tab control object rather than just one individual tab panel. This trigger executes before the tab is changed, so a script result of False stops the tab from being switched. Note that you can fire a script after the tab is changed by attaching the OnObjectModify trigger to the tab control object.

The two new functions—Get (TriggerCurrentTabPanel) and Get (TriggerTargetTabPanel)—are useful when creating the script called by the OnTabSwitch trigger. They return the index number and object name of the current tab panel and destination tab panel, respectively. You can read more about these functions in Chapter 10.

This trigger is useful for refreshing field values that drive the display of objects on a tab before it is viewed. For example, you can set the value of a field used to dynamically filter a portal or refresh aggregate values stored in a number field. (Storing values can make for a faster display rather than using unstored calculations.)

You can also use OnTabSwitch to restrict the view of a tab for certain users. In the following example, the user is required to have the extended privilege "SysAdmin" to view the Client Settings tab.


Examples:

// Must have Admin extended privilege to view the tab
Set Variable [$targetTabName; Value:GetValue ( Get (TriggerTargetTabPanel) ; 2)]
If [$targetTabName = "Client Settings"]
    If [FilterValues ( Get (AccountExtendedPrivileges ) ; "SysAdmin" )]
        Exit Script [Result: True]
   Else
        Beep
        Show Custom Dialog ["Message"; "Sorry, you must be an admin to view this tab."]
        Exit Script [Result: False]
   End If
End If
Exit Script [Result: True]


Description:

The OnViewChange script trigger executes after a user or script changes the view between form, list, and table views. Note that OnViewChange does not fire when a new window is open unless another action causes the view to change.

Keep in mind that the triggered script will likely cause the screen to flicker if it navigates to a new layout. Because of this, it is not advisable to use OnViewChange to navigate to an alternative layout specifically formatted for the view selected. You achieve a better user experience by using custom menus and reassigning the View as Form, View as List, and View as Table menu items to perform your script.

A better use of OnViewChange is to present the user with options appropriate to the new view. In the following example, the user is given the option to sort the data by Department, which then displays the subsummary part.


Examples:

// When entering Table View, offer to sort by Department
If [ Get ( LayoutViewState ) = 2  //Table View]
   Show Custom Dialog ["Message"; "You've switched to Table View. Should I also sort the Data into departments"]
   //Dialog Buttons: 1=Yes; 2=No
   If [Get (LastMessageChoice ) = 1   //Yes]
      Sort Records [Restore; No Dialog]
   End If
End If


Description:

The OnWindowClose script trigger is a file-level trigger. As such, it activates any time one of the file’s windows is closed, regardless of whether the close was initiated by a user or script. When the OnLastWindowClose trigger is also specified, OnWindowClose executes first. Should the OnWindowClose trigger return a False result, the window is left open and the OnLastWindowClose trigger is not activated.

Many users would like their database to behave more like a browser and provide a Back button for retracing their steps after drilling into a record’s detail. The following example uses OnWindowClose to clear the current window’s navigation history before closing the window. Each window’s history is stored in the repetition of a global variable that corresponds to the window’s name. (See the example for OnLayoutExit for another script related to supporting a Back button.)


Examples:

//Clear the back/forward navigation history for this window
//History stored in a global variable repetition corresponding to the window's number
Set Variable [$winNum; Value:Let ( [ winName = Get ( WindowName ) ; winValues = Substitute ( winName ; " - " ; ¶ ) ; lastVal = ValueCount ( winValues ) ; winNum = GetAsNumber ( GetValue ( winValues ; lastVal ) )]; Case ( IsEmpty ( winNum ) ; 1 ; winNum )  )]
Set Variable [ $$BACK_STACK[$winNum]; Value:"""]


Description:

The OnWindowOpen script trigger executes every time a new window is opened for the file, whether initiated manually by a user or script. Note that the OnWindowOpen trigger also activates when opening a window for a hidden file, which is a file that was previously opened by a relationship or script.

Because the script runs after the triggering event, the window always opens regardless of the triggered script’s result. If an OnFirstWindowOpen trigger is also specified in the file options, it executes first and then OnWindowOpen runs.

OnWindowOpen is useful for renaming the window when your database does not use FileMaker’s default naming convention of naming the window for the filename.

Imagine you have a database system that is composed of multiple databases and that one of the files should remain hidden (except for full access users) because it contains only data and not the interface. The script that follows could be activated by the OnWindowOpen trigger to discourage inappropriate interaction with the file.


Examples:

//Hide the file when the user does not have full access privileges
If[Get ( AccountPrivilegeSetName ) ≠ "[Full Access]"]
    Show Custom Dialog ["Permission Denied"; "Sorry, you are not permitted to view this file."]
    Close Window [Current Window]
  End If


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.6.75