Top Banner
Chapter Overview T his chapter will introduce you to the Lotus Formula Language. There are many books on the market that teach syntax and how to program. However, this chapter is intended to be a general introduction to facilitate learning and to help you understand the projects provided in this book. Additional information can be found in the Domino Designer help database that is included with the Designer software. By the end of the chapter you will have learned What Formula Language is • What @Functions are • What @Commands are The basic syntax structure How to assign values to variables How to construct multi-line formulas How to use formulas to calculate a field value Frequently used @Functions Frequently used @Commands What Is Formula Language? Formula Language is a simple, easy-to-use programming language that can be found in many Lotus products—such as Lotus 1-2-3 and Lotus Notes. Formula Language has been integrated into Lotus Notes since its inception in 1989 and has included numerous enhance- ments over the years. 93 Chapter 5 An Introduction to Formula Language
22
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Formula

Chapter Overview

This chapter will introduce you to the Lotus Formula Language. There are many bookson the market that teach syntax and how to program. However, this chapter isintended to be a general introduction to facilitate learning and to help you understand

the projects provided in this book. Additional information can be found in the DominoDesigner help database that is included with the Designer software.

By the end of the chapter you will have learned

• What Formula Language is• What @Functions are• What @Commands are• The basic syntax structure• How to assign values to variables• How to construct multi-line formulas• How to use formulas to calculate a field value• Frequently used @Functions• Frequently used @Commands

What Is Formula Language?

Formula Language is a simple, easy-to-use programming language that can be found inmany Lotus products—such as Lotus 1-2-3 and Lotus Notes. Formula Language has beenintegrated into Lotus Notes since its inception in 1989 and has included numerous enhance-ments over the years.

93

Chapter 5

An Introduction toFormula Language

Elliott_05.qxd 9/14/06 2:27 PM Page 93

Page 2: Formula

Then, in 2002, Lotus decided to completely rewrite the underlying processor (or engine)used to interpret the formula language source code. This significantly improved its per-formance and expanded its capabilities. Using a few simple Formula Language commandsand functions, you can build a robust database application.

What Is a Formula?

In the simplest terms, formulas are used to produce a data value or action. This value oraction is derived by using one or more commands, functions, or statements to create a mainexpression. All formulas must have a main expression that equates to a result. If the formuladoes not produce a value or action, the Designer client will not allow you to save the formula.

For example, the following illustrates an invalid formula. Here, the text value “Happy NewYear” is assigned to a temporary variable called message. Although the formula does per-form a calculation, there is no main expression. This formula does not produce a result.

message := "Happy New Year";

For this example to be valid, the formula must do something to produce a result. This sec-ond example illustrates a valid formula. Looking at this formula, you’ll notice that the firstline performs a computation by assigning a text value to a temporary variable. The state-ment is terminated with a semicolon, which separates the first statement from the second.The formula then ends with the main expression, which defines the value for the field.

message := "Happy New Year";message

In this case, the main expression is assigned the contents of the variable message.Alternatively, the same result could have been achieved by setting the text string to be themain expression, as illustrated next.

"Happy New Year"

TIP

When writing a formula containing multiple statements, each statementmust be separated by a semicolon, and the last line in the formulamust be the “main expression.”

Working with Variables

Now let’s take a look at the basic syntax rules for working with variables. There are two typesof variables that can be utilized in formulas—temporary variables and field name variables.

94 Chapter 5 • An Introduction to Formula Language

Elliott_05.qxd 9/14/06 2:27 PM Page 94

Page 3: Formula

Temporary variables, as the name implies, are used to temporarily store a value associatedwith the formula. Temporary variables cannot be referenced outside of the formula and onlycontain a value for the duration of the formula’s execution. In other words, the value storedin a temporary variable is not saved when the document or form is saved and cannot be ref-erenced by other formulas.

The syntax for creating a temporary variable is VariableName and the assignment operator:= followed by the data value and semicolon. For example, the following assigns "January"to the temporary variable called month.

month := "January";

Conversely, field name variables reference actual fields on a document or form. When usedin a formula, you can reference or change the value stored in the field name. In other words,by using formulas, you can use field names to calculate the main expression or modify thevalue already stored in the field.

There are three ways to reference an existing field. The FIELD keyword is used to assign avalue to an existing field. Using this keyword, the contents of the field are permanentlychanged and will be stored in the field when the document is saved. The syntax for settinga field value in a form or document is FIELD FieldName and the assignment operator :=followed by the new value and a semicolon. For example:

FIELD Month := "January";

It’s important to note that if the field exists on the form, the new value will replace the exist-ing data value. If the field does not exist on the form, Notes will create the field and assignthe value. Alternatively, you can also use the @SetField function. This function works justlike FIELD with one exception: @SetField can be imbedded within other FormulaLanguage functions.

@SetField ("Month"; "January");

Finally, to acquire the value of an existing field, you can use the @GetField function. Usingthis function, you can use the value stored in field inside another formula. For example, thefollowing will create the text string "Your project is due in: January", assumingthe Month field contains a value of "January".

"Your project is due in: " + @GetField ( "Month" );

NOTE

Lotus Notes will recognize a variable name regardless of the lettercase. Variable names can be uppercase, lowercase, or mixed case andwill still be understood. For example, the following are equivalent vari-able names: firstname, FIRSTNAME, FirstName, and FIRSTname.

Working with Variables 95

Elliott_05.qxd 9/14/06 2:27 PM Page 95

Page 4: Formula

Formula Language Keywords

As with any programming language, Formula Language includes a number of reserved key-words that have special meanings. These keywords are used to perform special functions andcannot be used as variables. For example, the following table describes the current list ofFormula Language reserved keywords.

Keyword Meaning

DEFAULT Used to define the initial or default value for a field. For example, let’s say you have a field called Status. Using the following formula, the field will be set to a value of "New Request" when the document is created. This field will continue to hold this value until either the user or the Notes application changes the value. After the stored value is changed and the document is saved, the new value will be stored in the field.DEFAULT Status := "New Request"; Status

ENVIRONMENT Used to assign a value to an environment setting in the user’s NOTES.INI file. For example, let’s say you have a database to request helpdesk support. Using the environment keyword, you could capture and store the employee’s serial number in the NOTES.INI file the first time an employee submits a service request. As new requests are submitted, the database could query for the existence of the field and automatically fill in the EmpNumfield with the employee’s serial number. If the environmentvariable does not already exist in the INI file, Notes will create the variable and assign it a value. Otherwise, if the variable already exists, Notes will assign the new value.ENVIRONMENT EmpNum := "123456";

Note: The @Environment function can also be used to retrieve (or set) an environment variable setting.

FIELD Used to assign a value to a field on a document or form. If the field exists, the new value will be assigned. If the field does not exist, the field will be created and assigned the value. For example, the following assigns the current date to a field called theDate.FIELD theDate := @Today;

REM Used to add comments to a formula. Comments must be enclosed in quotes or braces and terminated with a semicolon (if part of a multi-line formula). For example:REM "This is a comment.";

REM {This is a comment};

96 Chapter 5 • An Introduction to Formula Language

Elliott_05.qxd 9/14/06 2:27 PM Page 96

Page 5: Formula

Keyword Meaning

SELECT Used to determine the selection criteria for a view, agent, or replication formula. All documents that match the selection formula will be included in the view, agent, or replication formula.For example, let’s say you have a Notes database with multiple forms. To create a view that only displays one of the forms, you would define a selection formula similar to the following:SELECT form = "ServiceRequest";

By default, reserved words are always the first word in a statement. Reserved words may beentered in lower, upper, or mixed case. However, Designer will automatically convert loweror mixed case words to uppercase when the formula is saved.

Working with Operators

Operators are used to compare or equate values and for mathematic calculations. The fol-lowing table lists the primary operators used in formulas.

Operator Operator Usage or Description

- Used in subtraction or to represent a negative number

! Represents a logical NOT

!= Represents not equal

& Represents a logical AND

* Used in multiplication

/ Used in division

: Used to separate a list of values

:= Used to assign a value to a variable

| Represents a logical OR

+ Used in addition or to represent a positive number

< Represents less than

<= Represents less than or equal to

Working with Operators 97

continues

Elliott_05.qxd 9/14/06 2:27 PM Page 97

Page 6: Formula

Operator Operator Usage or Description

<> Represents not equal

= Represents equal

=! Represents not equal

> Represents greater than

>< Represents not equal

>= Represents greater than or equal to

General Syntax Rules

The Formula Language syntax rules are quite simple. All formulas must adhere to the fol-lowing five rules.

Rule 1: A semicolon must separate all formulas that contain more than one statement. It’simportant to understand that multiple statements can reside on a single line, pro-vided that a semicolon delineates each statement. For example, the following arevalid multi-statement formulas.

Example 1DEFAULT status := "New Request"; status

Example 2DEFAULT status := "New Request";status

Rule 2: At least one space must follow all reserved keywords. Otherwise, any number ofspaces—from none to many—may be used to separate operators, punctuation, andvalues. For example, the following are valid and equivalent statements (with regardto spacing):output := "Today's date is: " + @Today;output:="Today's date is: ” + @Today;FIELD output:= "Today's date is: " + @Today;

Rule 3: Two values, variables, or strings must be separated by at least one operator. Forexample, the following are valid statements. In the first example, the plus sign isused to sum the two numbers and divide the result by 2. In the second example,the plus sign is used to concatenate two values together. Finally, the third exampleshows three @Functions separated by the plus operator.output := (100 + 200)/2;output := "The sum of the two numbers is: " + total;output := @Month+@Day+@Year;

98 Chapter 5 • An Introduction to Formula Language

Elliott_05.qxd 9/14/06 2:27 PM Page 98

Page 7: Formula

Rule 4: You must use the := assignment operator to assign a value to a variable, whereasthe equal sign = is used to compare two values when used in a conditional state-ment (such as the @IF, @WHILE, or @FOR functions).

myVariable := "This is a valid assignment";

Rule 5: All formulas must contain a main expression that either produces a value or per-forms an action. For example, the following are valid main expressions.The following returns today’s date.

@Today

The following checks if the value stored in the result variable is equal to one. Ifthe condition is true, then the formula returns the text string "Yes". Otherwise,the formula is set to a text string "No".

@If ( result = 1; "Yes"; "No")

What Are Functions and Commands?

Formula Language can be divided into two groupings—@Functions and @Commands.Thesegroupings comprise Formula Language and are used to create formulas.

Functions are used to return a value and can be placed anywhere within a formula.Although most functions simply return a value, some functions interact with users or trig-ger other actions to occur. For example, the @Prompt and @PickList functions can be usedto request input from the user.

As you gain experience with Formula Language, you’ll find that most formulas are builtusing functions. However, some functions can only be used in specific design objects. Thefollowing table lists some of the restricted functions and describes where they can be used.

Restricted Function Design Objects That Can Use This Function

@All Replication formulas, agents, and view selection formulas

@AllChildren Replication formulas and view selection formulas

@AllDescendants Replication formulas and view selection formulas

@Command Toolbar buttons, manual agents, and action hotspots

@DBColumn Toolbar buttons, actions, hotspots, fields, and agent (except mail)

@DBLookup Toolbar buttons, actions, hotspots, fields, and agent (except mail)

What Are Functions and Commands? 99

continues

Elliott_05.qxd 9/14/06 2:27 PM Page 99

Page 8: Formula

Restricted Function Design Objects That Can Use This Function

@DeleteDocument Agents

@DeleteField Agents and fields

@DocChildren Column formulas and window title formulas

@DocDescendants Column formulas and window title formulas

@DocLevel Column formulas and window title formulas

@DocMark Agents

@DocNumber Column formulas and window title formulas

@DocParentNumber Column formulas and window title formulas

@DocSiblings Column formulas and window title formulas

@Failure Field validation formulas

ENVIRONMENT All formulas with the exception of popup hotspots

@Environment All formulas with the exception of popup hotspots

FIELD Toolbar buttons, agents, action hotspots, and fields

@IsCategory Column formulas

@IsDocBeingLoaded Forms and fields

@IsDocBeingMailed Buttons, hotspots, and fields

@IsDocBeingRecalculated Buttons, hotspots, and fields

@IsDocBeingSaved Buttons, hotspots, and fields

@IsExpandable Column formulas

@IsNewDoc Toolbar buttons, window title formulas, forms, and fields

@MailSend Toolbar buttons, agents, action hotspots, and fields

@PickList Toolbar buttons, manual agents, action hotspots, and fields

@Platform Toolbar buttons, manual agents, hotspots, view design (with the exception of selection and column formulas), forms, and fields

100 Chapter 5 • An Introduction to Formula Language

Elliott_05.qxd 9/14/06 2:27 PM Page 100

Page 9: Formula

Restricted Function Design Objects That Can Use This Function

@Prompt Toolbar buttons, manual agents, action hotspots, and fields

@Responses Window title formulas and fields

@Return Toolbar buttons, agents, hotspots, and fields

SELECT Replication formulas, agents, and view selection formulas

@SetDocField Toolbar buttons, agents, action hotspots, and fields

@SetEnvironment All formulas with the exception of popup hotspots

@SetField Toolbar buttons, agents, action hotspots, and fields

@Success Validation formulas

@Unavailable Agents, views, and action buttons

@ViewTitle Agents, action hotspots, and buttons

NOTE

A select number of functions can be called from LotusScript or haveequivalents in LotusScript. Functions are sometimes called fromLotusScript to simplify the code instructions. In other words, a single@Function can often replace multiple LotusScript code. In othercases, there are equivalent functions already included in theLotusScript language.

What Are Commands?

Commands are used to perform an action related to the application interface. For the mostpart, commands mimic menu options and tend to be used primarily in action buttons,hotspots, agents, and events. For example, commands can be used to

• Compose a new form• Edit, save, or close a form• Jump to a field and insert text• Attach a file• Send an email• Open the database help document

What Are Commands? 101

Elliott_05.qxd 9/14/06 2:27 PM Page 101

Page 10: Formula

NOTE

@Commands cannot be called from LotusScript and, with few excep-tions, cannot be implemented in Web-based applications.

The following table represents some of the most frequently used commands. In most cases,these commands would be placed in an action button for a given form.

Command Description Example

FileSave Saves the document currently @Command

displayed in the Lotus Notes ([FileSave]);

client. Syntax:@Command ( [FileSave] );

EditDocument Toggles between edit and read @Command

mode for the currently opened ([EditDocument]; 1)

document. Optionally, if you set the edit mode to 1, the document only goes to edit mode. If the mode is set to 0, the document goes to read mode. Syntax:@Command([EditDocument];

mode; pane)mode—Set to 1 for edit, 0 for readonly.pane—Set to 1 to display in preview pane.

CloseWindow Closes the document currently @Command

open in the Lotus Notes client. ([CloseWindow]);

Syntax:@Command ( [CloseWindow] );

Compose Creates a new document based @Command([Compose];

on the specified form. Syntax: "NewEmployee");

@Command ([Compose]; form );

form—An existing form in the database.

EditGoto Places the cursor in the specified @Command

-Field field on the document. Syntax: ([EditGotoField];

@Command ([EditGotoField]; "Title");

fieldname );

fieldname—Name of a field on a form.

102 Chapter 5 • An Introduction to Formula Language

Elliott_05.qxd 9/14/06 2:27 PM Page 102

Page 11: Formula

Working with Text Strings

Many formulas are used to manage and manipulate text strings. Using functions, you canparse information, implement data validation, and enforce consistency across data values. Forexample, the following are some of the more common functions used to manage text strings.

Function Description Example

@UpperCase Converts a string to @Uppercase ("january" );

uppercase. Syntax: Result: "JANUARY"@UpperCase ( string );

string—Any text string.

@LowerCase Converts a string to @Lowercase ("JANUARY" );

lowercase. Syntax: Result: "january"@LowerCase ( string );

string—Any text string.

@ProperCase Converts the first letter @Propercase ("john doe" );

of each word to a capital. Result: "John Doe"Syntax:@ProperCase ( string );

string—Any text string.

@Trim Removes leading and trailing @Trim ( " today is

spaces from a text string and Monday ");

removes duplicate spaces Result: "today is Monday"between text words. Syntax:@Trim ( string );

string—Any text string.

@Text Converts a number, date, or @Text ( 100 );

time to a text string. Syntax: Result: "100"@Text ( value ); @Text ( @Today );

value—The value to be Result: "01/01/2005"converted into a string.

@LeftBack Searches a string from left to This example returns "Mark".right and returns a substring. @LeftBack ("Mark Elliott"; " ");

This example returns "Mark Ellio".@LeftBack ("Mark Elliott"; 2);

@RightBack Searches a string from This example returns "Elliott".right to left and returns a @RightBack ("Mark Elliott"; " ");

substring. This example returns "rk Elliott".@RightBack ("Mark Elliott"; 2);

Working with Text Strings 103

Elliott_05.qxd 9/14/06 2:27 PM Page 103

Page 12: Formula

Working with Conditional Branching

The primary method to manage conditional branching is the @IF function. As with mostprogramming languages, this function tests an equation and then branches to the appro-priate action. The following describes the syntax for this function.

@IF ( condition; action1; action2 );

If the condition equates to true, then action1 is performed. Otherwise, if the conditionequates to false, then action2 is performed. It’s important to note that you can also nest@IF statements inside @IF statements. For example:

@If (@Created = @Today; "Document created today.";@If (@Created = @Yesterday; "Document created yesterday."; "Document created in

past."));

In this example, the first condition compares the document creation date with today’s date.If the two values match, then the formula executes action1 and returns the text string"Document created today." If the values do not match, then the formula executesaction2, which is the nested @IF statement. Here, the creation date is compared with yes-terday’s date. If the values match, then the formula returns the string "Document createdyesterday." Finally, if the document was not created yesterday, the string is set to"Document created in the past."

Working with Iterative Loops

The following are functions that can be used to manage loops. To implement these func-tions, you must be running Lotus Notes release 6 or greater.

Function Description Example

@For Executes one or more statements while the The following loops through specified condition remains true. After the elements of a keyword fieldeach execution, the condition is rechecked called Options. With eachto verify that the statement remains true. iteration, a counter calledSyntax: cntr is incremented and the@For ( initialize; condition; keyword element is displayed

increment; statement); to the user.initialize—The starting value for the @For(cntr := 1;

loop counter. cntr <=

condition—A true or false condition. @Elements(Options);

increment—A statement that changes cntr := cntr + 1;

the counter. @Prompt([OK]; "Item "

statement—A formula language statement + @Text(cntr) " is ";

to execute. Up to 254 statements can be Options[cntr]))

specified.

104 Chapter 5 • An Introduction to Formula Language

Elliott_05.qxd 9/14/06 2:27 PM Page 104

Page 13: Formula

Function Description Example

@While Executes one or more statements while the The following loops throughspecified condition remains true. Syntax: the elements of a keyword@While ( condition; statement ); field called Options. Eachcondition—A true or false condition. element is displayed and astatement—A formula language statement counter is incremented withto execute. Up to 254 statements can be each loop.specified. cntr := 1;

Note: There is also a @DoWhile statement, @While(cntr <=

which was introduced in release 6. @Elements(Options);

@Prompt([OK]; "Item "

+ @Text(cntr) " is ";

Options [cntr]);

cntr := cntr + 1)

Working with Lookup Functions

Lookup functions are used to retrieve one or more data values from a Notes database. Thedata values can be retrieved from the current or another database. The database can resideon the current or a different Domino server. Lookup functions are quite frequently used topopulate keyword fields or to default computed fields to a specific value.

Function Description Example

@DBColumn Returns a list of values from a view or The following returns a list offolder column. Syntax: values from column number@DBColumn( class : cache ; one for the "By Category"

server : database ; view ; view.columnNumber ) class := "";

class—The type of database being cache := "NoCache";

accessed. server := "";

cache—Specifies if the results should db := "";

be cached. view := "By Category";

server—Server name. Defaults to colnum := 1;

current server if set to "" in the statement. @DBColumn (class:cache;

database—Database name. Defaults to server:db; view;

current database if set to "" in the colnum);

statement.view—The view name or alias name.columnNumber—The column number to return values.

Working with Lookup Functions 105

A.5.1

continues

Elliott_05.qxd 9/14/06 2:27 PM Page 105

Page 14: Formula

Function Description Example

@DBLookup Returns a field value from a specified The following searches the view document in a view or folder. Syntax: "By Last Name" for the key@DBLookup( class : cache; value. If found, it returns the

server : database; view; first name for the document.key; fieldName; keywords ) class := "";

-or- cache := "NoCache";

@DBLookup( class : cache; server := "";

server : database; view; db := "";

key; columnNumber; keywords) view := "By Last Name";

class—The type of database being key := "Elliott";

accessed. fieldName := "firstname";

cache—Specifies if the results should @DBLookup (class:cache;

be cached. server:db; view; key;

server—Server name. Defaults to fieldName);

current server if set to "" in the statement.database—Database name. Defaults to current database if set to "" in the statement.view—The view name.key—Unique key.fieldname—Value to return.columnNumber—The column number to return values.

TIP

Best practices suggest that you should create temporary variables forfunctions that require multiple parameters. This helps with formulareadability and helps ensure that you change the correct parameter ifthe formula needs updates. Otherwise, you’ll need to remember (orlook up) what each parameter means and count semicolons to find theparameter.

Where possible, you should limit the number of lookup functions included on a form.Multiple lookup functions can affect the overall performance of the form.

However, if you need to retrieve multiple field values, consider creating a hidden view. Setthe first column to a unique key (such as a document number). In the second column, cre-ate a formula that contains all data fields separated by a delimiter (such as the tilde ~). Thenusing @DBLookup in conjunction with @Word, you retrieve multiple field values for a singledocument using a single lookup.

106 Chapter 5 • An Introduction to Formula Language

Elliott_05.qxd 9/14/06 2:27 PM Page 106

Page 15: Formula

For example, let’s say you have a service request form that requires the user to select theirimmediate manager. Then, after the user selects a name, the manager’s email address,department name, and phone fields automatically populate with the correct information.In this scenario, you would do the following:

1. Create a form that contains manager name, email, department, and phone number.

2. Create a hidden view, such as (MgrLookup).

3. Set the view formula for column1 to MgrName.

4. Set the view formula for column2 to MgrEmail+"~"+MgrDept+"~"+ MgrPhone.

5. Next, add a hidden, computed field (such as MgrData) to the service request form.Set the field formula to the following @DBLookup formula. This field will store a"~"delimited list of values based on the selected manager name.

Class :=""Cache:=""Host := "";View := "(MgrLookup)";Key := MgrName;Colnum := 2;output := @DbLookup( class : cache ; host ; view ; key ; colnum );@If(@IsError(output);"";@If (MgrName=""; ""; output ))

6. Finally, create the Email, Department, and Phone fields on the service request form.Make each field computed. Using the @Word function, set the field formula for eachrespective field. Be sure the form property is set to Automatically refresh fields.

@Word ( MgrData; "~"; 1);@Word ( MgrData; "~"; 2);@Word ( MgrData; "~"; 3);

Using this approach, three individual field lookups were replaced with one @DBLookupfunction call. Note that Automatically refresh fields can also affect performance if there isa significant number of computed fields on the form.

Working with Dates

The following table summarizes the common functions used to manage dates.

Function Description Example

@Date Translates a series of numbers into a @Date ( 2005; 12; 31);

date value. This function requires a Result: 12/31/2005year, month, and day value to be specified. Syntax:@Date;

Working with Dates 107

continues

Elliott_05.qxd 9/14/06 2:27 PM Page 107

Page 16: Formula

Function Description Example

@Day Returns the day of the month from @Day ( "07/10/2005");

the specified date. Syntax: @Day ( @Today );

@Day ( date ); Result: 10date—Any specified date.

@Month Returns the month from the specified @Month ( "07/10/2005");

date. Syntax: @Month ( @Today );

@Month ( date ); Result: 07date—Any specified date.

@Now Returns the current date and time. @Now;

Syntax: Result: 07/10/2005 9:31:45 AM@Now;

@Today Returns the current date. Syntax: @Today;

@Today; Result: 07/10/2005

@Tomorrow Returns tomorrow’s date. Syntax: @Tomorrow;

@Tomorrow; Result: 07/11/2005

@Weekday Returns the day of the week based on @Weekday ( "07/10/2005" );

the specified date. Returns a number @Weekday ( @Today );

corresponding to the weekday where Result: 1Sunday=1, Monday=2, and so on through Saturday=7. Syntax:@Weekday (date );date—Any specified date.

@Year Returns the current year from the @Year ( "07/10/2005");

specified date. Syntax: @Year ( @Today );

@Year ( date ); Result: 2005date—Any specified date.

@Yesterday Returns yesterday’s date. Syntax: @Yesterday;

@Yesterday; Result: 07/09/2005

Working with Lists

The following are common functions used to manage a list of values.

108 Chapter 5 • An Introduction to Formula Language

Elliott_05.qxd 9/14/06 2:27 PM Page 108

Page 17: Formula

Function Description Example

@Elements Counts the number of items in a list @Elements

and returns a number. Syntax: ("April":"May":"June");

@Elements ( list ); Result: 3list—A list of elements.

@Explode Converts a text string into a list of Data:="April May June";

elements. You can optionally specify a @Explode (Data; " ");

string delimiter. If a string delimiter is Result: "April" : "May" :not specified, the function will default "June"

to a space, semicolon, or comma. Syntax:@Explode ( string );

@Explode ( string; delimiter );

string—A string of text values.delimiter—An optional text string separator.

@Implode Converts a list of elements into a single Data:= "April" : "May" :text string. Optionally, you can specify "June";

a string delimiter. Syntax: @Implode (Data; " ");

@Implode ( list ); Result: "April May June"@Implode ( list; delimiter );

list—a list of elements.delimiter—an optional text string separator.

@IsMember Searches for a value within a text Data:= "April" : "May" :

string. Returns a numeric 1 if found "June";

and 0 if not found. Syntax: @IsMember ("April"; Data);

@IsMember ( string; list ); Result: 1string—The search string.list—A list of elements.

@Replace Searches a list for an element. If the Data:= "April" : "Dec" :

element is found, it is replaced with "June";

the new element. @Replace (Data; "Dec";

@Replace ( searchlist; oldlist; "May");

newlist ); Result: "April": "May":searchlist—The list of elements to "June"

be searched.oldlist—The list of value(s) to be replaced.newlist—The new list of replacement value(s).

Working with Lists 109

continues

Elliott_05.qxd 9/14/06 2:27 PM Page 109

Page 18: Formula

Function Description Example

@Select Returns the value specified in the n-th @Select(3; "April";

number position. If the number "May"; "June")

specified is greater than the total values, Result: "June"then the last value is returned. Syntax:@Select ( number; value1;

value2; valueN);number—Item number to select.value1—First value.value2—Second value.valueN—Last value.

@Word Selects the word specified in the n-th Data:="April~May~June";

number position. Words are determined @Word ( Data; "~"; 3);

based on the string delimiter. Syntax: Result: "June"@Word ( string; delimiter;

number );

string—The string to be searched.delimiter—The value used to separate “words.”number—The word to select from the search string.

Working with User Prompts

The following describes several functions that can be used to display information to theuser. These functions will display a dialog box window. In some cases, information is static.In other cases, the user can interact with the dialog box, and data values are returned to theunderlying form.

Function Description Example

@Dialogbox Displays a user-defined dialog box. In the following example, aResults from the dialog box are form called RepeatOptionssubsequently returned to the is displayed.underlying form. @Dialog box

@DialogBox( form ; style : title ) ( "RepeatOptions";

form—The name of the form to display [AUTOHORZFIT] :

in a dialog box. [AUTOVERTFIT];

style—Optional keyword that indicates "Recurring calendar

what the dialog box should look like. If event");

multiple options are specified, a colon should separate them.

110 Chapter 5 • An Introduction to Formula Language

Elliott_05.qxd 9/14/06 2:27 PM Page 110

Page 19: Formula

Function Description Example

[AUTOHORZFIT]—Auto-set horizontal size.[AUTOVERTFIT]—Auto-set vertical size.[NOCANCEL]—Do not display Cancel button.[NONEWFIELDS]—Do not create new fields on underlying form if the field does not already exist.[NOFIELDUPDATE]—Do not update fields on underlying form.[READONLY]—Disable the ability to edit content in the dialog box.[SIZETOTABLE]—Auto-set size based on the table.[NOOKCANCEL]—Do not display the OK and Cancel buttons on the dialog box.[OKCANCELATBOTTOM]—Place the OK and Cancel buttons at the bottom of the form. If parameter is omitted, buttons will display on right side of window.title—The title of the dialog box window.

@Prompt Displays a popup dialog box to the The following are several user. This function can be used to examples.capture data values or to capture the @Prompt ([OK]; "Warning";

result of a clicked button (i.e., OK or "You must specify a

Cancel). Syntax: request date");

@Prompt( [style] : [ NOSORT ] ; @Prompt ([YESNO];

title ; prompt ; defaultChoice ; "Continue?"; "Do you

choiceList ; filetype ) want to save this

style—A keyword that indicates what form?");

the dialog box should look like. Valid @Prompt ([OKCANCELEDIT];

keywords include the following: "Input"; "What is your

[CHOOSEDATABASE] name?"; );

[LOCALBROWSE] FIELD filename :=

[OK] @Prompt([LOCALBROWSE];

[OKCANCELCOMBO] "Select a file.";"");1

[OKCANCELEDIT]

[OKCANCELEDITCOMBO]

[OKCANCELLIST]

Working with User Prompts 111

continues

Elliott_05.qxd 9/14/06 2:27 PM Page 111

Page 20: Formula

Function Description Example

[OKCANCELLISTMULT]

[PASSWORD]

[YESNO]

[YESNOCANCEL]

NOSORT—An optional keyword. Values are sorted if this parameter is omitted.title—The title of the dialog box window.prompt—The text to be displayed within the dialog box.defaultchoice—The default button or choice in the dialog box.filetype—The type of files to be displayed. This parameter is only required for the [LOCALBROWSE] style.

Debugging Formula Language

Formula Language unfortunately does not provide a user interface that allows developers todebug or examine variables as a formula executes. However, the Designer client does auto-matically check the formula syntax, which in many cases resolves problems with the formula.

So the question then becomes, how do you debug a formula that meets the language syn-tax requirements but that fails to produce the correct result? There are several approaches toconsider—periodically display values as the formula executes (using @Prompt) or periodi-cally check results as the formula executes (using @IfError or @IsError).

Function Description Example

@IfError Returns a null string if the statement is This example produces a invalid. Optionally, you can specify an divide-by-zero error. When thealternate result if the result of formula executes, the IFstatement1 is invalid. Syntax: statement checks the value @IfError ( statement1 ); stored in output. If the value@IfError ( statement1; is invalid, the formula returns

statement2 ); "Math Error". Otherwise, ifstatement1—The statement to be the value is valid, the formulachecked. returns the output.statement2—Optional result to be output := 1/0;

returned if the first statement is invalid. @IfError ( output;

Note that @IfError has been "Math Error");

deprecated in release 7 and is obsolete.

112 Chapter 5 • An Introduction to Formula Language

Elliott_05.qxd 9/14/06 2:27 PM Page 112

Page 21: Formula

Function Description Example

@IsError Checks the statement to determine if This is another example of the result is valid. Function returns a 1 the divide-by-zero error.if valid and 0 if invalid. Syntax: output := 1/0;

@IsError ( statement ); @If( @IsError (output);

statement—Any formula language ""; output);

statement. Alternatively, instead ofreturning a null value, youcould return a message or usethe @Prompt function todisplay an error message.@If( @IsError (output);

"Divide by Zero"; output);

@Prompt See “Working with User Prompts” See the previous.previously.

NOTE

The @IfError function has been deprecated in release 7 and is obsolete.

Links to developerWorks

A.5.1 Polly, Mark. Keyword magic for the Web. IBM developerWorks, October 2003.http://www.ibm.com/developerworks/lotus/library/ls-keyword_pt1/index.html.

Links to developerWorks 113

Elliott_05.qxd 9/14/06 2:27 PM Page 113

Page 22: Formula

Elliott_05.qxd 9/14/06 2:27 PM Page 114