BP208 Fabulous Feats with @Formula

56
BP208 Fabulous Feats with @Formula: IBM Lotus Notes Client, Xpages and Beyond Kathy Brown | Running Notes

description

 

Transcript of BP208 Fabulous Feats with @Formula

Page 1: BP208 Fabulous Feats with @Formula

BP208 Fabulous Feats with @Formula: IBM Lotus Notes Client, Xpages and Beyond

Kathy Brown | Running Notes

Page 2: BP208 Fabulous Feats with @Formula

AgendaWhere to use @Formula

Using @Formula to work with lists

@Formula in XPages

Comparing @Formula to LotusScript

What’s new with @Formula

Some Old, but Cool Tricks

2

Page 3: BP208 Fabulous Feats with @Formula

Where to Use @FormulaActions, buttons, hotspots, etc.Computed valuesHide/when formulaWindow titlesDefault field valuesColumn formulaSection editor

3

Not all @functions can be used in all contexts!

Input validationInput translationView selection formulaXPages!

Page 4: BP208 Fabulous Feats with @Formula

Input ValidationUse @Success to validate the entered data and @Failure to reject the data and

provide a message to the user

@Success will allow the refresh or save of the document to continue

@Failure will cause the refresh or save to fail, and return the cursor to the failed field (if not hidden)

Use @Formula to disallow a single blank entry, or blank entries across several fields

@If (@ThisValue != “”; @Success; @Failure (“Please enter a value.”))

4

Page 5: BP208 Fabulous Feats with @Formula

You can enter @Formula in the input validation event for each field,

Or combine the @Formula in one field to eliminate multiple notifications to the user

@If (( field1 = “” | field2 = “” | field3 = “”); @Failure (“Please enter all of the required fields.”); @Success)

5

More Input Validation

Page 6: BP208 Fabulous Feats with @Formula

Remember that unless you code to prevent it, (@IsDocBeingSaved), every refresh of the document will trigger the input validation event

Irritating if the user refreshes the document before completing the form and every field on the form disallows blank entries

6

Even More Input Validation

Page 7: BP208 Fabulous Feats with @Formula

Requiring a particular value is quite simple@If (@ThisValue > 100; @Failure (“This field cannot contain a value larger

than 100”); @Success)

@Matches or @Length (among other @functions) can be used to check format or particular characters

@If (@Matches (@ThisValue; “{0-9} {0-9} {0-9} {-} {0-9} {0-9} {0-9} {-} {0-9} {0-9} {0-9} {0-9}); @Success; @Failure (“Phone numbers must be in xxx-xxx-xxxx format.”)

7

Still More Input Validation

Page 8: BP208 Fabulous Feats with @Formula

Input TranslationTrim and replace data to make user-entered data more consistent

Translate the data entered into data that is usable by the application

When possible, it is more user-friendly to translate the data rather than fail validation and require the user to re-enter data

8

Page 9: BP208 Fabulous Feats with @Formula

@Trim does just what it says, it trims any extra white spaces from text or a text list

It does not remove tabs or new lines

9

@Trim

Page 10: BP208 Fabulous Feats with @Formula

@ProperCase and @LowerCase convert text or text lists to either proper case or lower case, respectively

@LowerCase is particularly useful for making user-entered data consistent before checking for a specific value

Three different users may enter “San Antonio,” “SAN ANTONIO,” and “san antonio”

Lower case text is preferred for internationalization

10

@ProperCase and @LowerCase

Page 11: BP208 Fabulous Feats with @Formula

@ReplaceSubstring and @Replace are very powerful @functions

Essentially they provide find and replace functionality on strings or lists of stringssymbols := “!” : “@” : “#” : “$” : “%” : “^” : “&” : “*” : “+” : “=”;result := @Trim (@ReplaceSubstring (field1; symbols; “”))

@ReplaceSubstring (@ThisValue; “\” ; “/”)

@ReplaceSubstring (@ThisValue; @NewLine; “ ”)

11

@ReplaceSubstring

Page 12: BP208 Fabulous Feats with @Formula

Numbers can be tricky in Domino development, particularly during multiplication and division

3.3*3.3 = 10.893.33333*3.33333 = 11.11

Use @Round to make decimal placing consistentNote that @Round works differently than the Round function in

LotusScript@Round(10.555; 0.1) = 10.6Round(10.555, 1) = 10.6

12

@Round

Page 13: BP208 Fabulous Feats with @Formula

@Random generates a random number between 0 and 1

Use the following formula to create a randomly generated number between x and y

(y – x) * @Random + x

Help file!

13

@Random

Page 14: BP208 Fabulous Feats with @Formula

@ThisValue can be used in field formula to get the value of that field

@ThisName provides the name of the current field

No Hard Coding!

Re-use code!

Can’t be used outside of field formula

Can’t be used in a hide formula

14

@ThisValue and @ThisName

Page 15: BP208 Fabulous Feats with @Formula

@SetEnvironment can set or create a variable in the user’s notes.ini file (or Notes Preferences on a Mac)

Use @Environment to get the variable value from the notes.ini file

@SetEnvironment and @Environment cannot be used in column or selection formula, or on the Web

Oddly, a text list can be provided for the variableName parameter, and the same value will be assigned to all the listed variableNames, but …

If a text list is provided for the value parameter, only the first value is used, the rest are ignored

@SetEnvironment and @Environment can be useful for setting user preferencesFor example, a user location can be set and then provided as a default value

to make entry easier for the user

15

@SetEnvironment and @Environment

Page 16: BP208 Fabulous Feats with @Formula

Fantastic Feat #1Include the following formula in the Target Frame (single click) event in the

embedded view:@SetEnvironment( "eViewSelection"; @Text(@DocumentUniqueID))

Include the following LotusScript in a button on the form where the embedded view resides:

…selectedDocIDString = session.GetEnvironmentString("$eViewSelection", False)…Set selectedDocID = db.GetDocumentByUNID(selectedDocIDString)

16

Page 17: BP208 Fabulous Feats with @Formula

@Adjust allows you to adjust a given date value by second, minute, hour, day, month, and/or year

If more than one segment of the date value needs to be adjusted, @Adjust is easier than the LotusScript equivalent, as each value needs to be adjusted individually in LotusScript

Adjust by more than just a number@Adjust (aDate; 0; 0; - (@Weekday(aDate) – 1; 0; 0; 0) evaluates to the

Sunday before the given date

17

@Adjust

Page 18: BP208 Fabulous Feats with @Formula

@Text@Text isn’t just for converting values to a string

The power of @Text comes in the second parameter, the format string@Text (someDate; “D0S0”) provides a date with the month, day, and year, and

no timeMany of the LotusScript functions associated with date are reliant on the

system format

Several number formats are also available including currency and percentage

18

Page 19: BP208 Fabulous Feats with @Formula

View Selection FormulaTwo problems with the view selection formula are the inability to use @DbLookups

and the best practice of avoiding @Today@DbLookups just won’t work in view selection formula@Today is a poor practice due to the drag on performance

Hard coding values is a poor practice workaround!

LotusScript (and formula) to the rescue!

19

Page 20: BP208 Fabulous Feats with @Formula

View Selection Formula (cont.)@AllDescendents versus @IsResponseDoc

Use @AllDescendents in view selection formula@AllDescendents retrieves only those documents that are responses to

the documents included in the view@IsResponseDoc retrieves all response documents in the application and

checks them against the docs in the view

See Andrew Pollack’s blog for more information, including view index size comparisons

20

Page 21: BP208 Fabulous Feats with @Formula

AgendaWhere to use @Formula

Using @Formula to work with lists

@Formula in XPages

Comparing @Formula to LotusScript

What’s new with @Formula

Some Old, but Cool Tricks

21

Page 22: BP208 Fabulous Feats with @Formula

Working with ListsNote that many of the previous @functions also work on lists of values, not just

individual values

Now we’ll cover a few more @functions that are particularly useful when working with lists

22

Page 23: BP208 Fabulous Feats with @Formula

@Unique@Unique has two very different, very useful functions depending on the

parameters@Unique with no parameters provides a random, unique

text value@Unique when given a text list as a parameter, will return the list with

duplicate values removed

23

Page 24: BP208 Fabulous Feats with @Formula

@Transform@Transform takes three parameters

The list to transformA variable nameThe formula for transforming the list

@Transform (@ThisValue; “x”; @If (x>0; x*60; 0) )This example takes a list of values, checks to see if each item in the

list is greater than 0. If it is the value is multiplied by 60, if not, then 0 is returned.

The return value is a list that has been transformed by the formula

24

Page 25: BP208 Fabulous Feats with @Formula

@Transform (cont.)@Transform can utilize @Nothing

@Nothing is only available in @Transform@Transform (@ThisValue; “x”; @If (x>0; x*60; @Nothing) )

A great use of @Transform is changing the decimal place on a list of valuesFor example, a list of values meant to be percentages shown as 50, needs to

be transformed to 0.50@Transform (@ThisValue; “x”; @If (x>1; x/100; @ThisValue) )

25

Page 26: BP208 Fabulous Feats with @Formula

@Sort@Sort is an incredibly powerful @function

Particularly if you use the [CUSTOMSORT] keyword

Take a multi-value field with a list of names:“John Smith” : “Jane Doe” : “Kathy Brown”

How can you sort by last name?@sort (list; [CUSTOMSORT]; @If (@Word ($A; “ ”; 2) < @Word ($B; “ ”; 2);

@False; (@Word ($A; “ ”; 2) > @Word ($B; “ ”; 2); @True; @False))Essentially, a custom sort formula, using $A and $B as temporary

variablesUse any formula you can imagine for the custom sort function!

26

Page 27: BP208 Fabulous Feats with @Formula

@Max and @Min@Max will provide the maximum value in a list of values

Likewise @Min provides the minimum value in a list of values

Additionally, each will provide the maximum of a pair-wise list of values

List1 := 1 : 2 : 3 : 4List2 := 5 : 6 : 0 : 1

@Max (List1; List2) will return 5 : 6 : 3 : 4

27

Page 28: BP208 Fabulous Feats with @Formula

Fantastic Feat #2 @For(n := 1; n <= @ Elements (customers); n := n + 1;

cdate := @DbLookup(“”:””; “”:””; “aView”; customers[n]; “dueDate”;details := @Text(@Year(cdate)) + “~” + @Text(@Month(cdate)) + “~” + @Text

(@Day(cdate)) + “~” + @DbLookup(“”:””; “”:””; “aView”; customers[n]; 5));

details := @Min(details);

details

28

Page 29: BP208 Fabulous Feats with @Formula

@MatchesAn earlier example showed @Matches as a way of validating format for a field

entry

Several wildcard characters are available for @Matches

Lists can be passed in as both the parameter to be checked, and the parameter containing the pattern for which to check

29

Page 30: BP208 Fabulous Feats with @Formula

@Matches (cont.)

30

Symbol /Pattern Use /Matches

C Where C is any character. Matches any single, non-special character C (or c)? Matches any single character* Matches any string (any number of characters){ABC} Matches any character in set ABC{A-FL-R} Matches any character in the sets A...F and L..R+C Matches any number of occurrences of C (or c)ABC The three-character string [a|A][b|B][c|C]{ABC}{ABC} Any two-character string composed of capital letters A, B, or CA?C Any three-character string that starts with a|A and ends with c|C??? Any three-character string+? Any string, including the null string+?{A-Z} Any string that ends in a capital letter+{!A-Z} Any string that does not contain a capital letter

Page 31: BP208 Fabulous Feats with @Formula

@Contains@Contains is similar to @Matches in that either parameter passed in can be a

string or a string list

@Contains can return a true value if the first parameter contains the second parameter, but is not an exact match

Use the “=” operator or @IsMember for exact matches

31

Page 32: BP208 Fabulous Feats with @Formula

AgendaWhere to use @Formula

Using @Formula to work with lists

@Formula in XPages

Comparing @Formula to LotusScript

What’s new with @Formula

Some Old, but Cool Tricks

32

Page 33: BP208 Fabulous Feats with @Formula

@Formula in XPagesXPages are now available in Domino 8.5.x

@Formula is available to use in Server Side JavaScript (SSJS)

Not all @Formula are supported in XPages

33

Page 34: BP208 Fabulous Feats with @Formula

@Formula in XPages (cont.)Three syntactic changes to use @Formula in XPages:

Use commas rather than semicolonsUse exact case

Example:var uname = @Name(“[CN]”, @UserName())

“null” should be used in place of 0 for formulas such as @AdjustExample:

var adate = @Adjust (@Created(), null, null, 5, null, null, null)

34

Page 35: BP208 Fabulous Feats with @Formula

@Formula in XPages (cont.)Help file is not very helpful!

@Name(“[CN]”, name) – needs those quotes! But there is no example in the help file to demonstrate that!

@UserName() – needs those parentheses! Again, no example in the help file to show that!

35

Page 36: BP208 Fabulous Feats with @Formula

@Functions Not Supported in XPages

@AbstractSimple @CheckAlarms @DeleteField @DoWhile

@Accessed @CheckFormulaSyntax @DialogBox @EditECL

@ACos @Command @DocChildren @EditUserECL

@AddToFolder @Compare @DocDescendants @EnableAlarms

@AdminECLIsLocked @ConfigFile @DocFields @Environment

@All @Cos @DocLength @Eval

@AllChildren @DB2Schema @DocLevel @Exp

@AllDescendants @DbCommand @DocLock @FileDir

@Ascii @DbExists @DocMark @FloatEq

@ASin @DbManager @DocNumber @FontList

@ATan @DDEExecute @DocOmmittedLength @For

@ATan2 @DDEInitiate @DocParentNumber @FormLanguage

@BrowserInfo @DDEPoke @DocSiblings @GetAddressBooks

@BusinessDays @DDETerminate @DocumentUniqueID @GetCurrentTimeZone

@Certificate @DeleteDocument @Domain @GetDocField

36

Page 37: BP208 Fabulous Feats with @Formula

@Functions Not Supported in XPages (cont.)

@GetFocusTable @IsDocBeingRecalculated @Locale @OrgDir

@GetHTTPHeader @IsDocTruncated @Log @Password

@GetIMContactListGroupNames@IsEmbeddedInsideWCT @MailDbName @PasswordQuality

@GetPortsList @IsExpandable @MailEncryptSavedPreference @Pi

@GetProfileField @IsInCompositeApp @MailEncryptSentPreference @PickList

@GetViewInfo @IsModalHelp @MailSavePreference @Platform

@HardDeleteDocument @IsUsingJavaElement @MailSend @PolicyIsFieldLocked

@HashPassword @IsValid @MailSignPreference @PostedCommand

@InheritedDocumentUniqueID @IsVirtualizedDirectory @Matches @Power

@IsAgentEnabled @Keywords @NameLookup @Prompt

@IsAppInstalled @LanguagePreference @Narrow @RefreshECL

@IsCategory @LaunchApp @NoteID @RegQueryValue

@IsDB2 @LDAPServer @Nothing @Responses

@IsDocBeingEdited @Like @OpenInNewWindow @ServerAccess

@IsDocBeingMailed @Ln @OptimizeMailAddress @ServerName

37

Page 38: BP208 Fabulous Feats with @Formula

@Functions Not Supported in XPages (cont.)

@Set @TemplateVersion @URLHistory @ViewTitle

@SetDocField @ThisName @URLOpen @WebDbName

@SetEnvironment @ThisValue @UrlQueryString @WhichFolders

@SetHTTPHeader @TimeMerge @UserAccess @While

@SetProfileField @TimeToTextInZone @UserNameLanguage @Wide

@SetTargetFrame @TimeZoneToText @UserNamesList @Zone

@SetViewInfo @ToNumber @UserPrivileges DEFAULT

@ShowParentPreview @ToTime @UserRoles ENVIRONMENT

@Sign @Transform @V2If FIELD

@Sin @Unavailable @V3UserName REM

@Sort @UndeleteDocument @V4UserAccess SELECT

@Soundex @UpdateFormulaContext @ValidateInternetAddress

@Sqrt @URLDecode @VerifyPassword

@StatusBar @URLEncode @Version

@Tan @URLGetHeader @ViewShowThisUnread

38

Page 39: BP208 Fabulous Feats with @Formula

AgendaWhere to use @Formula

Using @Formula to work with lists

@Formula in XPages

Comparing @Formula to LotusScript

What’s new with @Formula

Some Old, but Cool Tricks

39

Page 40: BP208 Fabulous Feats with @Formula

@Formula vs. LotusScriptMany @functions have LotusScript equivalents

Check the Help file for language cross-referenceEspecially check Help file for each language for additional examples

Check the Help file for differences in parameters, syntax, and where the function can be used

Some @Formula do not have LotusScript equivalents

Some @Formula require less code and/or perform faster than LotusScript equivalents

40

Page 41: BP208 Fabulous Feats with @Formula

Use the Evaluate method in LotusScript to have access to @Formula

Only use it when it makes sense, like for @DbLookup or other @Formula that don’t have equivalent LotusScript methods

Dim results as variantresults = Evaluate ( { @Trim (@Unique (tempList))})

Most frequent problem is choosing the right delimiters and keeping them organized within the formula

results = Evaluate {“@IsMember (‘Joe’; ‘Joe’ : ‘Jane’ : ‘Jen’)”}

41

Evaluate using @Formula in LotusScript

Page 42: BP208 Fabulous Feats with @Formula

@MailSend is a great example of @Formula having more functionality over LotusScript equivalents

@MailSend acts like Send method of NotesUIDocument

However, @MailSend has more parameters, including flags!

42

@MailSend

Page 43: BP208 Fabulous Feats with @Formula

val := @Sort (TextList);@SetField (“textListOutput”; val)

vs.

Calls a script library!

@Sort vs LotusScript

Page 44: BP208 Fabulous Feats with @Formula

AgendaWhere to use @Formula

Using @Formula to work with lists

@Formula in XPages

Comparing @Formula to LotusScript

What’s new-ish with @Formula

Some Old, but Cool Tricks

44

Page 45: BP208 Fabulous Feats with @Formula

@WhichFoldersShows in which folders a particular document resides

Currently not that useful, only available in view column formula

From the IBM help file: “The function is effective only when the view is open in the UI and the outline pane on the left is visible”

But, someday ... ?

45

Page 46: BP208 Fabulous Feats with @Formula

@AbstractSimpleCreates an abstract of a text or rich text field

Must save the document before using

Returns the first 100 characters or first two paragraphs, whichever is smaller

Useful for searching rich text fields for certain strings of text

Less complex than @Abstract, no keywords, size, or beginning text requiredConsequently @AbstractSimple is more efficient than @Abstract

46

Page 47: BP208 Fabulous Feats with @Formula

New @Commands@Command [CopySelectedAsTable]

Functions the same as Edit--> Copy As… --> TableUseful for creating a button to streamline user experience in views where

users would typically copy the data

@Command [OpenInNewWindow]Causes a document selected within a view, folder, or calendar to be opened in

a new windowValuable when a new window would aid the user, such as comparing one

document to another

@Command [CalendarFormat]Added two new formats

Two work-week displayOne work-month display

47

Page 48: BP208 Fabulous Feats with @Formula

AgendaWhere to use @Formula

Using @Formula to work with lists

@Formula in XPages

Comparing @Formula to LotusScript

What’s new with @Formula

Some Old, but Cool Tricks

48

Page 49: BP208 Fabulous Feats with @Formula

Fantastic Feat #3!Data := [some field with a text string];

src := @Explode(Data; " ");

digits := (0:1:2:3:4:5:6:7:8:9);

digitsRev := (9:8:7:6:5:4:3:2:1:0);

numList := @Subset(((digits*+digits)*+digits); @Elements(src));

numListRev := @Subset(((digitsRev*10)*+digitsRev); -@Elements(src));

targList := @Text(numList) + @Char(250) + src;

@Word(@Replace(@Text(numListRev); @Text(numList); targList); @Char(250); 2)

49

Page 50: BP208 Fabulous Feats with @Formula

Complicated Functionality, Uncomplicated @FunctionsPrior code uses seven @functions

@Explode@Subset@Elements@Text@Char@Word@Replace

All seven are backwards compatible to Version 3!

Most important, using the building blocks of @Formula, you can create incredibly complex code

50

Page 51: BP208 Fabulous Feats with @Formula

Everything Old Is New AgainFormula debugger?

No, not really, but …You can place @Prompts throughout your code to see values as you goYou can write values to other fields to see @Formula values as you goFor simple @Formula, you can use the subject line of a memo and press

SHIFT+F9

51

Page 52: BP208 Fabulous Feats with @Formula

ResourcesAndrew Pollack’s entry on @AllDescendents vs. @IsResponseDoc

www.thenorth.com/apblog4.nsf/0/6DF6AAD2521ADF9185257647005E9539Andrew’s session, IBM Lotus Domino Server & Application Performance in the

Real World,

White paper on using Evaluatewww.ibm.com/developerworks/lotus/library/ls-The_Evaluate_

statement/index.html

Niklas Waller’s entry on @SetEnvironment to access a doc in an embedded viewwww.wohill.com/design/266/Get-selected-document-from-embedded-view.html

IBM Lotus Notes Documentation Lotus Domino Designer 8.5 Lotus Domino Designer XPages Reference Guide JavaScript language elements @Functions

http://bit.ly/FormulaMap

Lotus Domino Application Development wiki - www-10.lotus.com/ldd/ddwiki.nsf

52

Page 53: BP208 Fabulous Feats with @Formula

Bonus FeatREM {Get a Date};

dateString := @Prompt([OkCancelEdit]; "Enter a Date"; "Please enter a date below:"; "mm/dd/yyyy");

REM {Convert the date to a Julian Day.};m := @TextToNumber(@Word(dateString; "/"; 1));d := @TextToNumber(@Word(dateString; "/"; 2));y := @TextToNumber(@Word(dateString; "/"; 3));

y := @If(m <= 2; y - 1; y);m := @If(m <= 2; m + 12; m);

c := 2 - @Integer(y / 100) + @Integer(y / 400);jd := @Integer(1461 * (y + 4716) / 4) + @Integer(153 * (m + 1) / 5) + d + c - 1524.5;

53

Page 54: BP208 Fabulous Feats with @Formula

REM {Determine which synodic month we're in, using an average length of 29.53 days per synodic month.};k := (jd - 2451550.09765) / 29.530588853;

REM {The fractional value of k is how far along in the synodic month this day is. The full moon should come exactly halfway through the synodic month, so if the fractional value is 0.5 then today should be a full moon.};moonPhase := "Nothing special";fraction := @Round(k - @Integer(k); 0.01);moonPhase := @If(fraction >= 0.99 | fraction <= 0.01; "New Moon"; moonPhase);moonPhase := @If(fraction >= 0.24 & fraction <= 0.26; "First Quarter"; moonPhase);moonPhase := @If(fraction >= 0.49 & fraction <= 0.51; "Full Moon"; moonPhase);moonPhase := @If(fraction >= 0.74 & fraction <= 0.76; "Last Quarter"; moonPhase);

@Prompt([Ok]; "Moon Phase"; "date = " + dateString + @NewLine +"jd = " + @Text(jd) + @NewLine +"k = " + @Text(k) + @NewLine +"fraction = " + @Text(fraction) + @NewLine +"Moon Phase = " + moonPhase)

54

Page 55: BP208 Fabulous Feats with @Formula

Your Turn!Kathy Brown

@kjbrown13 on Twitter

[email protected]

www.runningnotes.net

@NotesDevTips on Twitter

Don’t Forget Your Evaluations!

55

Page 56: BP208 Fabulous Feats with @Formula

56

Legal Disclaimer© IBM Corporation 2011. All Rights Reserved.

The information contained in this publication is provided for informational purposes only. While efforts were made to verify the completeness and accuracy of the information contained in this publication, it is provided AS IS without warranty of any kind, express or implied. In addition, this information is based on IBM’s current product plans and strategy, which are subject to change by IBM without notice. IBM shall not be responsible for any damages arising out of the use of, or otherwise related to, this publication or any other materials. Nothing contained in this publication is intended to, nor shall have the effect of, creating any warranties or representations from IBM or its suppliers or licensors, or altering the terms and conditions of the applicable license agreement governing the use of IBM software.

References in this presentation to IBM products, programs, or services do not imply that they will be available in all countries in which IBM operates. Product release dates and/or capabilities referenced in this presentation may change at any time at IBM’s sole discretion based on market opportunities or other factors, and are not intended to be a commitment to future product or feature availability in any way. Nothing contained in these materials is intended to, nor shall have the effect of, stating or implying that any activities undertaken by you will result in any specific sales, revenue growth or other results.

IBM, the IBM logo, Lotus, Lotus Notes, Notes, Domino, Quickr, Sametime, WebSphere, UC2, PartnerWorld and Lotusphere are trademarks of International Business Machines Corporation in the United States, other countries, or both. Unyte is a trademark of WebDialogs, Inc., in the United States, other countries, or both.