Building Forms I
Building Forms I
Building Forms I
BuildingFormsI
Chapter15
WorkingwithTriggers
IntroductiontoFormTriggers*
DefinitionofaTrigger*
FormTriggerCategories*
Exercises*
FormTriggerTypesandScope*
Exercises*
FormTriggerProperties*
PropertyName*
Exercises*
HowtoProduceTriggers*
WritingTriggerCode*
Exercises*
UnderstandingtheUseofBuiltInSubprograms*
RestrictedandUnrestrictedBuiltIns*
Exercises*
IntroductiontotheWhenWindowClosedTrigger*
Exercises*
AddingFunctionalitytoFormItems*
SupplementingtheFunctionalityofInputItems*
Exercises*
SupplementingtheFunctionalityofNoninputItems*
Exercises*
UsingQueryTriggers*
DataBlockQueryProcessandTriggers*
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
1/20
19/6/2015
BuildingFormsI
Exercises*
WritingTriggersThatScreenQueryConditions*
Exercises*
WritingTriggerstoSupplementQueryResults*
Exercises*
DebuggingTriggers*
RunningaFormModuleinDebugMode*
Exercises*
UnderstandingtheComponentsoftheDebugger*
Exercise*
DebuggingPL/SQLCode*
Exercises*
ChapterSummary*
TwoMinuteDrill*
Inthischapter,youwillunderstandanddemonstrateknowledgeinthefollowingareas:
Introductiontoformtriggers
Howtoproducetriggers
Addingfunctionalitytoformitems
Usingquerytriggers
Debuggingtriggers
TriggersarethebreadandbutterofyourworkcreatingaFormBuilderapplication.Youhavealready
workedbrieflywithtriggersinpriorchaptersofthisbook.Nowitistimeforaformalintroduction.You
willstartbylearningabouttriggercategories,types,scope,andproperties.Next,youwilllearnhowto
producetriggersforavarietyofdifferentobjects,utilizingtriggerspecificcomponentsand
subprograms.Youwillpracticeaddingfunctionalitytoformitemsbyattachingtriggerstothem,andsee
howyoucanexertgreatercontroloverqueryresultsbyemployingquerytriggers.Then,youwillbe
learnhowtousetheformDebugger,whichcanprovidemajorassistancewhenyouneedtotrackdown
misbehavingcode.Thecontentsofthischapterrepresentsabout22percentofOCPExam3test
content.
IntroductiontoFormTriggers
Inthissection,youwillcoverthefollowingpointsrelatedtoformtriggers:
Definitionofatrigger
Formtriggercategories
Formtriggertypesandscope
Formtriggerproperties
InthissectionyouwilllearnaboutthenumerouscategoriesoftriggersFormBuilderoffersbe
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
2/20
19/6/2015
BuildingFormsI
introducedtothetwoformtriggertypeslearnhowtocontrolatriggersscopeandseeallofaform
triggersproperties.
DefinitionofaTrigger
AtriggerisablockofPL/SQLcodethataddsfunctionalitytoyourapplication.Triggersareattachedto
objectsinyourapplication.Whenatriggerisactivated,orfired,itexecutesthecodeitcontains.Each
triggersnamedefineswhateventwillfireitforinstance,aWHENBUTTONPRESSEDtrigger
executesitscodeeachtimetheuserclicksonthebuttontowhichthetriggerisattached.
FormTriggerCategories
ThetriggersmostcommonlyusedinFormBuilderfallintoseveralfunctionalcategories.Thereare
blockprocessingtriggerssuchasONDELETE,interfaceeventtriggerslikeWHENBUTTON
PRESSED,master/detailtriggerssuchasONPOPULATEDETAILS,messagehandlingtriggerslike
ONMESSAGE,navigationaltriggerssuchasWHENNEWFORMINSTANCE,querytimetriggerslike
POSTQUERY,transactionaltriggerssuchasPREINSERT,andvalidationtriggerslikeWHEN
VALIDATEITEM.Mostofthetriggersyoudealwithwillfallintothecategoryofinterfaceeventtriggers.
ThesefireastheuserinteractswithyourapplicationsGUI.Eachtimetheuserclicksonabutton,
choosesfromalist,orchangesaradiogrouporcheckbox,aseriesoftriggersisavailabletocontrol
theapplicationsresponse.
InterfaceeventtriggersgenerallyhavenamesfittingtheformatWHENobjectaction.Forinstance,list
triggersincludeWHENLISTACTIVATEDandWHENLISTCHANGED.Fortriggersthatfirewhena
newinstanceofanobjectiscreated,theformatWHENNEWobjectINSTANCEprevails.Forinstance,
ifyouwantedtoestablishcertainsettingswhenaparticularformopens,butdidnotwantthe
applicationtobotherreestablishingthosesettingsjustbecausetheusernavigatedoutoftheformand
thencamebackintoit,thetriggerWHENNEWFORMINSTANCEwoulddothetrick.Therearealso
quiteafewtriggersformouseevents,suchasWHENMOUSECLICK,WHENMOUSEDOUBLE
CLICK,WHENMOUSEDOWN,WHENMOUSEUP,WHENMOUSEENTER,andWHENMOUSE
LEAVE.Inaddition,thereareover40triggerstorespondtokeystrokestheseusethenamingformat
KEYkeytype.ExamplesincludeKEYDOWN,KEYUP,KEYF1,KEYENTER,andaveryuseful
addition,KEYOTHERS.TheKEYOTHERStriggerfireswhenevertheuserpressesakeythatcan
haveatriggerbutdoesnot.Itisanexcellentwaytodisableunwantedfunctionkeys,ortoperformone
ormoreactionseachtimetheuserpressesanykey.
Exercises
1. WhatarethemostcommontriggercategoriesinFormBuilder?
2. IfyouseeatriggernamedWHENCHECKBOXCHANGED,whatcategorydoesthetriggerfall
into?
3. Whattriggerwouldfireeachtimeanewrecordiscreated?
4. WhatisthepurposeoftheKEYOTHERStrigger?
FormTriggerTypesandScope
Triggerscanalsobedividedaccordingtotheirtriggertypeandtriggerscope.Therearetwotypesof
triggers:builtinandusernamed.Builtintriggerscorrespondtospecificruntimeeventsandare
suppliedwithFormBuilder.UsernamedtriggersarenotprovidedwithFormBuildertheyarewritten
bydeveloperslikeyou,andtheirnamescanbewhateveryou,thedeveloper,desire.Usernamed
triggersarerequiredonlyinspecialsituations,andtheycanonlyberunusingthe
EXECUTE_TRIGGERbuiltinprocedurefromwithinausernamedsubprogram,builtintrigger,or
menuitemcommand.
Atriggersscopedefineswhateventmustoccurinorderforthetriggertofireasaresult.Thetrigger
scopeisusuallydeterminedbytheobjecttowhichitisattached:itsscopeencompassestheobject
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
3/20
19/6/2015
BuildingFormsI
itself,andanysmallerobjectscontainedtherein.Forinstance,ifyoudefinedaWHENNEWITEM
INSTANCEtriggerforasingleitemonacanvas,thetriggerwouldfirewhenevertheusernavigatedto
thatitem.Ifyoumovedthetriggertoablock,itwouldfireeachtimetheusernavigatedtoanyitemin
theblock.Movethesametriggerfartheruptoaformlevel,anditwouldfirewhentheusernavigatedto
anyiteminanyoftheformsblocks.
Exercises
1. Whatisthedifferencebetweenabuiltintriggerandausernamedtrigger?
2. Whatismeantbyatriggers"scope?"Whatdeterminesatriggersscope?
FormTriggerProperties
Triggershaverelativelyfewproperties.Thismakessenseforanobjectwhoseverynamedefineswhen
itoperates,andwhosecodecontentdefineswhatitdoes.Table151showsthetriggerpropertiesand
whattheydo.
Property
NodeGeneral
Name
NameofthistriggerasitappearsintheObject
Navigator.
General
Subclass
Information
Allowsyoutosubclassthistriggerunderanotherin
ordertosimplifychangingglobalproperties.
General
Comments
Developercommentsabouttrigger.
Functional
TriggerStyle
AllowsyoutoselectbetweenaPL/SQLtriggerand
aV2styletrigger.Thelatterisavailableonlyfor
compatibilitywithpreviousversions,anditisnot
recommended.
Functional
TriggerText
ContainsaMorebuttonthatopensthePL/SQL
Editorforenteringandeditingthetriggerscode.
Functional
FireinEnter
QueryMode
Specifieswhethertriggershouldfireiftheformisin
EnterQuerymode.Onlyapplicablefortriggers
relatedtoactionsthatarevalidinEnterQuery
mode.
Functional
Execution
Hierarchy
Ifahigherlevelobjectcontainsatriggerwiththe
samename,thispropertydefineswhetherthis
triggershouldoverridethehigherlevelone(the
default),executebeforeit,orexecuteafterit.
Help
Displayin
KeyboardHelp
UsefulonlyforKEYtriggers,specifieswhethera
descriptionofthetriggerwillappearinthelist
producedbytheFormsRuntimeprogramsHelp|
Keysmenucommand.
Help
KeyboardHelp
Text
TexttodisplayforakeytriggerintheruntimeKeys
helpscreen.
Table1:TriggerProperties
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
4/20
19/6/2015
BuildingFormsI
Exercises
1. Whichpropertycontrolshowatriggerinteractswithothertriggers?
2. Whichpropertycontrolswhatactionsatriggerwillperform?(Hint:Thisisatrickquestion.)
HowtoProduceTriggers
Inthissection,youwillcoverthefollowingpointsaboutproducingtriggers:
Writingtriggercode
Understandingtheuseofbuiltinsubprograms
IntroductiontotheWHENWINDOWCLOSEDtrigger
Thissectioncoversthebasicsofwritingtriggercode.Itstartswithanoverviewofthecomponentsyou
canuseinatriggercodeblock.ItthenintroducesthebuiltinsubprogramsthataresuppliedwithForm
Builder.Itwrapsupwithanexerciseinwhichyouuseabuiltinsubprogramwithinaformtrigger.
WritingTriggerCode
TriggersconsistofPL/SQLcodeblocks.Thestructureoftheseblockswillbefamiliarifyouhave
completedthefirsttwounitsofthisbook.(Ifyouhavenotyetworkedthroughthoseunits,besuretodo
sotheinformationtheycontainisessentialtoyoursuccessasaDeveloper/2000developer.)Trigger
codecancontainadeclarationsection,acodesection,andanerrortrappingsection.Inaddition,there
aremanynewsystemvariablesenablingyoutoascertainandcontrolfacetsoftheclient/server
environmentprovidedbyFormBuilderthesearelistedinTable152.Therearealsomany,many
objectpropertiesthatyoucanreadandsetusingPL/SQLcode.Forinstance,youcouldchangethe
backgroundcolorofaniteminresponsetoaneventbyplacingcodelikethisintheeventstrigger:
DECLARE
ITEM_IDitem
BEGIN
ITEM_ID:=find_item('NET_EARNINGS')
set_item_property(ITEM_ID,visual_attribute,'GREEN_TEXT_GROUP')
END
Inaddition,therearemanybuiltinpackagescontainingPL/SQLconstructsyoucanreferenceinyour
owncode.ExamplesincludeCLEAR_ITEM,whichclearsatextitemscurrentvalue,and
GET_FILE_NAME,whichcausesanfileopendialogboxtodisplayandreturnsinformationaboutthe
fileselectedtotheroutinethatcalledit.Thenextsectioncoversbuiltinsingreaterdetail.Asyouwork
throughthischapterandthechaptersthatfollow,youwillhavemanyopportunitiestoexpandyour
triggerwritingskills.
SYSTEM.BLOCK_STATUS
SYSTEM.COORDINATION_OPERATION
SYSTEM.CURRENT_BLOCK
SYSTEM.CURRENT_DATETIME
SYSTEM.CURRENT_FORM
SYSTEM.CURRENT_ITEM
SYSTEM.CURRENT_VALUE
SYSTEM.CURSOR_BLOCK
SYSTEM.CURSOR_ITEM
SYSTEM.CURSOR_RECORD
SYSTEM.CURSOR_VALUE
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
SYSTEM.MESSAGE_LEVEL
SYSTEM.MODE
SYSTEM.MOUSE_BUTTON_PRESSED
SYSTEM.MOUSE_BUTTON_SHIFT_STATE
SYSTEM.MOUSE_ITEM
SYSTEM.MOUSE_CANVAS
SYSTEM.MOUSE_X_POS
SYSTEM.MOUSE_Y_POS
SYSTEM.MOUSE_RECORD
SYSTEM.MOUSE_RECORD_OFFSET
SYSTEM.RECORD_STATUS
5/20
19/6/2015
BuildingFormsI
SYSTEM.DATE_THRESHOLD
SYSTEM.EFFECTIVE_DATE
SYSTEM.EVENT_WINDOW
SYSTEM.FORM_STATUS
SYSTEM.LAST_QUERY
SYSTEM.LAST_RECORD
SYSTEM.MASTER_BLOCK
SYSTEM.SUPPRESS_WORKING
SYSTEM.TAB_NEW_PAGE
SYSTEM.TAB_PREVIOUS_PAGE
SYSTEM.TRIGGER_BLOCK
SYSTEM.TRIGGER_ITEM
SYSTEM.TRIGGER_RECORD
Table2:FormBuilderSystemVariables
Exercises
1. WhatfeaturescanyouutilizeasyouwritetriggercodeinFormBuilder?
2. Whataresystemvariables?
UnderstandingtheUseofBuiltInSubprograms
Inadditiontosystemvariablesandobjectproperties,therearemanybuiltinsubprograms,alsoknown
asbuiltins,containingPL/SQLconstructsyoucanuseinyourowntriggerandsubprogramcode.Form
Buildercomeswithhundredsofbuiltins,andtheyarealwaysavailableforusewithinyourcode.
ExamplesincludenavigationalfunctionssuchasNEXT_ITEM,NEXT_RECORD,orNEXT_BLOCK,as
wellasprogrammingconvenienceslikeGET_FILE_NAME,whichgeneratesafileopendialogboxand
returnsinformationabouttheselectedfiletoitscallingroutine.ThebuiltinsprovidedwithFormBuilder
aregroupedbyfunctionintopackages.YoucanviewthebuiltinpackagesintheObjectNavigatorby
openingtheBuiltInPackagesnode.Table153showsthepackagesandtheirfunctionalareas.
BuiltInPackage
Name
DDE
Debug
List
OLE2
Ora_FFI
Ora_NLS
Ora_Prof
PECS
Standard
Extensions
Standard
PackageSpec
Text_IO
Tool_Env
Tool_Err
Tool_Res
VBX
Web
FunctionalArea
DynamicDataExchangesupportforDeveloper/2000components
Procedures,functions,andexceptionsfordebuggingPL/SQLprogramunits
Procedures,functions,andexceptionsforcreatingandmaintaininglistsof
characterstrings
PL/SQLAPIforcreatingandmanipulatingattributesofOLE2automationobjects
Publicinterfacetocallforeign(C)functionsfromPL/SQL
Extractshighlevelinformationaboutyourcurrentlanguageenvironment
Procedures,functions,andexceptionsfortuningPL/SQLprogramunits
ToolstoutilizeFormBuildersPerformanceEventCollectionServicesmeasuring
resourceusage
CoreFormBuilderbuiltinssuchasCALL_FORMandCREATE_RECORD
Comparison,number,text,date,record,andlogicaloperatorssuchas>=,
BETWEEN,DECODE,LTRIM,ADD_MONTHS,CHARTOROWID,andXOR
Supportforreadingandwritinginformationfromandtofiles
ToolstointeractwithOracleenvironmentvariables
Allowsyoutomanipulateerrorstackcreatedbyotherbuiltinpackages
ExtractsstringresourcesfromaresourcefileinordertomakePL/SQLcodemore
portable
UtilizeVBXcomponentsinforms
UtilityforWebapplications
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
6/20
19/6/2015
BuildingFormsI
Table3:BuiltInPackages
Youhavealreadyusedbuiltinswhiledoingthisbooksexercises.Forinstance,whenyoucreateda
formtodisplayimagesyouincludedabuttonemployingtheGET_FILE_NAMEbuiltintolettheuser
specifyagraphicsfiletobeloaded.Forreminderssake,thecodeusedisshownhere:
declare
v_dirnamevarchar2(255)
v_filenamevarchar2(255)
begin
v_dirname:='C:\'
v_filename:=get_file_name(v_dirname,NULL,
'Bitmapfiles(*.bmp)|*.bmp|'||
'JPEGfiles(*.jpg)|*.jpg|')
ifv_filenameisnotnullthen
read_image_file(v_filename,'ANY','av_data_image.blob_data')
endif
end
ThiscodealsousedtheREAD_IMAGE_FILEbuiltintoloadtheselectedimagefileintothe
applicationscurrentrecordmemory.BothofthesebuiltinsarepartoftheStandardExtensions
package.Whenyouuseabuiltinfromapackageotherthanthestandardpackages,youmust
precedeitsnamewiththenameofthepackageforinstance,WEB.SHOW_DOCUMENT.
RestrictedandUnrestrictedBuiltIns
BecausesomeofthebuiltinsprovidedintheStandardExtensionspackagearedesignedtocause
navigation,apotentialproblemexists:whatifadeveloperwritesatriggerinresponsetoanavigation
event,andthetriggercontainsabuiltingeneratinganothernavigationeventcausingtheoriginal
triggertofireagain?Thissortofcircularreferencemistakewouldcausetheapplicationtohang,andit
canhappenwithdatabasetransactionsaswellasnavigationevents.Tokeepthisfromhappening,
FormBuilderprohibitsnavigationtriggersfromcontainingbuiltinsthatmoveinputfocusorinvolve
databasetransactions.TheserestrictedbuiltinscannotbecalledfromPREandPOSTtriggers,
becausethesetriggersfirewhiletheusernavigatesfromoneitemtoanother.Examplesofrestricted
builtinsincludeCLEAR_FORM,COMMIT_FORM,DELETE_RECORD,DOWN,ENTER,GO_ITEM,
andNEXT_ITEM,amongothers.
Tip:Triggernameshavehyphensbetweenthewords,and
builtinsubprogramnameshaveunderscoresbetweenthe
words.Thisisahandythingtorememberwhiletakingthe
certificationexam,becausesomequestionsaskabout
triggersandoffersomeanswerscontainingunderscores,or
askaboutbuiltinsubprogramsandoffersomeanswers
containinghyphens.Keepingtheirrespectivenaming
conventionsstraightwillhelpyoueliminateanswersthat
areinthewrongcategoryaltogether.
Exercises
1. Whatisabuiltinsubprogram?Abuiltinpackage?
2. Whatnamingconventionmustbeobservedwhencallingbuiltinsfrompackagesotherthanthe
Standardpackages?
3. Whyaresomebuiltinsclassifiedasrestricted?Whatistherestrictionthatisenforced?
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
7/20
19/6/2015
BuildingFormsI
IntroductiontotheWhenWindowClosedTrigger
TheWHENWINDOWCLOSEDtriggerfireswhenevertheuseremploysthewindowmanagerClose
commandtocloseawindow.Tocreateone,openyourSOUND_MODULEapplication.IntheObject
Navigator,opentheWindowsnodeandchangethenameoftheapplicationsonlywindowto
SOUND_WINDOW.Then,gobackuptothetopoftheObjectNavigatorandselecttheTriggersnode
directlybeneaththemodulename.ClickontheCreatebutton,selecttheWHENWINDOWCLOSED
trigger,andclickontheOKbutton.EnterthefollowingcodeinthePL/SQLEditorforthetrigger:
message('ExecutingtheWHENWINDOWCLOSEDtrigger.Preparingtoclose
form',ACKNOWLEDGE)
exit_form
Compilethecode,closethePL/SQLEditor,andrunyourapplication.Whentheapplicationopensin
theFormsRuntimeprogram,clickontheWindowsClosebuttoninthetoprightcornerofyourform
window.(ThetriggerdoesnotfireifyouusetheClosebuttonintheouterMDIwindow,ortheAction|
Exitmenucommand.)Youshouldseeadialogboxappearthatlookssimilartotheoneshownin
Figure151.ClickonthedialogboxsOKbuttontoreturntoFormBuilder.
Figure1:DialogboxfromWHENWINDOWCLOSEDtrigger
AkeyfacttorememberabouttheWHENWINDOWCLOSEDtriggeristhatitisnotattachedtoa
window.Why?LookintheObjectNavigatorwithintheWindowsnodeforyourmodule.Seeanytrigger
subnodes?Nowindowsdonothavetriggers.Soyouhavetogoupalevel,attachingtheWHEN
WINDOWCLOSEDtriggerattheformlevel,whereitwillfirewhenanywindowinthemoduleis
closed.Becauseofthis,itiscommontohavetheWHENWINDOWCLOSEDtriggercontainanif
statementthatselectsthetriggersactionsbasedonwhichwindowsclosingfiredthetrigger.An
exampleofthis,fromthed2khelp.fmbdemofileprovidedwithDeveloper/2000,follows:
if:system.event_window='WIN_REL_TOPICS'
then
trt_hlp.hide_topics
elseif:system.event_window='WIN_EXAMPLE'
then
trt_hlp.hide_example
else
do_key('exit_form')
endif
Exercises
1. WhendoestheWHENWINDOWCLOSEDtriggerfire?
2. AtwhatlevelshouldaWHENWINDOWCLOSEDtriggerbeplaced?Why?
AddingFunctionalitytoFormItems
Inthissection,youwillcoverthefollowingpointsaboutaddingfunctionalitytoitemsonyourforms:
Supplementingthefunctionalityofinputitems
Supplementingthefunctionalityofnoninputitems
ThestudyofthetriggersandbuiltinsubprogramsFormBuilderoffersforitsinputandnoninputitems
islikelytobeanongoingprocessinyourlifeasadeveloper.Hereisanoverviewthatwillhelpyou
understandtheforestasyoulearnaboutthetrees.
SupplementingtheFunctionalityofInputItems
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
8/20
19/6/2015
BuildingFormsI
Allinputitemscanhavetriggersattachedtothem.Becauseofthenatureoftheirfunctionaccepting
datainputitemscommonlyhavetriggersthatfirewhentheuserarrivesontheitem,leavestheitem,
orchangestheitemsdata.AnyinputitemcanhaveaWHENNEWITEMINSTANCEtriggerthat
executeseachtimetheuserlandsontheitem,aswellasaWHENVALIDATEITEMtriggercontaining
codetodeterminewhetherthecontententeredbytheusersatisfiesyourintegrityconstraints.Input
itemsthatfunctionbyhavingtheuserchangetheirstateratherthanenteravaluemeaningallinput
itemsexcepttextitemscanhavetriggersthatfirewhentheircontentschangetheformatusedin
thosetriggersnamesisWHENitemtypeCHANGED.Table154showsthecommontriggersforeach
typeofinputitem.
ItemType
CommonTriggers
TextItem
WHENVALIDATEITEM
WHENNEWITEMINSTANCE
PRETEXTITEM
POSTTEXTITEM
CheckBox
WHENVALIDATEITEM
WHENNEWITEMINSTANCE
WHENCHECKBOXCHANGED
RadioButton
WHENVALIDATEITEM
WHENNEWITEMINSTANCE
WHENRADIOCHANGED
Poplist
WHENVALIDATEITEM
WHENNEWITEMINSTANCE
WHENLISTCHANGED
TList
WHENVALIDATEITEM
WHENNEWITEMINSTANCE
WHENLISTCHANGED
ComboBox
WHENVALIDATEITEM
WHENNEWITEMINSTANCE
WHENLISTCHANGED
ListofValues
(LOV)
WHENVALIDATEITEM
WHENNEWITEMINSTANCE
WHENLISTCHANGED
Table4:CommonTriggersforInputItems
Inputitemtriggerscanincludebuiltinstoenhancetheirfunctionality.Therearebuiltinstomanipulate
data,suchasCLEAR_ITEM,CLEAR_RECORD,ADD_LIST_ELEMENT,DELETE_LIST_ELEMENT,
INSERT_RECORD,DELETE_RECORD,ENTER_QUERY,andEXECUTE_QUERY.Therearealso
builtinstomovetheinputfocus,suchasGO_ITEM,GO_RECORD,GO_BLOCKNEXT_ITEM,
NEXT_RECORD,NEXT_BLOCKandPREVIOUS_ITEM,PREVIOUS_RECORD,and
PREVIOUS_BLOCK.Inaddition,therearebuiltinstoopenspecificitems,suchasSHOW_EDITOR
andSHOW_LOV,aswellasbuiltinstocontrolanitemsavailability,likeDISABLE_ITEMand
ENABLE_ITEM.ThesebuiltinsoperatelikeaPL/SQLfunction,expectingspecificinputparameters
whentheyarecalled.
Exercises
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
9/20
19/6/2015
BuildingFormsI
1. Describethedifferencebetweenatriggerandabuiltin.
2. Whattriggerwouldyouusetostorecodethatshouldfirewhenaradiogroupsvalueismodified
bytheuser?
3. Whichbuiltinwillcauseaneditortodisplay?
SupplementingtheFunctionalityofNoninputItems
Likeinputitems,noninputitemscanbeaugmentedwithtriggers.Table155showsthecommon
triggersforeachtypeofnoninputitem.
ItemType
CommonTriggers
Boilerplatetext
Notapplicable
DisplayItem
Notapplicable
Image
WHENNEWITEMINSTANCE
WHENIMAGEPRESSED
WHENIMAGEACTIVATED
Sound
Available,butnotriggersarespecificallydesignedforsounditems
PushButton
WHENNEWITEMINSTANCE
WHENBUTTONPRESSED
Icon
WHENNEWITEMINSTANCE
WHENBUTTONPRESSED
Table5:CommonTriggersforNoninputItems
Noninputitemtriggerscanalsoemploybuiltinstoenhancetheirfunctionality.Anoninputitemtrigger
canemployanybuiltinusedforaninputitem,aswellasmanyotherbuiltinsthatcontrolinterface
elements.ExamplesincludeCALL_FORMandCLOSE_FORM,ENTER_QUERYand
EXECUTE_QUERY,OPEN_FORMandEXIT_FORM,andGET_TAB_PAGE_PROPERTYand
SET_TAB_PAGE_PROPERTY.YoumayalsofindusefulnessinGET_BLOCK_PROPERTY,
GET_CANVAS_PROPERTY,andGET_FORM_PROPERTYSET_BLOCK_PROPERTY,
SET_CANVAS_PROPERTY,andSET_FORM_PROPERTYSHOW_PAGE,SHOW_VIEW,
SHOW_WINDOWHIDE_PAGE,HIDE_VIEW,andHIDE_WINDOWandSHOW_MENU,
HIDE_MENU,andEXIT_MENU.
Exercises
1. Whichnoninputitemscanyouassigntriggersto?
2. Whatbuiltinwouldyouusetochangeatabpagesname?
UsingQueryTriggers
Inthissection,youwillcoverthefollowingpointsaboutquerytriggers:
Datablockqueryprocessandtriggers
Writingtriggersthatscreenqueryconditions
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
10/20
19/6/2015
BuildingFormsI
Writingtriggerstosupplementqueryresults
Believeitornot,asinglequerycanfireoverhalfadozentriggers.ThereisareasonthatOracle
Corporationexpendedtheefforttoofferthismanypointsatwhichyoucaninserttriggercode:control.
Querytriggersallowyoutoexertanenormousamountofcontroloverthequeriesyourapplication
generates,bothbeforetheyarecreatedandaftertheirdataresultshavebeenreturned.Inthissection
youwilllearnhowtoutilizequerytriggers.
DataBlockQueryProcessandTriggers
Aqueryseemslikeasimpleprocess:youidentifywhatmustbetrueabouttherecordsyouwantto
see,andOraclefetchesthemforyou.WhenthisisdoneviaaDeveloper/2000application,additional
layersofactionsareaddedrelatingtothepresenceofauserinterface.Thefirstgroupofactionsfalls
underthecategoryenteringthequery.WhentheuserinitiatesaqueryintheFormsRuntimeprogram,
theprogramstartsbycheckingwhetherthedatablocktheuserisinhasitsQueryAllowedpropertyset
toYes.Ifso,itcheckstoseeiftheblockcontainsanyitemswhoseQueryAllowedpropertyisalso
Yes.Ifso,theFormsRuntimeprogramallowstheusertoutilizeEnterQuerymodetoenterquery
conditions.TheFormsRuntimeprogramthentakesthequeryconditionsenteredbytheuserinEnter
Querymodeandaddswhateverconditionswerepreviouslyplacedinthedatablockswhereclause
property(thispropertycanbechangedbyatriggeratruntime,asyouwillsoonsee).TheForms
Runtimeprogramalsoappendsanyorderingspecificationsyouhaveplacedinthedatablocksorder
byclauseproperty(whichcanalsobechangedprogrammaticallyatruntime).
Thenextstageisexecutingthequery.Here,theFormsRuntimeprogramonceagaincheckswhether
thedatablocksQueryAllowedpropertyissettoYes(itdoesthisagainbecausethispointcanbe
reachedbyothermeans).Oncethatsucceeds,itnavigatestotherelevantdatablock,validatesany
recordsthatarentvalidated,andpromptstheusertosaveanyunsavedchanges.Finally,itopensthe
query.Ifthereareresultingrecords,itfetchestherecords,limitingtheirquantitytothenumber
specifiedintheblocksQueryArraySizepropertyifthepropertyissettoavalueotherthanzero.
Inadditiontoperformingtheactionsjustdescribed,Developer/2000hastheabilitytofireavarietyof
triggersduringtheprocessoffulfillingaquery.Forinstance,thereareprequeryandpostquery
triggersthatyoucanattachtoblocksorforms.Theseusuallyareattachedtoablock,wheretheycan
exertsuchcontrolasspecifyingadditionalwherecolumnconditions(viaaprequerytrigger)and
settingvaluesinfetchedrecordsbeforeshowingtherecordstotheuser(viaapostquerytrigger).To
giveyouamorecompletepictureofwhenquerytriggersfire,Table156showstheorderinwhich
querytriggersandactionsexecute.Wheneveratriggerisonthesamelineasanaction,theForms
Runtimeprogramchecksforthepresenceofthetriggerfirst,andifthetriggerexists,itisfiredandthe
correspondingactiondoesnotoccur.
Production:Pleaseformatlefthandcolumnassubheadings.
Stage
EnterQuery
Triggers
ExecuteQuery
Actions
Checkwhetherqueryisallowedondatablock
Checkwhetherdatablockcontainsanyqueryable
items
AcceptusersqueryconditionsviaEnterQuery
mode
Checkwhetherqueryisallowedondatablock
Navigatetoblock
Validateunvalidatedrecords
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
11/20
19/6/2015
BuildingFormsI
Prompttocommitunsavedchanges
FirePREQUERYtrigger
Checkwhethertheblockhasabasetable
Buildselectstatement
FirePRESELECTtrigger
FireONSELECTtrigger
FirePOSTSELECTtrigger
FireWHENCLEARBLOCK
trigger
Executeselectstatement
Flushexamplequeryrecordfromblock
FetchRecords
Checkwhetherbufferalreadycontainsfetched
rowsnotyetplacedindatablockifso,usethose
rowsandskiptoPOSTCHANGEtrigger
FireONFETCHtrigger
Fetchonerecord,orquantityspecifiedinQuery
ArraySizeproperty
Placecursoratfirstrecordinbuffer
FirePOSTCHANGEtrigger
Markrecordanditemsasvalid
FirePOSTQUERYtrigger
onceforeachrecord
Looptofetchnextrecord
Table6:ChronologyofQueryActionsandTriggers
Exercises
1. Whatarethethreemajorstepsintheprocessofqueryingadatablock?
2. AtwhatobjectlevelarePREQUERYandPOSTQUERYtriggersmostoftenattached?
3. DoesthePREQUERYtriggerfirebeforeoraftertheuserenterscriteria?DoesthePOST
QUERYtriggerfirebeforeorafterrecordsareshowntotheuser?
4. Inwhattriggerwouldyouplacecodetocheckwhethertheuserspecifiedcriteriaforanindexed
itembeforerunningthequery?
WritingTriggersThatScreenQueryConditions
ThePREQUERYtriggergivesyoutheabilitytocheckaqueryenteredbytheuserbeforethatqueryis
executed,andmodifyorstopthequeryifyouwish.Forinstance,youcanuseaPREQUERYtriggerto
ensurethattheusersqueryincludesatleastonecolumnthathasanindex,inordertomaximizequery
turnaroundspeedandminimizeserverworkload.YoucanalsouseaPREQUERYtriggertocontrol
howreturnedrecordsaresorted,aswellastoapplyadditionalwhereclausecriteriabeforethequery
isprocessed.
Topracticethis,youwillmodifyyourDEPARTMENTcanvassoitletsuserschoosewhethertosort
departmentsbyDEPARTMENT_IDorDEPARTMENT_NAME.Openyouroriginalsampleapplication,
clickontheDataBlocksnode,andclickontheCreatebutton.SelectBuildanewdatablockmanually
andclickontheOKbutton.ChangethenewblocksNamepropertyto
DEPARTMENT_SORT_CONTROLandchangeitsDatabaseDataBlockpropertytoNotomakeita
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
12/20
19/6/2015
BuildingFormsI
controlblock.IntheObjectNavigator,clickontheblocksItemsnode,followedbytheCreatebutton.
ChangetheitemsnametoSORT_SELECT,itsItemTypepropertytoRadioGroup,itsInitialValueto
DEPARTMENT_ID,anditsCanvaspropertytoDEPARTMENT.BackintheObjectNavigator,clickon
theSORT_SELECTitemsTriggersnode,clickontheCreatebutton,selecttheWHENRADIO
CHANGEDtrigger,andenterthefollowingcodeinthePL/SQLEditor:
go_block('DEPARTMENT')
execute_query
CompilethetriggercodeandclosethePL/SQLEditor.NowclickontheSORT_SELECTitemsRadio
Buttonsnode,followedbytwoclicksontheCreatebutton.ChangethefirstradiobuttonsNameand
LabelpropertiestoID,anditsRadioButtonValuepropertytoDEPARTMENT_ID.Changethesecond
radiobuttonsNameandLabelpropertiestoNAME,anditsRadioButtonValuepropertyto
DEPARTMENT_NAME.Next,intheObjectNavigator,rightclickonthe
DEPARTMENT_SORT_CONTROLblocksnameandselectLayoutWizardfromthecontextmenuthat
appears.SpecifythatyouwanttolaythecontrolblockoutontheDEPARTMENTcanvas,specifya
formtypeofForm,enteraframetitleofDepartmentSortOrder,andthenclickontheFinishbutton.In
theLayoutEditor,movethecontrolblocksoitisnexttotheDEPARTMENTblock.ClosetheLayout
EditorandreturntotheObjectNavigator.OpentheDEPARTMENTdatablocksnode,clickonthe
Triggersnode,andclickontheCreatebutton.SelectthePreQuerytriggerandenterthefollowing
codeinthePL/SQLEditor:
set_block_property('DEPARTMENT',ORDER_BY,
:department_sort_control.sort_select)
CompilethetriggercodeandclosethePL/SQLEditor.Saveyourapplicationandthenrunit.Inthe
FormsRuntimeprogram,navigatetotheDepartmentwindow,andthenclickontheNAMEradio
button.ThatshouldinitiateaquerywhoseresultslookverysimilartothoseinFigure152.Whenyou
arethrough,closetheFormsRuntimeprogramandreturntoFormBuilder.
Figure2:DepartmentformsortedbyPreQuerytrigger
Ifyouwantedtocreateaprequerytriggertoensurethatausersqueryincludescriteriaonthe
indexedcolumnDEPARTMENT_ID,youcoulddosowithcodesimilartothis:
if:DEPARTMENT.DEPARTMENT_IDisnullthen
message('ADepartmentIDisrequired.Pleaseprovide'||
'aDepartmentIDandrerunyourquery.')
raiseform_trigger_failure
endif
Youcanalsospecifyadditionalwhereclausefilteringbyusingcodelikethefollowing(whichassumes,
forthesakeofdemonstration,thatacheckboxexistsidentifyingwhethertheuserwantstheir
employeeformtoshowonlyemployeesintheprofitsharingplan):
ifcheckbox_checked('EMPLOYEE_FILTER_CONTROL.PROFIT_SHARE_ONLY')then
set_block_property('EMPLOYEE',DEFAULT_WHERE,'PROFIT_SHARING_INDICATOR=
1')
endif
YoucanuseallofthesetechniquestogetherinasinglePreQuerytrigger,givingyoutheassuranceof
indexutilizationwhilegivingyouruserstheabilitytoeasilytailorthedatareturnedwithouthavingtogo
throughEnterQuerymode.
Exercises
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
13/20
19/6/2015
BuildingFormsI
1. Whattypeoftriggergivesyoutheabilitytomodifyquerycriteriabeforerecordsareselected?
2. Whattypesofitemscanyouaddtoyouruserinterfacetogivetheuserasimplemethodof
changingquerycriteriaandrerunningaquery?
WritingTriggerstoSupplementQueryResults
BecausethePostQuerytriggerfiresafterrecordsareretrievedbutbeforetheydisplayedtotheuser,
youcanuseittoaugmentaquerysrecordsinanumberofways.ThePostQuerytriggercancontain
codetocalculaterunningtotals,generatestatisticsabouttherecordsretrieved,orpopulatecontrol
items,aswellasitemsinotherblocks.
Thefollowingexamplebuildsonthetechniquesyoupracticedinthesectionyoujustcompleted.The
examplecode,designedtoberunfromanEmployeeform,usestheemployeesDEPARTMENT_IDto
retrievethatdepartmentsmissionstatementfromtheDEPARTMENTtableanddisplayitinonthe
EMPLOYEEcanvas.TheexamplecodeassumesthattheDEPARTMENTtablehasacolumnnamed
MISSIONtostoremissionstatements,andthattheEmployeecanvashasadisplayitemnamed
DEPT_MISSION_DISPLAYtoshowamissionstatement.
DECLARE
cursorMEM_DEPT_MISSIONis
selectMISSION
fromDEPARTMENT
whereDEPARTMENT_ID=:EMPLOYEE.DEPARTMENT_ID
BEGIN
openMEM_DEPT_MISSION
fetchMEM_DEPT_MISSIONinto:EMPLOYEE.DEPT_MISSION_DISPLAY
closeMEM_DEPT_MISSION
END
Exercises
1. WhendoesthePostQuerytriggerfire?
2. WhatarethepotentialbenefitsofusingaPostQuerytrigger?
DebuggingTriggers
Inthissection,youwillcoverthefollowingpointsaboutdebuggingtriggersinyourforms:
Runningaformmoduleindebugmode
UnderstandingthecomponentsoftheDebugger
DebuggingPL/SQLcode
Nothingismorefunthandebuggingtriggercode.Okay,thatmaynotbetrue.Butusingdecent
debuggingtoolscanmaketheprocessalotmorepleasant.Thissectioncoversthefundamentalsof
usingtheFormsRuntimeprogramsDebugger.Youwillstartwithanoverviewofthedebugging
processusedforDeveloper/2000forms.Then,youwilllearnspecificsaboutdebuggingoptionsand
initiatingthedebugprocess.Next,youwillgetathoroughexplanationoftheDebuggersscreen
components,followedbyawalkthroughonsettingdebugbreakpoints,alteringmemoryvalueswhile
theapplicationispaused,andseeingtheimpactofalteredvalueswhentheapplicationresumes.
RunningaFormModuleinDebugMode
Whenyourunyourformmoduleindebugmode,theFormsRuntimeprogramstarts,butinsteadof
goingimmediatelyintoyourapplication,itfirstdisplaystheDebugger.WhileintheDebuggeryoucan
createbreakpointsandevenwritecodeddebugtriggersthatfireatspecifictimes.Afteryouhave
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
14/20
19/6/2015
BuildingFormsI
establishedbreakpointsanddebugtriggersorifyoudontyetknowwhereyouwillneedthemyou
closetheDebugger,andyourapplicationstarts.Fromthatpointon,theevidencethatyouareindebug
modevariesdependingonhowyouconfiguredyourdebugsettingsbeforerunningyourform.Youmay
seeevidencethatyouarerunningindebugmodeeverytimeatriggerfires,orwhenevertheprograms
executionisinterruptedwithabreakcommandinyourcode,orwhenyouchooseHelp|Debugfrom
theFormsRuntimemenu.
YoucanstarttheDebuggerfromFormBuilderbyclickingontheDebugModebutton,shownhere:
Illustration1
Whenthisbuttonisactive,theDebuggerwillstarteachtimeyourunyourformfromFormBuilder.
Behindthescenes,enablingthisbuttoncausesFormBuildertoincludesourcecodeinthe.fmxand
.mmxfilesitgeneratesbeforecallingtheFormsRuntimeprogram.SincepartoftheDebuggersjobis
lettingyouviewandmodifysourcecodeatruntime,itisnecessarytohavethatsourcecodeinthe
executablefile.
ThereisoneotherdebugoptionyousetfromFormBuilder:DebugMessages.Tosetthisoption,
executetheTools\Preferences\Runtimemenucommand.Theresultingdialogboxcontainsacheck
boxlabeledDebugMessages.Whenyourunyourformindebugmodewiththisoptionenabled,the
FormsRuntimeprogramdisplaysanalerteverytimeatriggerisabouttofire.Inaddition,itdisplaysin
theformconsolethenameofthetrigger,alongwiththeitemthatthetriggerisattachedto.Thisoption
canbevaluable,becauseitletsyoupinpointpreciselythespotinanapplicationwhereaproblemis
occurring.Ontheotherhand,simpleactionscangeneratealotoftriggerevents,andifyoualready
haveagoodideawhereaproblemisoccurring,yourdebuggingmaybesloweddownsubstantiallyby
enablingtheDebugMessagesoption.Forthesakeoflearning,enableitnowandclosethedialogbox.
Beforerunningyourform,ensurethattheDebugModebuttonisenabled.ThenclickontheRunForm
buttontostarttheFormsRuntimeprogram.Beforeyourapplicationstarts,youwillseetheDebugger
screen,whichisdiscussedindetailinthenextsection.
Exercises
1. Assumingyoualreadyhaveaformmoduleapplication,whatarethestepsforrunningitindebug
mode?
2. WhatdoesFormBuilderdodifferentlytothe.fmxand.mmxfilesitcreateswhenitknowsyou
willberunningtheapplicationindebugmode?
UnderstandingtheComponentsoftheDebugger
InordertousetheDebuggereffectivelyyoumustbethoroughlyacquaintedwithitscomponents.
Figure153showstheDebuggerwindowandidentifiesitsmaincomponents.
Toolbar
SourcePane
ObjectNavigator
Interpreter
Figure3:Debuggercomponents
TheDebuggertoolbarprovidesquickaccesstofunctionscommonlyusedwhiledebugging.Thetoolbar
isshownindetailinFigure154.TheStepIntobuttoninstructstheDebuggertostepintosubprogram
calls.Incontrast,theStepOverbuttondisablessteppingintocalledsubprogrambodies.TheStepOut
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
15/20
19/6/2015
BuildingFormsI
buttonresumesexecution,andstaysineffectuntilthecurrentsubprogramhasreturned.TheGo
buttonalsoresumesprogramexecution,remainingineffectuntilthethreadcurrentlyexecuting
terminatesorisinterruptedbyadebugaction.TheResetbuttonstopsprogramexecutioninthe
currentdebuglevelandreturnsprogramcontroltoanouterlevel.TheClosebuttonclosesthe
Debuggerwindowsoyoucanproceedtorunyourform.TheExpand,Collapse,ExpandAll,and
CollapseAllbuttonscauseObjectNavigatornodestoopenandclose,eitherindividuallyorasagroup.
StepInto
StepOver
StepOut
Go
Reset
Close
Help
Create
Delete
Expand
Collapse
ExpandAll
CollapseAll
Figure4:Debuggertoolbar
BeneaththetoolbaristheSourcePane,whichdisplaysthesourcecodeofwhateverprogramunityou
haveselectedintheDebuggersObjectNavigator.Thesourcecodeisreadonlywhenviewedthrough
theSourcePanethepaneisnotdesignedforediting.TheSourcePanealsodisplaystheprogram
unitslinenumbersalongitsleftmargin.Inadditiontolinenumbers,theleftmarginoftheSourcePane
sometimesshowsothersymbols.Thepipesymbol(|)marksthecurrentsourcelocation.Thecurrent
scopelocationismarkedwiththesymbol=>.Ifthecurrentexecutionlocationisdifferentthanthe
currentscopelocation,itwillbemarkedwiththesymbol.BreakpointsareindicatedwiththeletterB
followedbyanumberrepresentingthecorrespondingdebugactionID.Debugtriggersaremarkedwith
theletterTalongwithanumberindicatingthecorrespondingdebugactionID.
BelowtheSourcePaneistheDebuggersObjectNavigator.Thisarealistsallthemodulesthatthe
Debuggerisgoingtowatch.Youcanseeyourmodulebyclickingonthe+totheleftoftheModules
node.Whenyoudo,youwillseeyoursampleapplicationmodule.Openit,openitsBlocksnode,open
theDEPARTMENTnode,opentheTriggerssubnode,andclickonthePREQUERYtrigger.Youwill
seethetriggerscodeappearintheSourcePaneabove.
UnderneaththeObjectNavigatoristheInterpreter.Thisisaninteractivepromptatwhichyoucanenter
commandsthatcontroltheactionsoftheDebugger,suchascreatingbreakpoints.Muchofwhatyou
candoattheInterpreterpromptcanalsobedonebyselectingitemsintheSourcePaneorthe
DebuggerObjectNavigator,orbyexecutingcommandsfromthenewmenucommandgroupsthat
appearinyourFormsRuntimemenuwhentheDebuggerisactive:View,Navigator,Program,and
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
16/20
19/6/2015
BuildingFormsI
Debug.
Exercise
1.
WhichDebuggermenubuttonscauseprogramexecutiontoresume?Whatarethedifferences
betweenthem?
DebuggingPL/SQLCode
WhenyourunaformmoduleindebugmodeandtheDebuggerpresentsitsscreen,itislikelyyouwill
wanttosimplydismisstheDebuggerandrunyourapplicationuntilyouobservetheproblemyouare
tryingtosolve.DismisstheDebuggernowbyclickingontheClosebuttoninitstoolbar.Thennavigate
toyourDepartmentform.IfyouenabledtheDebugMessagesoptioninFormBuilder,youwill
immediatelybepresentedwithanalertboxstatingsimply"Pleaseacknowledgemessage."Downin
theconsole,themessagelinewillidentifythatatriggerisabouttofireitwillnamewhichtrigger,and
specifywhatobjectownsthetrigger.ClickonthealertboxsOKbuttontoproceed,andthenpopulate
theDepartmentformbyclickingontheNAMEradiobuttonintheDepartmentSortOrdercontrolblock.
Thiswillcauseseveralalertmessagestodisplayoneforeachtriggerthatfireswhiletheprogram
fulfillsyourrequest.Asyoucansee,theDebugMessagesoptiongivesyouaveryfinerazorandcan
getannoyingafterawhile.Toturnitoff,exitfromtheFormsRuntimeprogram,executetheForm
BuildersTools|Preferences|Runtimecommand,andunchecktheDebugMessagesoption.Then
clickontheOKbuttonandrerunyourform.Thistime,dontdismisstheDebuggerrightaway.Withinits
ObjectNavigator,navigatetothePREQUERYtriggeryoucreatedearlierfortheDEPARTMENTtable.
Whenyoufindit,thetriggerscodewillbedisplayedintheDebuggersSourcePane.Doubleclickon
theset_block_propertylineinthetriggercode.YouwillseethatitslinenumberchangestoB(01).
Youhavejustsetabreakpoint,whichwillcausetheDebuggertobeinvokedjustbeforeyour
applicationexecutesthatlineoftriggercode.Youcanremovethebreakpointbydoubleclickingonthe
lineagain.YoualsocouldhaveestablishedabreakpointherewhenyoucreatedthetriggerinForm
Builderbyincludingalinecontainingthefollowingcode:
break
Thebreakcommandcanbeespeciallyhandyaspartofanifstatementthatchecksforvalidconditions
andexecutesthebreakcommandifitfindsaproblem.
Ensurenowthattheset_block_propertylineinyourtriggerismarkedasabreakpoint,andthenclick
ontheClosebuttontoproceedtorunyourapplication.NavigatetotheDepartmentformandclickon
theNAMEradiobutton.WhentheFormsRuntimeprogramencountersthebreakpointinyourPRE
QUERYtrigger,itwillstopandopentheDebugger.Atthispointyourscreenshouldlooksimilarto
Figure155.Ifyouweretrackingdownarealproblem,youwouldnowusetheDebuggersObject
Navigatortoinvestigatethevaluesstoredinyourmodule,globalvariables,orsystemvariables.For
example,opentheObjectNavigatorsModulesnodeandnavigatedowntoyour
DEPARTMENT_SORT_CONTROLblock.OpenitsItemsnodeandyouwillseethattheonlyitemit
hasSORT_SELECThasacurrentvalueofDEPARTMENT_NAME.Ithasthatvaluebecausethe
mostrecentactionwasinitiatedbytheNAMEradiobutton,andyouassignedthatradiobuttonavalue
ofDEPARTMENT_NAMEwhenyoucreatedit.ToseehowyoucanusetheDebuggertoaltervalues
duringexecution,clickontheDEPARTMENT_NAMEvaluetotherightoftheSORT_SELECTitem,
andreplacethevaluewithDEPARTMENT_ID.Presstheenterkeytomakethenewvalue"stick,"and
thenclickontheGobuttontocontinue.YouwillseethatthedepartmentdatahasbeensortedbyID,
andtheradiogrouphasitsIDbuttonmarked,eventhoughitwastheNAMEbuttonthatinitiatedthe
action.Theresultsweredifferentbecauseyoualteredthevaluemidstreamusingthebreakpointand
theDebugger.
Figure5:Debuggeropeninresponsetobreakpoint
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
17/20
19/6/2015
BuildingFormsI
Exercises
1. WhatisthedifferencebetweentheStepInto,StepOver,andStepOutmenucommands?
2. Whenyourunaformindebugmode,howmanydifferentactionscancausetheDebuggerto
appear?
ChapterSummary
Inthischapter,youhavecoveredasubstantialamountofinformationonworkingwithtriggers.You
startedwithanexplanationofwhattriggersareandhowtheywork.Youthenlearnedhowtoproduce
triggers,andyouemployedthisknowledgewhilewritingtriggersthataddfunctionalitytoitemsand
queries.Next,youlearnedhowtodebugtriggersusingtheDebugger.
Thefirstareayoucoveredwasanintroductiontoformtriggers.AtriggerisablockofPL/SQLcodethat
addsfunctionalitytoyourapplication.Triggersareattachedtoobjectsinyourapplication.Whena
triggerisfired,itexecutesthecodeitcontains.Eachtriggersnamedefineswhateventwillfireitfor
instance,aWHENBUTTONPRESSEDtriggerexecutesitscodeeachtimetheuserclicksonthe
buttontowhichthetriggerisattached.ThetriggersmostcommonlyusedinFormBuilderfallinto
severalfunctionalcategories:BlockProcessing,InterfaceEvent,Master/Detail,MessageHandling,
Navigational,Query,Transactional,andValidation.Mostofthetriggersyoudealwithwillbeinterface
eventtriggers,whichfireastheuserinteractswithyourapplicationsGUIobjects.Interfaceevent
triggersgenerallyhavenamesfittingtheformatofWHENobjectaction.Triggersthatfirewhenanew
instanceofanobjectiscreatedfollowanamingformatofWHENNEWobjectINSTANCE.Mouse
eventtriggersusethenamingformatWHENMOUSEmouseaction,andtriggersthatrespondto
keystrokesusetheformatKEYkeytype.TheKEYOTHERStriggerfireswhenevertheuserpressesa
keythatcanhaveatriggerbutdoesnot,anditisanexcellentwaytodisableunwantedfunctionkeys.
OnetriggerwhosenamedoesnotrepresenttheobjectitisattachedtoisWHENWINDOWCLOSED.
Becausewindowsdonothavetriggers,theWHENWINDOWCLOSEDtriggerisusuallyattachedat
theformlevel.
Triggerscanalsobegroupedbytheirtypeandscope.Thetwotypesoftriggersare"builtin"and
"usernamed."BuiltintriggersaresuppliedwithFormBuilder,andtheyeachcorrespondtoa
predefinedruntimeevent.Usernamedtriggers,ontheotherhand,arenotprovidedwithFormBuilder
theyarewrittenbydeveloperslikeyou,andtheirnamescanbewhateverthedeveloperdesires.A
triggersscopedefineswhateventmustoccurinorderforthetriggertofire,andisdeterminedbythe
objecttowhichthetriggerisattached.Triggershavefewproperties,themostimportantofwhichare
ExecutionHierarchy,whichdetermineshowtheFormsRuntimeprogramhandlestriggerswithidentical
namesandoverlappingscopesandDisplayInKeyboardHelp,whichgivesyoutheabilitytoadda
descriptionofaKEYtriggertothekeyhelpintheFormsRuntimeprogram.
Afterestablishingthebasicpremisesoftriggerfunctions,categories,types,scopes,andproperties,
yourattentionturnedtothetechniquesinvolvedinproducingtriggers.Triggersconsistofcodeblocks
filledwithPL/SQLinstructions.Triggercodecanalsocontainavarietyofsystemvariables,commands
toreadandsetobjectproperties,andbuiltinpackagescontainingpremadePL/SQLconstructsfor
specificpurposes.ThebuiltinsprovidedwithFormBuilderaregroupedbyfunctionintopackages.
WhenyouuseabuiltinfromapackageotherthantheStandardpackages,youmustprecedeitsname
withthenameofthepackageforinstance,WEB.SHOW_DOCUMENT.Builtinsthatmoveinputfocus
orinvolvedatabasetransactionscannotbeusedinnavigationtriggers,soastoavoidcircular
referencesthatgenerateendlesscommandloops.Thesebuiltinsarecalledrestrictedbuiltins.
Whenaddressinghowtousetriggerstoaddfunctionalitytoformitems,youlearnedthatallinputitems
canhavetriggersattachedtothem.Inputitemscommonlyhavetriggersthatfirewhentheuserarrives
ontheitem,leavestheitem,orchangestheitemsdata.AnyinputitemcanhaveaWHENNEW
ITEMINSTANCEtriggerthatexecuteseachtimetheuserlandsontheitem,aswellasaWHEN
VALIDATEITEMtriggertochecktheitemscontentsforintegrity.Inputitemsthatfunctionbyhaving
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
18/20
19/6/2015
BuildingFormsI
theuserchangetheirstateratherthanenteravaluemeaningallinputitemsexcepttextitemscan
havetriggersthatfirewhentheircontentschangetheformatusedinthosetriggersnamesisWHEN
itemtypeCHANGED.Inputitemtriggerscanmakeuseofbuiltinsthatmanipulatedata,movetheinput
focus,openeditorsandLOVs,andcontrolanitemsavailability.Likeinputitems,noninputitemscan
beaugmentedwithtriggers,generallyincludingaWHENNEWITEMINSTANCEtriggerandatrigger
thatfireswhentheitemisclickedwiththemouse.Noninputitemtriggerscanalsoemploybuiltinsto
enhancetheirfunctionality.Anoninputitemtriggercanmakeuseofanybuiltinusedforaninputitem,
aswellasmanyotherbuiltinsthatcontrolinterfaceelements.
Youthenproceededtolearnaboutquerytriggers.Youstartedbylearningtheprocessinvolvedin
executingadatablockquery,whichconsistsofthreesteps:enteringthequery,executingthequery,
andfetchingtherecords.Adataquerycanhaveseveraltriggersattachedtoit,themostusefulof
whicharethePREQUERYtrigger(whichfiresbeforetheselectstatementisfinalized)andthePOST
QUERYtrigger(whichfiresbeforeselectedrecordsarepresentedtotheuser).
Thefinalareacoveredinthischapterisdebugging.TheDebuggercanbeinvokedbyenablingthe
DebugModeoptioninFormBuilderandthenrunningyourform.WhentheDebugModebuttonis
active,theDebuggerwillstarteachtimeyourunyourformfromFormBuilder.Enablingthisbutton
causesFormBuildertoincludesourcecodeinthe.fmxand.mmxfilesitgeneratesbeforecallingthe
FormsRuntimeprogram.YoucanalsochoosetoenableDebugMessages,whichcausetheForms
Runtimeprogramtodisplayanalerteverytimeatriggerisabouttofire,alongwithamessageinthe
consoleidentifyingthetriggerandobjectthatownsit.TheFormDebuggerhasfourvisualcomponents:
thetoolbar,whichcontainsbuttonsforoftenusedactionstheSourcePane,whichshowsthePL/SQL
instructionsinwhatevercodeobjectyouselecttheObjectNavigator,whichdisplaysDebuggerobjects
inahierarchicallayoutandtheInterpreter,whichisaninteractivepromptatwhichyoucantype
Debuggercommands.WhileintheDebugger,youcancreatetemporarybreakpointsandwritecoded
debugtriggersthatfireinresponsetospecificactions.YoucanalsocreatebreakpointsinFormBuilder
byaddingthecommandbreaktoyourPL/SQLcode.WhenevertheFormsRuntimeprogram
encounterseithertypeofbreakpoint,itpausesexecutionofyourapplicationandstartstheDebugger,
whichallowsyoutoexamineandchangememoryvariablesandprogramcode.
Allinall,thischaptercomprisesabout22percentofmaterialtestedonOCPExam3.
TwoMinuteDrill
AtriggerisablockofPL/SQLcodethataddsfunctionalitytoyourapplication.
Triggersareattachedtoobjectsinyourapplication.
Whenatriggerisfired,itexecutesthecodeitcontains.
Eachtriggersnamedefineswhateventwillfireit.
ThetriggersmostcommonlyusedinFormBuilderfallintoseveralfunctionalcategories:Block
Processing,InterfaceEvent,Master/Detail,MessageHandling,Navigational,Query,
Transactional,andValidation.
Mostofthetriggersyoudealwithwillbeinterfaceeventtriggers,whichfireastheuserinteracts
withyourapplicationsGUIobjects.
InterfaceeventtriggersgenerallyhavenamesfittingtheformatofWHENobjectaction.
TriggersthatfirewhenanewinstanceofanobjectiscreateduseanamingformatofWHEN
NEWobjectINSTANCE.
MouseeventtriggersusethenamingformatWHENMOUSEmouseaction.
TriggersthatrespondtokeystrokesusethenamingformatKEYkeytype.
TheKEYOTHERStriggerfireswhenevertheuserpressesakeythatcanhaveatriggerbutdoes
not.
Becausewindowsdonothavetriggers,theWHENWINDOWCLOSEDtriggerisusually
attachedattheformlevel.
Thetwotypesoftriggersarebuiltinandusernamed.BuiltintriggersaresuppliedwithForm
Builder,whileusernamedtriggersarewrittenbydevelopers.
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
19/20
19/6/2015
BuildingFormsI
Atriggersscopedefineswhateventmustoccurinorderforthetriggertofire,andisdetermined
bytheobjecttowhichthetriggerisattached.
TriggersconsistofcodeblocksfilledwithPL/SQLinstructions.
Triggercodecanalsocontainavarietyofsystemvariables,commandstoreadandsetobject
properties,andbuiltinpackagescontainingpremadePL/SQLconstructsforspecificpurposes.
ThebuiltinsprovidedwithFormBuilderaregroupedbyfunctionintopackages.
WhenyouuseabuiltinfromapackageotherthantheStandardpackages,youmustprecedeits
namewiththenameofthepackageforinstance,WEB.SHOW_DOCUMENT.
Builtinsthatmoveinputfocusorinvolvedatabasetransactionscannotbeusedinnavigation
triggers,soastoavoidcircularreferencesthatgenerateendlesscommandloops.Thesebuiltins
arecalledrestrictedbuiltins.
Inputitemscommonlyhavetriggersthatfirewhentheuserarrivesontheitem,leavestheitem,
orchangestheitemsdata.
AnyinputitemwillacceptaWHENNEWITEMINSTANCEtriggerthatexecuteseachtimethe
usermovesfocustotheitem,aswellasaWHENVALIDATEITEMtriggertoidentifyhowthe
itemscontentsshouldbecheckedforintegrity.
Allinputitemsexcepttextitemscanalsohavetriggersthatfirewhentheircontentschangethe
formatusedinthosetriggersnamesisWHENitemtypeCHANGED.
Noninputitemscanalsobeaugmentedwithtriggers,generallyincludingaWHENNEWITEM
INSTANCEtriggerandatriggerthatfireswhentheitemisclickedwiththemouse.
Anoninputitemtriggercanemployanybuiltinusedforaninputitem,aswellasmanyother
builtinsthatcontrolinterfaceelements.
Thequeryprocessinvolvesthreesteps:enteringthequery,executingthequery,andfetchingthe
records.
Adataquerycanhaveseveraltriggersattachedtoit,themostusefulofwhicharethePRE
QUERYtrigger(whichfiresbeforetheselectstatementisfinalized)andthePOSTQUERY
trigger(whichfiresbeforeselectedrecordsarepresentedtotheuser).
TheDebuggercanbeinvokedbyenablingtheDebugModeoptioninFormBuilderandthen
runningyourform.
WhentheDebugModeoptionisactive,theDebuggerwillstarteachtimeyourunyourformfrom
FormBuilder.
EnablingthisbuttoncausesFormBuildertoincludesourcecodeinthe.fmxand.mmxfilesit
generatesbeforecallingtheFormsRuntimeprogram.
IfyouenableDebugMessages,theFormsRuntimeprogramwilldisplayanalerteverytimea
triggerisabouttofire,alongwithamessageintheconsoleidentifyingtheitemandtrigger.
TheFormDebuggerhasfourvisualcomponents:toolbar,SourcePane,ObjectNavigator,
Interpreter.
WhileintheDebugger,youcancreatetemporarybreakpointsandwritecodeddebugtriggers
thatfireinresponsetospecificactions.YoucanalsocreatebreakpointsinFormBuilderby
addingthecommandbreaktoyourPL/SQLcode.
WhenevertheFormsRuntimeprogramencountersabreakpoint,itpausesexecutionofyour
applicationandstartstheDebugger,whichallowsyoutoexamineandchangememoryvariables.
http://dbdeveloper.narod.ru/97515f.html#_Toc443106547
20/20