Tải bản đầy đủ - 0 (trang)
Chapter 8. Getting Started with Calculations

# Chapter 8. Getting Started with Calculations

Tải bản đầy đủ - 0trang

UnderstandingHowandWhereCalculationsAre

Used

Calculationfunctionsareamongthemostimportantand

powerfultoolsatyourdisposalinthedevelopmentofFileMaker

Prosolutions.Somepeoplefindlearningcalculationstobean

tobedaunting.Whichevercampyoufallinto,calculationswill

FileMakerweencourageyoutostickwithit.Ourhopeisthatthis

Techniques,"willprovideyouasolidgrounding.

Thischapterfocusesonbasiccalculationfunctionsand

techniquesforusingthemwell.Chapter14looksatmore

newtoFileMaker,youshouldstarthere.Thosewhohavebeen

usingFileMakerforyearsmaywanttojustskimthischapter.

(Thereareprobablyafewnuggetsofinformationthatwillmake

itworthyourwhile.)We'vealsoincludedacompletefunction

referenceinourcompanionbook,FileMaker8Functionsand

ScriptsDeskReference.Thatbookisintendedtoserveasa

referencewhenyouneedtolookupspecificinformation.Here,

wetakemoreofatutorialapproachandexplorehowandwhy

oneemployscalculations.

Fromtheoutset,it'simportanttounderstandthedifference

betweencalculationfieldsandcalculationformulas.Theterm

calculationisoftenusedambiguouslytodenotebothconcepts

("Thattablehasmorethan100calculations!"or"What'sthe

calculationusedtodetermineaccesstothisrecord?").

Calculationfieldsareaparticulartypeoffieldwhosevalueis

determinedthroughtheevaluationofacalculationformula.

ofaformulatodetermineanoutput.Whenyoulearn

"calculations,"you'rereallylearningcalculationformulas.Itso

happensthatyou'llusecalculationformulastoconstruct

calculationfields,buttheformulasareappliedwidely

throughoutFileMakersolutions.

WritingCalculationFormulas

Essentially,thepurposeofacalculationformulaistoevaluate

anexpressionandreturnavalue.InFigure8.1,forexample,

youcanseethefielddefinitionforacalculationfieldcalled

MileageCalc.Thevalueofthisfieldisdefinedtobetheresultof

multiplyingthecontentsoftheMileagefieldby.37,whichisa

typicalmileagereimbursementrate.

Figure8.1.Whendefiningcalculationfields,you

specifyanexpressiontoevaluateintheSpecify

Calculationdialog.

[Viewfullsizeimage]

Mostoftheexpressionsyouuseincalculationformulasare

intendedtoreturnavalue,andthatvaluemightbeanumber,a

inacontainerfield.Anotherclassofformulas,however,is

intendedtoevaluatetheveracityofanequationorstatement.

Thevaluereturnedbytheseformulasiseithera1,indicating

thattheequationorstatementistrue,or0,indicatingthatthe

equationorstatementisfalse.Typically,calculationsareusedin

thismannerinIfscriptsteps,incalculatedvalidations,andfor

definingfieldaccessrestrictions.

WorkingwithFields,"p.67.

InFigure8.2,forinstance,youcanseeacalculationdialogthat

specifiestheconditionforanIfscriptstep.Whenthescript

executes,FileMakerevaluateswhetherthenumberofhoursis

infactgreaterthan8(basedonthecurrentrecord'sdata).

DependingonthevalueoftheHoursfieldforanyparticular

record,thestatementmaybeeithertrueorfalseandthescript

willpresumablyreactaccordingly.

Figure8.2.Calculationformulasareoftenusedto

determinethetruthfulnessofanequationora

statement.

[Viewfullsizeimage]

Forcertainuses,then,thepurposeofacalculationformulaisto

returnavalue;forotherusesit'ssimplytoevaluatethe

veracityofanequationorstatement.Insituationsinwhich

FileMakerisexpectingaformulathatreturnsatrue/falseresult,

youseethewordsCalculationresultmustbeBooleannearthe

bottomofthecalculationdialog.TheIfscriptstepshownearlier

isatypicalexampleofthissituation.Booleanisasoftware

programmingtermforavaluewithoneoftwostates:trueor

false.Anyvaluereturnedotherthan0oranullvalue(for

example,anemptystring)isconsideredtrue.

Note

NotethatBooleanrulesapplyfortextvalues,dates,

negativenumbers,andsoon."Hello"istrue(not

zeroandnotnull),asinglespacecharacter("")is

true,and-1istrue.Notealsothattheresultsofa

formulaareevaluatedinthesameway:(0*100)is

false.(0+100)istrue.Last,alsonotethatyoucan

usecomparativeoperators:1and1istrue(where

eachclauseonbothsidesoftheandoperator

evaluatetotrue),1or1istrue,1xor1isfalse,and

chapter.

Caution

TheGetAsBoolean()functiontreatsalldataasnumeric,

suchthat,forexample,"hello"evaluatesasfalseand

"hello999"evaluatesastrue.Thisisaninconsistency

withthewayinwhichotherBooleanlogicoperates,

sobesuretotakenoteofit.

UsesforCalculationFormulas

Thischapterfocusesontheuseofcalculationformulasinfield

definitions,butit'simportantthatyouunderstandthatthere

areotherplaceswherecalculationformulasareusedaswell.

Briefly,theseincludethefollowing:

ScriptstepsCalculationformulascomeintoplayinmany

scriptsteps.TheIf,SetField,andSetVariablescriptsteps

arenotableexamples.Manyotherscriptstepsallowyouto

useacalculationformulatoactasaparameter.Asampling

includesGotoLayout,GotoField,GotoRecord,Pause/Resume

canbeusedtodefinescriptparametersandscriptresults.

FieldvalidationOneoftheoptionsavailabletoyoufor

validatingdataentryisvalidatingbycalculation.This,in

effect,letsyoudefineyourownrulesforvalidation.For

weekday,orperhapsthatastatusfieldnotallowavalueof

"complete"ifthereisdatamissingelsewhereinarecord.

Theequationyouprovideisevaluatedeverytimeauser

modifiesthefield.Ifitevaluatesastrue,theuser'sentryis

committed.Ifitdoesn't,theuserispresentedwithanerror

message.Forinstance,ifauserissupposedtoentera

callbackdateonacontactrecord,youmightwantto

validatethattheentryisafuturedate.Todothis,you

mightusetheformulaCall_Back_Date>Get(CurrentDate)as

thevalidationfortheCall_Back_Datefield.

Record-levelsecurityWhenyoudefineprivilegesets,you

havetheoptionoflimitingauser'saccesstoview,edit,and

deleterecordsbasedonacalculationformulayouprovide.

Iftheequationyouprovideevaluatesastrue,theusercan

performtheaction;ifnot,theactionisprohibited.For

instance,youmightwanttopreventusersfrom

posted.Soyou'dsetuplimitedaccessforeditingrecords

basedontheformulaInvoice_Status "Posted".Onlyrecords

forwhichthatisatruestatementwouldbeeditable.

Auto-entryoptionsWhenyou'redefiningtext,number,

date,time,andtimestampfields,severalauto-entryoptions

areavailableforspecifyingdefaultfieldvalues.Oneofthese

optionsistoauto-entertheresultofacalculationformula.

Forinstance,inacontactmanagementdatabase,youmight

Theformulayou'duseforthismightbesomethinglikeGet(

CurrentDate)+14,ifyouwantedacallbackdatetwoweeksin

thefuture.

CalculatedreplaceAcalculatedreplaceisawayof

changingthecontentsofafieldinalltherecordsinthe

currentfoundset.It'sparticularlyusefulforcleaningup

sometimesenteredspacesattheendofanamefieldas

theyweredoingdataentry.Youcouldcleanupthisdataby

performingacalculatedreplacewiththeformulatrim(First

Name).

ExploringtheCalculationDialogBox

formulasareused,it'stimetoturnnexttothelayoutofthe

calculationdialogboxitself.Therearesomesmalldifferences

amongthecalculationdialogsyoufindinparticularareaswithin

FileMakerPro.We'llfocusourattentiononthedialogusedfor

definingcalculationfieldsbecauseit'sthemostcomplex.Figure

8.3showsthecalculationdialogforafieldcalledFullName,

whichservesasthemodelforthisanatomylesson.

Figure8.3.Whenyou'recreatingcalculation

fields,ithelpstoknowyourwayaroundthe

SpecifyCalculationdialogbox.

[Viewfullsizeimage]

SpecifyingContext

fromwhichtoevaluatethiscalculation.Thischoiceisnecessary

onlywhenthesourcetableyouareworkingwithappearsin

yourRelationshipsGraphmorethanonce.Andeveninthose

cases,itreallymattersonlywhenyourcalculationformula

involvesrelatedfields.Insuchcases,thecalculationmayreturn

differentresults,dependingonthecontextfromwhichit's

evaluated.

Tomakethispointclear,considertheexampleinFigure8.4.

Figure8.4.NoticethattheTransactiontable

occurrencehastworelatedparenttable

occurrencesderivedfromthesamesourcetable

ofPerson.

[Viewfullsizeimage]

foragiventransaction.Thismeansthenthatapersonrecord

willhavepotentiallytwosetsofrelatedtransactions:thosefor

whichthatpersonisaseller,andthoseforwhichheorsheisa

tablethatproducedatotaloftransactions,you'dgetvery

differentresultsdependingonfromwhichcontextyoucalculate.

BothversionsofthecalculationwoulduseaSUM(

Transaction::Amount)formula,buttheoriginatingcontextwill

perspectiveorthesellerperspective.Inthisexample,it's

criticalthattheoriginatingcontextbesetdeliberatelyinorder

todeterminewhichtransactionsgettotaled.

WritingtheFormula

ThelargeboxinthemiddleoftheSpecifyCalculationdialogis

whereyoudefinetheformulaitself.Ifyouknowthesyntaxof

thefunctionsyouneedandthenamesofthefields,youcan

cases,though,you'llwanttousethelistsoffieldsandfunctions

abovethetextbox.Double-clickingonaniteminthoselists

insertsthatitemintoyourformulaatthecurrentinsertion

point.

Note

OnaMacintosh,afteranitemishighlighted,youcan

alsopressthespacebartoinsertitintoyour

formula.OnWindows,theInsertkeyfunctions

similarly.

fields,constants,operators,andfunctions.Allthefollowingare

examplesofformulasyoumightwrite:

2+2

FirstName&""&LastName

Get(CurrentDate)+14

Left(FirstName;1)&Left(LastName;1)

"Dear"&FirstName&":"

\$loopCounter=\$loopCounter+1

LastName="Jones"

Intheseexamples,FirstNameandLastNamearefields.