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

easytask,whereasotherscanfindwritingcomplexcalculations

tobedaunting.Whichevercampyoufallinto,calculationswill

enableyoutounlockmuchoftheadvancedpowerwithin

FileMakerweencourageyoutostickwithit.Ourhopeisthatthis

chapteranditscompanion,Chapter14,"AdvancedCalculation

Techniques,"willprovideyouasolidgrounding.

Thischapterfocusesonbasiccalculationfunctionsand

techniquesforusingthemwell.Chapter14looksatmore

advancedcalculationformulasandspecifictechniques.Ifyou're

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.

Calculationformulaisabroaderconceptthatreferstoanyuse

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

textstring,adateortime,orevenareferencetoafiletoplace

inacontainerfield.Anotherclassofformulas,however,is

intendedtoevaluatetheveracityofanequationorstatement.

Thevaluereturnedbytheseformulasiseithera1,indicating

thattheequationorstatementistrue,or0,indicatingthatthe

equationorstatementisfalse.Typically,calculationsareusedin

thismannerinIfscriptsteps,incalculatedvalidations,andfor

definingfieldaccessrestrictions.

Tolearnmoreaboutfieldvalidation,seeChapter3,"Definingand

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

soon.You'lllearnaboutoperatorslaterinthe

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

Script,andOmitMultiple.Additionally,calculationformulas

canbeusedtodefinescriptparametersandscriptresults.

FieldvalidationOneoftheoptionsavailabletoyoufor

validatingdataentryisvalidatingbycalculation.This,in

effect,letsyoudefineyourownrulesforvalidation.For

example,youmightwanttotestthataduedatefallsona

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

inadvertentlymodifyinganinvoicethathasalreadybeen



posted.Soyou'dsetuplimitedaccessforeditingrecords

basedontheformulaInvoice_Status "Posted".Onlyrecords

forwhichthatisatruestatementwouldbeeditable.

Auto-entryoptionsWhenyou'redefiningtext,number,

date,time,andtimestampfields,severalauto-entryoptions

areavailableforspecifyingdefaultfieldvalues.Oneofthese

optionsistoauto-entertheresultofacalculationformula.

Forinstance,inacontactmanagementdatabase,youmight

wantadefaultcallbackdatesetforallnewcontactrecords.

Theformulayou'duseforthismightbesomethinglikeGet(

CurrentDate)+14,ifyouwantedacallbackdatetwoweeksin

thefuture.

CalculatedreplaceAcalculatedreplaceisawayof

changingthecontentsofafieldinalltherecordsinthe

currentfoundset.It'sparticularlyusefulforcleaningup

messydata.Say,forexample,thatyourusershad

sometimesenteredspacesattheendofanamefieldas

theyweredoingdataentry.Youcouldcleanupthisdataby

performingacalculatedreplacewiththeformulatrim(First

Name).







ExploringtheCalculationDialogBox

Nowthatyouknowsomethingabouthowandwherecalculation

formulasareused,it'stimetoturnnexttothelayoutofthe

calculationdialogboxitself.Therearesomesmalldifferences

amongthecalculationdialogsyoufindinparticularareaswithin

FileMakerPro.We'llfocusourattentiononthedialogusedfor

definingcalculationfieldsbecauseit'sthemostcomplex.Figure

8.3showsthecalculationdialogforafieldcalledFullName,

whichservesasthemodelforthisanatomylesson.



Figure8.3.Whenyou'recreatingcalculation

fields,ithelpstoknowyourwayaroundthe

SpecifyCalculationdialogbox.



[Viewfullsizeimage]



SpecifyingContext

Acrossthetopofthedialog,you'reaskedtospecifythecontext

fromwhichtoevaluatethiscalculation.Thischoiceisnecessary

onlywhenthesourcetableyouareworkingwithappearsin

yourRelationshipsGraphmorethanonce.Andeveninthose

cases,itreallymattersonlywhenyourcalculationformula

involvesrelatedfields.Insuchcases,thecalculationmayreturn

differentresults,dependingonthecontextfromwhichit's

evaluated.

Tomakethispointclear,considertheexampleinFigure8.4.



Figure8.4.NoticethattheTransactiontable

occurrencehastworelatedparenttable

occurrencesderivedfromthesamesourcetable

ofPerson.



[Viewfullsizeimage]



Inthisexample,apersoncanactaseitherabuyeroraseller

foragiventransaction.Thismeansthenthatapersonrecord

willhavepotentiallytwosetsofrelatedtransactions:thosefor

whichthatpersonisaseller,andthoseforwhichheorsheisa

buyer.IfyouweretocreateacalculationfieldinthePerson

tablethatproducedatotaloftransactions,you'dgetvery

differentresultsdependingonfromwhichcontextyoucalculate.

BothversionsofthecalculationwoulduseaSUM(

Transaction::Amount)formula,buttheoriginatingcontextwill

determinewhetheryou'reviewingrecordsfromthebuyer

perspectiveorthesellerperspective.Inthisexample,it's

criticalthattheoriginatingcontextbesetdeliberatelyinorder

todeterminewhichtransactionsgettotaled.



WritingtheFormula



ThelargeboxinthemiddleoftheSpecifyCalculationdialogis

whereyoudefinetheformulaitself.Ifyouknowthesyntaxof

thefunctionsyouneedandthenamesofthefields,youcan

simplygoaheadandtypeintheformulabyhand.Inmost

cases,though,you'llwanttousethelistsoffieldsandfunctions

abovethetextbox.Double-clickingonaniteminthoselists

insertsthatitemintoyourformulaatthecurrentinsertion

point.



Note

OnaMacintosh,afteranitemishighlighted,youcan

alsopressthespacebartoinsertitintoyour

formula.OnWindows,theInsertkeyfunctions

similarly.



Everycalculationformulaismadeupofsomecombinationof

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.

$loopCounterisavariablebyvirtueofbeingprefixedwithadollarsigncharacter.Get(CurrentDate)andLeftarefunctions.Theonly

operatorsusedherearetheadditionoperator(+)andthe



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 8. Getting Started with Calculations

Tải bản đầy đủ ngay(0 tr)

×