Your SlideShare is downloading. ×
10g forms
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

10g forms

17,269
views

Published on

ORACLE FORMS 10 G

ORACLE FORMS 10 G

Published in: Education, Technology

3 Comments
5 Likes
Statistics
Notes
  • my mail id is abdullahmd.137@gmail.com can anybody send me dis books oracle forms and reports
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • very effective
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • thanks so much
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
17,269
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
1,320
Comments
3
Likes
5
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Oracle 10g Forms This book belongs to Name :______________________________________ Batch :______________________________________ SQL Star International Ltd. SQL Star House, No. 8-2-293/174/A 25, Road No. 14, Banjara Hills, Hyderabad - 500 034, Andhra Pradesh, INDIAConfidential © SQL Star International Ltd. 1
  • 2. Copyright © 2008 Second Edition SQL STAR INTERNATIONAL LIMITED SQL Star House,8-2-293/174/A25, Road No.14, Banjara Hills, Hyderabad - 500 034. Tel. No. 91- 40-23101600(30 lines) Fax No. 23101663 Toll Free No: 1800 425 2944 Email: info@sqlstar.comNo part of this publication may be reproduced (incl. photocopying) in any way, withoutprior agreement and written permission of SQL Star International Ltd., Hyderabad. SQLStar International Ltd., Hyderabad assumes no responsibility for its use, nor for anyinfringements of patents or other rights of third parties which could result.Confidential © SQL Star International Ltd. ii
  • 3. Table of contents 10g FORMS CHAPTER CHAPTER TITLE PAGE No. NO 1. Introduction to Oracle Forms Developer Suit 1 – 12 2. Running a Forms Developer Application 13 – 25 3. Forms Developer Interface 26 – 39 4. Basic Form Module Creation 40 – 65 5. Discuss Data Block Properties 66 – 77 6. Creating Text items, LOVs and Editors 78 –100 7. Creating Input and Non-Input Items 101-126 8. Windows & Canvases 127-142 9. Triggers 143-167 10. Item InteractionTriggers and Alerts 168-193 11. Item Validation and QueryTrigger 194-213 12. Navigation 214-228 13. Key & Mouse Event Triggers 229-249 14. Transaction Triggers 250-263 15. Flexible Code 264-275 16. Sharing Objects and Code 276-292 17. WebUtil for Client Interaction 293-308 18. Working with Multiple Form Applications 309-340 19. Managing Menus 341-372Confidential © SQL Star International Ltd. iii
  • 4. Chapter 1 Introduction to Oracle Forms Developer Suite Introduction to Internet Computing Products Grid computing Oracle10g Tools for Forms development Oracle10g AS Architecture Oracle10g Provides Oracle Forms Services Benefits of Oracle10g Developer Suite What Is Oracle Forms Developer© SQL Star International Ltd 1
  • 5. ObjectiveAt the end of this chapter, you will be able to: • Get a brief idea about Internet Computing Products • Understand Grid Computing • Learn the components of the Oracle10g Application server • Know what Oracle10g Provides • Describe the features and benefits of Oracle Forms services and Oracle Forms developer • Gather information about the benefits of Oracle10g Developer Suite • Know all the features of Oracle Forms DeveloperConfidential © SQL Star International Ltd. 2
  • 6. Introduction to Internet Computing ProductsInternet is the most preferred media to publish information for the masses.Oracle Corporation has come up with a wide range of different tools, which istargeted at different audience for the development work.Based on the nature of work requirement, you can choose from the pool of Oracleproducts. Different products have been developed for different kind of audiences.Some of the categories of audiences who can use them are:Enterprise application developers:The apt Oracle product for audience belonging to this category would be OracleDesigner and Oracle Forms Developer. • Oracle Designer: This Oracle modelling tool helps to collect the business requirement by giving support to SDLC process. • Oracle Forms Developer: It is a wizard based Rapid application development tool through which Internet based powerful applications can be developed within a short span of time. Deployment of the application is made easier with Form Services, which is an Oracle Application server component.Java Component Developers:If you were a Java developer, then the suitable product of Oracle would beJdeveloper. • Jdeveloper: It is a single Oracle’s java development environment, providing necessary tools for developers working in Java and Web services projects. It covers the full development lifecycle from design through coding, debugging and tuning till deploying the application.Website developers:These developers are mainly those, who see Internet as the only media to workwith, in order to publish their information. Oracle has come up with Oracle portalkeeping these developers in mind. • Oracle Portal: It is a complete integrated framework used for developing and deploying application of enterprise portal. It tightly resides inside Oracle10g database.MIS Developers: Oracle business intelligent toolset has helped MIS developers to create reports which help the management to make mission critical decisions. This toolset also contains a product, which can be used by the end user to generate day- to-day reports. Oracle business intelligent toolset comprises the following products, which provides a whole range for reporting, analysis, and trending facilities: • Oracle Reports Developer • Oracle Report services • Oracle Discoverer • Oracle ExpressConfidential © SQL Star International Ltd. 3
  • 7. Grid ComputingThe database systems such as Relational, Hierarchical and Network have beensuccessful in developing the database for traditional business applications such asBanking and Railway reservations. But, when it comes to more complex businessapplications such as databases for scientific work, engineering designs,telecommunications, geographic information system and multimedia, thetraditional database systems cannot handle them because the requirements andcharacteristics of these applications are different from the traditional businessapplications. These applications require more complex structures for: • Storing data related to real world objects such as engineering diagrams, molecular structures, or financial instruments. • Transactions, which would be for longer durations. • New datatypes required for storing complex multimedia data such as audio and video clips, images and maps.Oracle10g Database meets the above needs as it tightly incorporates ORDBMSconcepts.Object Relational Database Management System (ORDBMS) is a databasemanagement system that has evolved from the relational model and includesboth the relational and object oriented technology. Oracle8.0 was the first versionof the Oracle database to incorporate object-oriented technology.In Oracle10g, ‘g’ stands for GRID. This release is focused on efficientmanagement of infrastructure based on its grid computing mechanism.Now, the question arises what is Grid Computing?Grid computing provides clustering of remotely distributed computing.The idea behind grid computing is to utilize the resources available to themaximum extent, by dynamically pooling it based on the requirement of the enduser during the peak hours. In this case, the end user need not know thewhereabouts of the resource.Oracle grid infrastructure products: • Oracle Database 10g • Oracle Application Server 10g • Oracle Enterprise Manager 10g Grid ControlOracle Database 10gOracle10g database supports Grid Computing architecture. Here, multipledatabase servers are pooled together to form a cluster. It enhances utilization ofresources. It efficiently stores and manages the structured and unstructured datasuch as: • Spreadsheets • Word documents • PowerPoint presentations • XMLConfidential © SQL Star International Ltd. 4
  • 8. • Multimedia data types like MP3, graphics, video and more.Oracle 10g facilitates two-tiered or multi-layered distributed databaseenvironments like client/server and Web-based applications. Large objects needbe stored inside and outside the database. Oracle Database 10g have serviceswhich help to manage and retrieve data, located outside the database.• Oracle Application Server 10gA complete infrastructure platform is provided for developing and deployingenterprise applications, integrating many functions including a J2EE and Webservices run-time environment, an enterprise portal, an enterprise integrationbroker, business intelligence, Web caching, and identity management services.The existing 10g AS gets further enhanced with the introduction of new gridcomputing features. It further integrates users, applications and data across yourorganization.• Oracle Enterprise Manager 10g Grid ControlIt is the consolidated, core management console that forms the basic frameworkto automatically initiate administrative tasks across the networked environment.With Oracle Grid Control, multiple hardware nodes, databases, application serversand other targets can be brought together into single logical entities.Oracle10g Tools for Forms developmentOracle10g release can be broadly divided into 3 categories.Oracle Database: It supports ORDBMS, managing unstructured and structuredinformation efficiently. It follows the concept of re-usability there by promotingautomation techniques.Oracle10g Application Server (Oracle10g AS): It forms the middle tier whichholds a range of Business Logic Application, developed in different platforms suchas JAVA, PORTAL, FORMS, WAP and business intelligence. Forms Services, themain component of Oracle10g AS play an important role in deploying the formsapplication on to the Web-based environment.Oracle10g Developer Suite (Oracle10g DS): It comprises Oracle applicationdevelopment tools and Oracle Business Intelligence tools. This product forms acomplete package for developing scalable, re-usable and reliable application to beshared across the web environment.Oracle10g AS ArchitectureLooking into the functional structure, this architecture can be divided into: • Communication Services: Manage the request/response of/for a client, by means of suitable protocols. • Application Runtime Services: It contains J2EE Container that forms a common runtime environment for Applications developed as JSPs, Servlets, EJBs and Web Services. • System Services: It provides a similar group of runtime services required by the web based application for managing their essential processes such as request dispatch and scheduling, resource pooling, clustering, fault monitoring, transaction management and messaging.Confidential © SQL Star International Ltd. 5
  • 9. • Management Services: These services record the status, monitor the performance and handle the failure of the system. It helps to keep track of the resource consumption, manage multiple instances and support single sign-on feature. • Connectivity Services: Enables connectivity between systems of different platforms. • Solutions: A comprehensive set of solutions all built on the infrastructure described above, including Enterprise Portals, Enterprise Integration, Business Intelligence, Wireless and ISV Solutions. Oracle10g AS ArchitectureList of Oracle10g Application Server Components and their functionality: • Extract and analyze business intelligence: Clickstream, Personalization, Reports Services, Discoverer. • Integrate your business: Interconnect, Workflow, Unified Messaging, Internet File System. • Create personalized portals: Oracle10g AS Portal. • Deploy dynamic Web applications: XDK, Web Services, Forms Services, OC4J, HTTP Server. • Manage and secure your Web infrastructure: Enterprise Manager, Security, and Internet Directory.Oracle10g AS provides: • A Comprehensive and a fully integrated platform for deploying web applications. • Facilities to redefine the business process and publish them into the enterprise portal, which can be accessed from the internet or wireless services. • Forms Services, a component in it that deploys the application on to the web.Confidential © SQL Star International Ltd. 6
  • 10. • Provides web cache which enhances the performance and throughput of the website by caching mechanisms. • Manage and secure your Web infrastructure by Single Sign On (SSO) method.Oracle Forms ServicesOracle Form Services is a component of the middle tier, Oracle10g AS. It isresponsible for deploying Oracle Forms Developer applications in a multi-layeredenvironment without compromising the functionality and the intricacies of theinterface. It provides the required infrastructure through its in-built services.Oracle Forms Services uses a three-layered architecture to deploy applicationsover the web. These include: • A Java enabled thin client tier, where the application’s output is presented by the interface to the user. • The middle tier is the application server or servers, where the application logic and server software reside. • The database tier is the database server or servers, where enterprise data is stored. Oracle10g Forms Services Forms Services ArchitectureForms Services consists of four major components: the Java client (Forms Client),Oracle Jinitiator, the Forms Listener Servlet, and the Forms Runtime Engine. Youwill learn about these components in chapter 2 - Running a Forms DeveloperApplication.Process at the client end: 1) Oracle Jinitiator is downloaded on the very first request of the client. This forms the surface for running the applications. 2) An applet is dynamically loaded into the client machine and cached.Confidential © SQL Star International Ltd. 7
  • 11. The Forms Listener Servlet and Forms Runtime Engine process on the middle tierof Oracle10g As.Benefits of Oracle10g Developer SuiteThe Oracle10g Developer Suite: • Provides a complete integrated set of tools for developing web-based applications. • Helps to develop Internet compatible Web services applications using Java and XML. • Produces performance based tuned application, by utilizing the resources of both Oracle Database and Oracle application server to its maximum.Confidential © SQL Star International Ltd. 8
  • 12. • Further, enhances the richness of the application by incorporating capabilities for Microscopic analysis of data and distributing the same, across the web.Based on the toolset availability, Oracle10g developer suite can be divided into: 1. Application Development tools Oracle Designer: Used for reverse engineering and code generation. Forms Developer and Jdeveloper: Used for Rapid Application development (RAD) of enterprise application and business components for Java respectively. J2EE and Web Services: Extends support for latest J2EE 1.2 API’s, including Enterprise JavaBeans (EJB), Java Server Pages (JSP) and Servlets 2.3. Integrated web services support for SOAP (simple object access protocol) and WSDL (web services definition language) Software Configuration Manager (SCM): Used to keep a record of version changes, impact of renewed configuration, parallel development and analyzing dependencies among objects. 2. Business Intelligence Reporting Tools Oracle10g Warehouse Builder: Follows a fixed process of extracting, transforming and loading data. It reduces the complexity of designing and managing the warehouse and data mart, web based business intelligence application by providing easy GUI driven data mapping, pre-defined transformation tools and creating dimensional data by drag-drop features. Oracle10g Discoverer Administrator: Provides a collection of data of business importance, neatly managed by the system manager of the BI tools. It allows ad-doc query and analysis on these related data performed on the Discoverer clients, which are Oracle10g AS Discoverer Plus, Oracle10g DS Discoverer Desktop, and Oracle10g AS Discoverer Viewer. Oracle10g Reports Developer: Reports can be created with easy wizard driven GUI tool. It allows the developer to create reports by taking maximum control over the various data sources available and utilizes a wider media to publish the same.What is Oracle Forms Developer?It is a front-end tool used to develop enterprise-driven applications with its GUIcapabilities. Powerful web based interface applications can be rapidly developeddue its re-entrant wizard features. It tightly integrates with the Oracle10gDatabase for building up its application. It can also embed java components,increasing its developmental capabilities further.Applications can be developed on the basis of code generation and reverseengineer modeling features of Oracle Designer. Hence it works hand in hand withOracle Designer.Oracle10g Forms Developer: Key FeaturesTools for Rapid Application Development:Confidential © SQL Star International Ltd. 9
  • 13. Database forms and business logic can be created with minimum effort. WizardandBuilt-in subprograms are responsible for quick development of application.Application Partitioning:PL/SQL program units can be created both in the back-end i.e. database server aswell as in the front on i.e. Oracle Forms. It is because of the separate PL/SQLengine present in both the environments. When needed, this business logic canbe moved between the modules and Oracle10g database.Flexible Source Control:Oracle10g Software Configuration Manager (SCM) is integrated directly in FormsDeveloper, used to keep a record of version changes, impact of renewedconfiguration, parallel development and analyzing dependencies among objects.Extended Scalability:The multi-layered environment allows the product to be distributed among a widerange of users with no further manipulation in the application.Object Reuse:It enables centralization of code and pooling of reusable objects by creatingPL/SQL libraries and object libraries, linking the object behavior of differentmodules by inheritance and subclassing mechanism.Confidential © SQL Star International Ltd. 10
  • 14. SummaryIn this chapter, you have learnt that: • Various Oracle products have been developed for accommodating the needs of different kinds of developers. For example, a suitable product of Oracle for a Java developer would be Jdeveloper. • Grid computing provides clustering of remotely distributed computing. • Oracle Database supports OORDBMS, managing unstructured and structured information efficiently. • Oracle10gAS architecture can be divided into: Communication Services, Application Runtime Services, System Services, Management Services, Connectivity Services and Solutions. • Oracle Form Services is a component of the middle tier, Oracle10g AS that is responsible for deploying Oracle Forms Developer applications in a multi-layered environment. • The Oracle10g Developer Suite benefits you by providing a complete integrated set of tools for developing web-based applications and many more. • Oracle10g developer suite can be divided into Application Development tools and Business Intelligence Reporting tools. • Oracle Forms Developer is a front-end tool used to develop enterprise- driven applications with its GUI capabilities. • Key Features of Oracle10g Forms Developer are tools for Rapid Application Development, Application Partitioning, Flexible Source Control, Extended Scalability and Object Reuse.Confidential © SQL Star International Ltd. 11
  • 15. Exercise1. What do you understand by Grid Computing?2. What are the different Oracle 10g tools for Forms Development?3. Explain briefly about Oracle Forms Services.4. What are the different Reporting Tools?5. List out the key features of Oracle10g Forms Developer. Confidential © SQL Star International Ltd. 12
  • 16. Chapter 2 Running a Forms Developer Application Introduction to Three-tier Architecture Testing a Form Java Runtime Environment Starting a Run-time Session Form Application in a Web Browser Oracle Environment variablesConfidential © SQL Star International Ltd. 13
  • 17. ObjectiveAt the end of this chapter, you will be able to: • Define the three-tier architecture • Get the solution of how to test a Form • Learn the concept inside Java Runtime Environment • Describe Starting a Run-time session • Understand about various Form application in a web browser • Know about some Oracle environment variablesConfidential © SQL Star International Ltd. 14
  • 18. Introduction to Three-tier ArchitectureWe are now aware that Form Services, a component of Oracle10g AS helps todeploy applications in a multi-layered environment. But how does this componentactually work?This chapter helps us to explore its functionality in detail.A three-tier Architecture would look something like this: Application Server Database Three-tier EnvironmentLet us now discuss the different entities of the architecture individually in detail:Forms Client:It includes a thin Java applet embedding all types of Oracle forms application,which runs within the boundaries of client’s Java enabled web browser. This isalso known as thin client as no application logic or enterprise data is stored by it.It is responsible for: • Displaying user-interaction screen encoded in the application. • Acting as a single point user-interface to accept the requests. • Behaving like an acceptor to receive the responses given by the form services.Application Server:It is the middle tier where the application logic and the main component fordeployment, the Form Services reside. All processing related to application isdone here.Confidential © SQL Star International Ltd. 15
  • 19. Application ServerThe main components that reside inside the form services of the ApplicationServer are:Forms Listener Servlet: It is a complete Java Servlet that runs in the middletier, which works in close proximity with Oracle HTTP Server or OC4J (OracleApplication Server Container for J2EE).Responsibilities include: • Accept request given by the client for initiating connectivity. • It either invokes a new runtime engine or is allocated a previously running runtime engine from the runtime engine pool. • Acts as a communicating agent between the client and the runtime engine.Forms Servlet: It generates an HTML page to be downloaded on to the client,based on the web configuration file (formsweb.cfg), base HTML file (basejini.htmor base.htm or baseie.htm) or application’s URL parameters.Runtime Engine: It is an ifweb90 processor initialized by forms listener servletin the middle tier.Responsibilities include: • Managing the processing of application logic. • Maintaining an uninterrupted connection to the database on behalf of the client.Oracle10g Database: It is the third tier where enterprise data is stored.Confidential © SQL Star International Ltd. 16
  • 20. Testing a Form: Starting Oracle Application ServerContainers for J2EE (OC4J)Oracle Application Server containers for J2EE (OC4J) is preferred to run Formsapplications. • Included in Oracle10g DS to enable testing. • On NT, run batch file to start OC4J.Starting OC4JOracle10g AS Containers for J2EE (OC4J) is Oracle’s Java 2 Enterprise Edition(J2EE) container that executes on any Java Virtual Machine (JVM), the Javainterpreter that is provided on each operating system and hardware platform. Itis implemented completely in Java, making it lightweight and easy to install. Atthe same time, it provides complete support for J2EE applications, includingServlets, Enterprise JavaBeans, Java Server Pages, and so on.OC4J is ideally suited to run Forms applications. It is included in Oracle10gDeveloper Suite to enable you to test your applications, if desired, on the samemachine where you are running Forms Builder. In other words, you do not needto install Oracle10g AS to test your applications.To use OC4J on Windows NT, you start it by executing the provided batch file,called startinst.bat. This file is located in the j2eeOracle10gDS subdirectory ofORACLE_HOME. If you will be testing your applications on your client machine,then it is a good idea to set up a shortcut to startinst.bat batch file and alsostopinst.bat batch file to start and stop the OC4J instance respectively.The batch file executes in a separate window. (You can minimize this window ifdesired). Do not close this window, or you will abort the OC4J instance.When you no longer need to run OC4J, you can execute the batch file to stop theOC4J instance, called stopinst.bat.Confidential © SQL Star International Ltd. 17
  • 21. Testing a Form: The Run Form Button With the Run Form Menu command or Button , you can : - Run a form from Forms Builder - Test the form in a three-tier environment The Run Form command takes its settings from Preferences ; - Edit -> Preferences - Runtime tab - Set Application Server URL to point to Forms Servlet - Set Web Browser location if desired – http://127.0.0.1:8889/forms/frmservletRunning of a FormIn order to run the application in a web browser, the user’s request should be inthe form of a URL. This URL is written in the address bar of the web browser. Thesyntax of the URL would be similar to the following format:http://domain[:port]/forms servlet or html file [parameter]Where,http: ProtocolDomain: Server name where the application resides.Port: Default for HTTP server 8889 default for OC4JFormsServlet: /forms/frmservletParameter: indicates form, userid=username/password@databaseJava Runtime EnvironmentIn order to deploy the forms application on to web browser, it is necessary tohave a Java runtime environment. On windows platform, Java RuntimeEnvironment (JRE) can be created by Oracle Jinitiator, a plug-in supplied byOracle, which enables the end user to run Oracle forms developer directly on thebrowser that does not provide a JRE environment. It is automatically downloadedto a client machine from the application server.Benefits: • It caches the Java archive files on the client thereby helping reduce the application startup time. • It provides applet instance caching. This is a method of storing the running form application during navigation event. When the userConfidential © SQL Star International Ltd. 18
  • 22. returns to the same page, the cached page is restored. This improves the application performance.Starting a Run-time SessionGiven below, is a list of processes that occurs: • A request is sent from the client to the application server in the form of URL. • The request is taken up by the Oracle HTTP server or OC4J and passed further to Forms Servlet. In response to it, Forms Servlet creates a HTML page containing all the relevant information for the generation of a forms applet, which is given to the HTTP server. You can see this in the following diagram:Now, HTTP server responds by downloading a generic applet, which is cachedlocally on the client.Forms applet sends a request to the Forms listener to invoke the forms runtimeengine.Confidential © SQL Star International Ltd. 19
  • 23. • Forms Client cannot interact with the database directly. So here, runtime engine works on behalf of the client. Oracle Forms runtime engine executes the application specified in the URL and then passes the result to the Forms applet via Forms listener. • Forms applet running within the client browser, displays the application as per the application logic. • Once the initial request to the application is completed, the Forms listener Servlet along with HTTP server handles the communication between the forms applet and the runtime engine.Forms application in a Web browserClient-Server Deployment at RuntimeForms runtime session is started when you run a form module. The componentsof the runtime session are:Confidential © SQL Star International Ltd. 20
  • 24. • MDI Parent Window: Multiple Document Interface (MDI) parent window is the default window provided to display form modules. MDI window can display multiple form modules. • SDI Window: Form Builder also provides support for a Single Document Interface (SDI) Window even though the default window is the MDI Window. • Default Menu: Oracle Forms Developer provides all applications with a default menu. This menu can be customized to enhance the functionality of your applications. • Menu Toolbar: Menu Toolbar contains icons that correspond to the menu items. It is provided to add functionality and is a short cut to the menu items. • Console: The Console is displayed during runtime at the bottom of your window, which displays information. It also consists of: o Message Line: It displays Form Builder and application specific messages. Database error messages are displayed in the message line. o Status Line: Displays the state of the form module. It will tell you if there is a list of values associated with the item and if the block is in the enter query mode or not. o Data Elements: Irrespective of the deployment the data elements in a Form Builder are same in the Web or in a Client-server environment. The data elements that you see at runtime are: • Boilerplate text • Boilerplate graphics • PromptsConfidential © SQL Star International Ltd. 21
  • 25. • Text items • List items • Push buttons • Display items • Radio buttons • Check boxes • Image items • Hierarchical tree items • Chart items • Custom items Oracle Developer Environment Variables In order to customize the application, following environment variables can be modified. Forms environment variables for design time UI_ICON_EXTENSIONFORMS_BUILDER_CLASSPATH FORMS_HIDE_OBR_PARAMS Set to FALSE to be able to Set so that forms builder see the hidden parameters can find java class files passed in the URL during development and testing process UI_ICON Type of the iconic image, i.e., gif, jpeg of .ico must To create iconic images in be specified here forms builder, path of the icon is set here Confidential © SQL Star International Ltd. 22
  • 26. Forms environment variables for runtime FORMS_RESTRICT_ENTER _QUERY FORMS_PATH CLASSPATH Set this parameterGives path of the Form ORACLE_PATH Specifies path of to True to invokebeing searched by Java Class file the Query/WhereForms builder to run it required for Forms dialog box. By default it is set to Specifies the search path False. for files referenced by Reports RuntimeAlternatively, you can control the environment variable setting in file known asformsserverdefault.envConfidential © SQL Star International Ltd. 23
  • 27. Summary In this chapter, you have learnt that: • How Form Services, a component of Oracle10g AS actually works. • Forms Client includes a thin Java applet embedding all types of Oracle forms application, which runs within the boundaries of client’s Java enabled web browser. • Oracle10g AS Containers for J2EE (OC4J) is Oracle’s Java 2 Enterprise Edition (J2EE) container that executes on any Java Virtual Machine (JVM). • OC4J is ideally suited to run Forms applications. • In order to run the application in a web browser, the user’s request should be in the form of a URL. • Java Runtime Environment (JRE) can be created by Oracle Jinitiator, which enables the end user to run Oracle forms developer directly on the browser that does not provide a JRE environment. • One of the benefits of JRE is that it caches the Java archive files on the client. • Forms Client cannot interact with the database directly. So here, runtime engine works on behalf of the client. • Forms runtime session components are MDI Parent Window, SDI Window, Default Menu, Menu Toolbar and Console.Confidential © SQL Star International Ltd. 24
  • 28. Exercise 1. What are the main components of Forms Services? 2. What are the different modes of operations? 3. ________ is the default window provided by forms builder. 4. ________ is the default canvas provided by Forms Builder. 5. What are the components of run-time session? 6. What is the default port number in Oracle 10g? 7. Which file is required to start and stop OC4J server? 8. List the forms environment variables available at design time and runtime? 9. _______ gives the path of the Form being searched by forms builder to run it. 10. _______ specifies the path of java class file required for forms debugger. 11. _______ is set so that forms builder can find java class files during development and testing process. 12. _______ path of an icon is set here which is used to create iconic images in the forms builder. 13. Type of the iconic image i.e., gif, jpeg or ico must be specified in _______. 14. In formsweb.cfg change the applet parameter width to 900 and height to600.Confidential © SQL Star International Ltd. 25
  • 29. Chapter 3 Forms Developer Interface The Form Builder Environment The Form Builder Components The Form Builder Module Types Oracle Form Builder Interface Components Form Module Objects Navigation in a Form Module Master versus Detail Blocks Multi-Block and Multi-Form Applications Library Management ModuleConfidential © SQL Star International Ltd. 26
  • 30. Objective At the end of this chapter, you will be able to: • Identify and describe forms builder environment • Understand the main components of form builder • Get a brief idea about forms builder interface components • Learn form module objects • Know how navigation takes place in a form module • Find the difference in Master and Detail Blocks • Find the difference in multi-block and multi-form applications • Describe library management moduleConfidential © SQL Star International Ltd. 27
  • 31. The Form Builder Environment The Form Builder environment allows you to design your form modules and manipulate data in a number of ways. Form Builder enables users to: • Insert, update, delete and query data • Present data using text and images • Present data using JavaBeans and ActiveX custom controls • Manage Forms across multiple windows • Access Oracle Graphics Builder and OLE2 applications • Send data to Oracle Reports BuilderThe Form Builder Components The Form Builder has three executables that help to create, compile and run a form module: Form Builder: It is used to design and build applications and store the definition. It can be invoked using FRMBLD.EXE Form Compiler: It is used to read the definition of the form module and convert them into an executable run file. It can be invoked using FRMCMP.EXE Form Runtime: It is used to execute a form module. Before you want to run a Form, ensure that the form module is compiled.The Form Builder Module Types Form Builder allows you to create four types of modules, which are stored as files. A module owns all the objects that are created within it and is the basis of storage and ownership. The different types of modules in Form Builder are: • Form Modules: These make up the major chunk of your application. In a form module you retrieve and manipulate data that is arranged in the form of records. • Menu Modules: Form Builder enables users to create their own menus. The menu of an application is created and stored in a menu module. Users can customize or replace the default menu provided by Oracle Forms Developer. • PL/SQL Library Modules: This is a collection of all the PL/SQL program units that can be used by other modules in your application. • Object Library Modules: An object library allows you to store objects that you can reference and use in other modules. This feature enables you to create objects and distribute them throughout the organization.Confidential © SQL Star International Ltd. 28
  • 32. Oracle Form Builder Interface Components The following tools are provided in the Form Builder: • Object Navigator: This is a hierarchical tree structure of the objects used in the application. It is used to locate and manipulate the objects. • Property Palette: All objects in an application including the module have their own set of properties. These properties can be viewed and modified in the Property Palette.Confidential © SQL Star International Ltd. 29
  • 33. . • Layout Editor: Provides an interface to create and arrange the items and graphical objects in your application.Confidential © SQL Star International Ltd. 30
  • 34. • PL/SQL Editor: Allows you to develop subprograms in the Oracle Forms Developer and in the database.Confidential © SQL Star International Ltd. 31
  • 35. Form Module Objects Form modules make up a major portion of your application. They are made up of a large number of objects. A form module comprises the following: • Window: This is the largest object in a form module. Broadly speaking window is nothing but an empty picture frame. All the visual objects are contained within this frame. There are two types of windows: o Document or modeless window o Dialog or modal window • Canvas: A canvas is the interface where items are placed. A window can contain more than one canvas. There are four types of canvases: o Content Canvas o Stacked Canvas o Tab Canvas o Toolbar Canvas • Block: A block is the owner of items in a form; there can be more than one block in a form. All the items in a block are logically related. There are two types of blocks: o Data Blocks: These blocks contain items that are based on the database tables, views, stored procedures, a FROM clause query, or a transactional trigger. o Control Blocks: These blocks are not based on any database tables, but they are created to enhance the functionality of the application.Navigation in a Form ModuleWhen you run a form, you principally navigate by the way of items and blocksand not by canvases. Each item has a sequenced position within its block, andeach block has a sequenced position in the form.When a user requests to move to the next item in a block, focus will be set on thenext item in sequence, no matter wherever that may be. If the next item is on adifferent canvas, Oracle Forms Developer displays that canvas automatically.Similarly, users can request to move to the next block (or previous block). If thefirst item in this block resides on another canvas, then that canvas is displayedautomatically.Of course, if you can already see the item that you want to move to, then youmay click on it directly with the mouse. You can also program mechanisms intothe application to enable navigation in other ways.Confidential © SQL Star International Ltd. 32
  • 36. Master Versus Detail BlocksTo support the relationship between data blocks and their underlying base tables,you can define one data block as the detail (child) and other as a master (parent)data block. This links primary key and foreign key values across data blocks, andthereby synchronizes the data that these data blocks display.Forms Builder automatically generates the related objects and codes needed tosupport master-detail relationships. As the designer, if you need only thenrequest it. NOTE If your application requires it, you can also create independent data blocks in which there is no relationship between the two data blocks.Single-Record Versus Multi-Record BlocksYou can design a data block to show one record at a time (single-record block) orseveral records at once (multi-Record block). Usually, you create a single-record data block to show master data block and a multi-record data block toConfidential © SQL Star International Ltd. 33
  • 37. show detail data block. In either case, records in a data block that are currentlynot visible on the screen are stored in a block buffer.Multi-Block and Multi-Form ApplicationsTypically, a Forms Builder application consists of more than one data block. Withmore than one data block, you can do the following: • Separate the navigation cycle of one group of items from another. • Map each data block to a different database table (You can have one base table per data block.) • Produce a master-detail form, with a master data block and the corresponding detail data blocks that are related to the master. • You can create a large form module with many data blocks. Alternatively, you can create several smaller form modules with fewer data blocks in each. • Generally, a modular application with several smaller form modules has the following characteristics: Modules are loaded only when their components are required, thus conserving memory. Maintenance can occur on one module without regenerating or loading the others. Forms can call upon one another, as required.Confidential © SQL Star International Ltd. 34
  • 38. Block 1 Block 1 Block 1 Form C Block 2 Open Form Block 3 Block 2 Block 1 Form A Open Form Form B Block 4 Single Form Module Multiple Form Modules Forms and Data BlocksMany Blocks or Many Forms? • Parallel development can be carried out by different team members on different components.Here are some points to consider while grouping data blocks in the application: Data Blocks in the Same Form Data Blocks in Different Form Module Modules The data blocks can be directly linked The data blocks cannot be linked by the in master-detail relationships. standard interblock relations. Navigation between data blocks is Navigation between data blocks of handled by default functionality. different forms is programmed by the designer (although mouse navigation to visible items can be automatic).Confidential © SQL Star International Ltd. 35
  • 39. Library Management ModuleA Brief ExplanationBranch table stores the Unique ID number and location of different branches ofthe library.Member stores the details of the members with their details and to which branchthey belong.Member fee stores the details of the range of age, their fee and the grade.The Book table stores the details for the books present in each branch withnumber of copies.Transaction table stores the daily transaction of issuing to and receiving thebooks back from the members. Only those books are to be issued which arepresent in the BOOK table.Confidential © SQL Star International Ltd. 36
  • 40. Category stores the details of the category id and the type of books.Publisherdetails stores the details of the publisher.Libstaff stores the details of the librarian staff.Confidential © SQL Star International Ltd. 37
  • 41. SummaryIn this chapter, you have learnt that: • With Forms Builder, an Oracle Forms Developer component, you can develop form-based applications for presenting and manipulating data in a variety of ways. Forms Builder enables screen-based queries, inserts, updates, and deletes of data. • The Form Builder has three executables: Form Builder, Form Compiler, Form Runtime • Forms Builder provides powerful GUI and integration features. • Applications consist of form modules, menu modules, PL/SQL Library Modules and Object Library Modules. • Oracle Form Builder Interface has Object Navigator, Property Palette:, Layout Editor and PL/SQL Editor Components. • Object Navigator is a hierarchical tree structure of the objects used in the application used to locate and manipulate the objects. • When you run a form, you principally navigate by the way of items and blocks and not by canvases. • Form modules consist of logical data blocks. A data block is the logical owner of items. Items in one data block do not need to be physically grouped. Items in one data block can span several canvases. • Usually, you create a single-record data block to show master data block. • With more than one data block in a Form Builder application you can separate the navigation cycle of one group of items from another. • The data blocks can be directly linked in master-detail relationships and not in standard interblock relations. • Branch table stores the Unique ID number and location of different branches of the library.Confidential © SQL Star International Ltd. 38
  • 42. Exercise 1. What are the different Forms builder components? 2. Name the form builder interface components? 3. Explain the different kinds of Modules available along with their functionality. 4. In which situations, Single Record block and Multi-records block has to be created. Specify a scenario where creating Single record block and Multi- records block is apt. 5. List the available canvas in the Form builder?Confidential © SQL Star International Ltd. 39
  • 43. Chapter –4 Basic Form Module Creation Introduction Creating a Data Block Invoking a Layout Wizard Re-entrant Mode Save, Compile and Run a Form Module Creating a Template Form Text Files and Documentation File Extensions of Modules Runtime Modes Manipulate Data using DML Commands Creating a Control Block Deleting a Control Block Master-detail Form ModuleConfidential © SQL Star International Ltd. 40
  • 44. ObjectiveAt the end of this chapter, you will be able to: • Create a Data block • Know how to invoke a Layout Wizard • Describe the Re-entrant mode • Save, Compile and Run a form module • Create a template form • Understand Text Files and Documentation • Learn about File extensions of modules • Get an idea about Runtime modes • Manipulate data using DML Commands • Plan the way you want to create a Control block • Plan the way you want to delete a Control block • Create Master-detail relationships in form moduleConfidential © SQL Star International Ltd. 41
  • 45. IntroductionIn the process of creating a Form Module many form builder components areused. To start with the Object navigator, it is used to create an Empty Module. Itis only at this stage, you will find a window created by default. Data block, whichholds the actual data, has to be created through wizard or manually. Once this isdone, align the object or layout editor for further fine-tuning. Functionality to theitems is coded using the PL/SQL. Finally, to test the application, the form builderis executed using the run button on the standard tool bar.You will look at each of these phases in subsequent pages.Creating a Data BlockYou can create a Data Block manually or by using the Data Block Wizard. Thelater enforces integrity constraints by generating code automatically. Aftercreating the data block, use the Layout Wizard to create a good visualpresentation for the application.Starting the Data Block WizardYou can start the wizard in the following ways:Invoke Form Builder and choose the ‘Use the Data Block Wizard’ option in theForm Builder welcome screenIf you are already in the Form Builder then you can do one of the following: • Tools menu -> Data Block Wizard option • Click the right mouse button and select the Data Block Wizard option • In the Object Navigator, choose the Data Block node, and click the Create icon in the toolbar. The New Data Block dialog box appears as shown below.Choose the ‘Use the Data Block Wizard’ option. • In the Layout Editor, click the ‘Data Block Wizard’ icon from the toolbar.Creating a Data Block Using the Data Block Wizard In order to create the block you need to choose appropriate options on the three wizard screens: • Type screen: To select the object that the data block is based on.Confidential © SQL Star International Ltd. 42
  • 46. • Table screen: To select the database table on which the data block should be based • Finish screen: To create the data block and invoke the Layout Wizard To create a data block based on the Member table, the steps are: 1. In the Type screen, select the Table or View option to create the data block based on a database table as shown below. 2. Click Next to view the Table screen 3. Select the database table on which you want to create your data block. 4. If you are connected to the database, you can browse and select a table name or enter a table name. Enter the table name as Member. or If you are not connected to the database the Connect dialog box is displayed. Enter the username, password and the connect string. 5. Click the Refresh button to display a list of columns from the table you selected as shown below.Confidential © SQL Star International Ltd. 43
  • 47. 6. Select the column or columns you want to include in the data block. To select multiple columns press [Ctrl] and select all the columns and then release the [Ctrl] key or Click >> or << to include or exclude all the columns. Including a column will enable the user to see that column in the data block. If you exclude the column it will not appear in the data block. Click > or < to include or exclude a single column. 7. Check Enforce data integrity checkbox to enforce data integrity on the client side. The Form Builder does this by writing triggers. These triggers are dealt in a later session. 8. In the finish screen, select Create the Data block, then call the Layout Wizard option and click Finish as shown below.Confidential © SQL Star International Ltd. 44
  • 48. Invoking a Layout Wizard The Layout Wizard is the easiest way to design a new data block. The Layout Wizard has seven screens and you have to navigate and enter the required information in all the screens in order to design the Layout. The seven screens are: 1. Welcome screen: This screen is shown when you select the Layout Wizard option in the Data Block Wizard finish screen. You can also invoke the Layout Wizard manually in the Object Navigator by selecting Tools Layout Wizard. 2. Canvas screen 3. Data block screen 4. Item Prompt screen 5. Layout Style screen 6. Frames and Rows screen 7. Finish screen The steps to create the layout for the data block are: • On entering the Layout wizard Click Next to proceed further. • Select New Canvas from the list in the canvas screen as shown below to display the data block items.Confidential © SQL Star International Ltd. 45
  • 49. • Select Content as the canvas type in the Type list and click Next. • In the data block screen, choose the items from the Available Items option. Use the [Ctrl] key to select more than one item or click > or < to include or exclude selected items. Click >> or << to include or exclude all items. You can also drag and drop items to display in a certain sequence. Select all the items. • Select the item type from the Item Type list for each item. Form Builder provides the default type as Item. Click Next to display the Item screen. • In the Item screen, set the prompt values for every item, set the name, text display width and height as shown below:Confidential © SQL Star International Ltd. 46
  • 50. • Click Next to display the Layout Style screen. • Select the Form or the Tabular option as shown below and click Next to view the Frame and rows screen.Confidential © SQL Star International Ltd. 47
  • 51. • Enter the Frame title as Member Details • In the Number of Records Displayed field, enter a value. • Leave the Distance Between Records field as it is. • Select the Display scrollbar check box if you want a scroll bar for your data block (if the data block style selected is ‘Tabular’) and now click Next to view the last screen. • In the finish screen, click Finish to create a frame and layout the items for the data block. • The form is displayed in the layout in the Layout Editor. • After you have finished creating the form module and designing its layout, go to the Object Navigator and: • Change the default name of the frame to fr_Member. • Change the default name of the canvas to cnv_Lib. • Change the default name of the window to win_Lib.Confidential © SQL Star International Ltd. 48
  • 52. NOTE Changing the name of any form module object is the same as that described for changing the name of the Form.Re-entrant ModeWhen you create a form module, the Form Builder provides the form module witha default name MODULEXX. This name is displayed in the Object Navigator and inthe Property Palette.Create a form module and change its default name to frmLib.To change the name of the form module in the:Object Navigator: 1. Double-click the form module name 2. Type frmLib and press [Enter]Property Palette: 1. Double-click the Forms node in the Object Navigator or select the object and select the Property option from the Tools menu 2. Change the name of the form module by typing frmLib in the Name property as shown below:Confidential © SQL Star International Ltd. 49
  • 53. •Modifying the Appearance of the Data Block To modify the layout of an existing data block, you have to re-enter the Layout Wizard. You can re-enter the Layout Wizard by any of the following two methods: • In the Object Navigator: • Select the form module that you want to customize and click: Tools menu->Layout Wizard option • You can also invoke the wizard by clicking the right mouse button and selecting the Layout Wizard. • In the Layout Editor: • Select the frame of the data block and invoke the Layout Wizard either from the Tools menu or by right-clicking the mouse. • On invoking the Layout Wizard you can change the name of the data block by: Double-clicking the required data block and changing the name in the Object Navigator. Invoking the Property Palette by double clicking the node next o the data block you want to modify.Confidential © SQL Star International Ltd. 50
  • 54. Save, Compile and Run a Form ModuleOnce the process of creating a form module is complete, you should compile andsave it. Execution process follows immediately and then executes it.Saving a Form Module • Saving a form module can be done in two ways: • In the Object Navigator, select the File menu and click on the Save option. • Click on the Save icon in the toolbar of the Object Navigator. Both the above methods display the File dialog box: Enter the file name Click OK.Compiling a Form ModuleAn executable file must be created to run the form module. To do this you needto compile the form module either,Implicitly: • Select the Edit menu and select the Preferences menu option. • Check the Build before Running check box.Explicitly: • Select the File menu. Select Program Compile Module option. Ensure that the file is open. • Launch the Form Compiler component • Initiate the compiling process from the command line. (FRMCMP.exe)Running a Form ModuleYou can run a form module from: • A Web browser • The Form Runtime Component • The Command line • The Form Builder ComponentYou can run the form module from the Form Builder by clicking one of the fourrun methods, orIn the Object Navigator: Choose the Program menu and select the Run Formoption.Select one of the two run form options: • Web: This option is used to run a form module from a Web previewer. • Debug: This option is used to invoke the debug mode for the current runtime session.Confidential © SQL Star International Ltd. 51
  • 55. Creating a Template FormAnother method of creating a form is by using a template. This method providesa default starting point to users. You can create standard window layouts,toolbars, graphics and program units in a template form. Steps to create atemplate form are: Invoke the Form BuilderIn the Welcome screen choose the Build a form, based on a template option. Click OK.Text Files and DocumentationAll the files that are created by saving a form module are in binary format. Youcan convert these binary files into text files. The steps to convert a binary fileare: In the Object Navigator, choose File Convert Select the type of module you want to convert and the type you want to convert it to (Binary-to-Text). Choose Convert. To add functionality to your application you can produce documentation for your form module by: Selecting the form module that is to be documented in the Object Navigator. Choosing File Administration Object List Report from the menu. An ASCII file is created with .txt extension. The file has the same name as the module.File Extensions of Modules As you already know that Form Builder has four types of modules Form, Menu, PL/SQL Library and Object Library. Each of these is stored in a different format.Form Modules • .fmb: extension is used for the form design file, it represents form module binary. This file is portable across platforms • .fmx: form module executable or an fmx is the executable runfile. This file is not portable • .fmt: is a text export file and is portable. It represents a form module text. • Menu Modules • .mmb: Represents a menu module binary file. It is the menu design file and is portable. • .mmx: Represents a menu module executable. It is the executable runfile and is not portable. • .mmt: Represents a menu module text. It is a text export file and is portable.Confidential © SQL Star International Ltd. 52
  • 56. • PL/SQL Library • .pll: PL/SQL Library Document Binary. Files with this extension are design files but can be executed as it contains both the source code and executable code. This file is portable • .plx: PL/SQL Library Document Executable, it is an executable file that does not contain a source code. This file is not a portable file • .pld: PL/SQL Library Document Text is a text export file and is portable • Object Library • .olb: The object library module binary is a design file and is a portable file • .olt: The object library module text is a text export file and is portable • Forms Runtime Environment• The environment in which a form is executed is called the Forms Runtime Environment. Runtime Modes When you run a form, it is always in one of the two modes: • Enter Query mode • Normal mode Enter Query Mode In the Enter Query mode, you can specify a search criterion to retrieve data from the database. When you invoke the form in this mode, the form clears all its contents and waits for the user to key in the criteria. The key strokes that the user types are interpreted as search condition. Forms in this mode allows to: • Retrieve records • Use queries to retrieve restricted records • Use the WHERE clause to retrieve records You can know the number of rows that match your condition before records are retrieved by selecting Query Count Hits Enter Query mode does not allow to: Insert records Update records Delete records Navigate out of the current data block Exit the run time session Confidential © SQL Star International Ltd. 53
  • 57. Normal Mode Normal mode is used to perform DML operations on the database. In this mode you cannot retrieve restricted set of records. Normal mode allows to: Insert records Update records Delete records Commit Rollback Navigate outside the current block Exit the current sessionRetrieving Data You can retrieve data from the database to make modifications or to view data. You can retrieve data by performing restricted query or an unrestricted query.UnRestricted Query You can retrieve all the records from the database by performing an unrestricted query. You cannot query when you have an unsaved insert, update or delete. Use one of the following to query:In the Forms Runtime, select the Execute option from the Query menu.Click the Execute Query icon from the Forms Runtime toolbar.Restricted Query A Restricted query retrieves records that match your query criteria. You can use the following wildcards in your search condition: Wildcard Character Uses - Replace a single character % Replace any number of characters > Find values greater than < Find values less than < Find values not equal to >, ! = > Find values greater than or = equal to < Find values lesser than or = equal to # Use to make the SQL operator work (#betweenConfidential © SQL Star International Ltd. 54
  • 58. Wildcard Character Uses ’01-jan-1998’ and ‘10-jan- 2008’) Use the form module frmLib that you just created, to perform a restricted query: • Run the frmLib form module. • Select the Query menu, and click the Enter option or choose the Enter Query icon at the runtime. • Specify the search condition in the required Fields. • For instance: you want to know the book details whose number of copies is greater than 2. Enter >2 in the nnoofcopies field. Now, to Execute the query, select the Query menu and choose the Execute option or click the Execute Query icon. Using a Query/Where dialog box to query the frmLib form module. • In Oracle forms 10g, to invoke Query/Where dialog box, FORMS_RESTRICT_ENTER_QUERY has to be set to FALSE. By default it is set to TRUE. Set this parameter in Default.env file found in devsuite_homeFormsserver. • Run the frmLib form module. • Select the Query menu, select Enter option or click the Enter Query icon. • Enter a colon (:) followed by unique character variable name in one or more items field. • Select the Query menu, select Execute option or click the Execute Query icon.Specify the search condition in the Query/Where dialog box. Use theQuery/Where dialog box to specify a complex search condition using SQL. Also,use the dialog box to execute queries with OR or the ORDER BY clause. Click OK.For example: Enter the following in the Query/Where dialog box, to retrieve allthe member details of all the members whose age is between 18 and 56. : a between 18 and 56Manipulate Data using DML CommandsYou can manipulate records in the Normal mode. In this mode, anything that theuser types is interpreted as an insert and anything that the user keys over anexisting record is interpreted as an update.Steps to insert a record are: 1. Position the cursor on a blank record by:Confidential © SQL Star International Ltd. 55
  • 59. Scrolling down to a blank record Selecting Record Insert from the menu Click the icon for inserting records from the toolbar 2. Enter data 3. Steps to update a record are: Select the Query -> Enter option Enter the search condition to retrieve the records Select the Query -> Execute option to retrieve the records that match your search condition Select the record you want to update 4. Update the record 5. Steps to delete a record are: Select the Enter option from the Query menu Enter the search condition Select the Execute option from the Query menu to retrieve records Select the record you want to delete and delete the record by doing one of the following: o Select the Remove option from the Record menu o Click the Delete icon from the toolbarMaking Changes PermanentTo make inserts, deletes and updates permanent, do one of the following: • Select the Save option from the Action menu • Click the icon for saving in the toolbarIf you do not want to make inserts, updates and deletes option permanent, youshould clear the record. You can perform a rollback by choosing Action Clear Allfrom the menu.Display Database ErrorsAn error is displayed on the message line in the console area of your FormsRuntime window. This error message is not detailed. If you want any furtherdetails about the message, select the Display option from the Help menu.This opens a dialog box where the top half shows you the code; where there wasan error and the bottom half displays the Oracle Error message.Creating a Control BlockA data block that is not associated with the database is known as a control block.A control block does not interact with data but it exercises control over theapplication. Control blocks are used to enhance the functionality of theapplication. For example, you can create buttons to perform certain functions youneed for the application and place them in a control block.Confidential © SQL Star International Ltd. 56
  • 60. Steps to create a control block Controlblk in the frmLib form module: • In the Object Navigator, click on the Data Blocks node • Click the Create icon or select the Create option from the Navigator menu • The New Data Block dialog box is displayed, choose the “Build a new data block manually” option. • Open the Property Palette of the data block you just created and change its default name to Controlblk. A control block will not contain any items until you add them manually. Deleting a Block • Deleting a data block deletes all the items that are owned by that particular data block. However, the frame and its title are not deleted. To delete the frame and its title you have to do it manually in the Layout Editor. To delete a data block: • In the Object Navigator, select the data block you want to delete • Click the Delete icon in the toolbar or select the Delete option from the Navigator menu • Click Yes to delete the data block when an alert appears for confirmationMaster-detail Form Module In Form Builder, every form module contains one or more data blocks. These blocks can either be related with each other or they can be independent. To create a relation between blocks, you create a Master-detail form module.Master-detail Relationship A master-detail relation is also called as a parent-child relation. In order to have such a relation it is essential that the master or parent table contain the primary key, which is referenced by the detail or child table. When you create a master-detail block, triggers are created automatically by the Forms Builder to enforce the integrity constraints defined in the database. NOTE A master block can contain more than one detail block. A detail block can be a master to another detail block. A detail block can also have more than one master.Confidential © SQL Star International Ltd. 57
  • 61. Create a Master-detail Form Module A master-detail form module can be created explicitly or implicitly using the Data Block Wizard. We will create a master-detail form module based on the Branch and Book tables of the Library database. To create a master- detail block: 1. Create a form module and name it as desired, say FrmLibTrans. 2. In the form created, create a master block based on the Branch table. 3. After creating the master block go to the Object Navigator and invoke the Data Block Wizard to create a detail block based on the Book table. 4. Navigate and interact with all the pages in the Data Block Wizard till you see the master-detail page. 5. Uncheck the Auto-join data blocks check box. 6. Click the Create Relationship option. 7. The Relation Type dialog box opens. Select -> Based on a join condition option and click OK. 8. Choose Branch as the master block from the Data Block dialog box that is displayed and click OK. 9. In the master-detail page choose the detail item as cBranchID from the poplist and master item as cBranchID from the master item poplist. You can now see the join condition. 10. Click Next and finish the Data Block Wizard steps. Invoke the Layout Editor and finish creating and designing the data blocks. 11. In the Object Navigator, change the default window name and canvas name to WinLibTrans and CanLibTrans respectively. Ensure that the master block already exists in the form module before you create a master-detail relation. After you have completed creating a master-detail relationship: Form Builder will implicitly create an object called Relation under the master block in the Object Navigator. This relation will automatically handle the relationship between the blocks. A default MASTERDATABLOCK_DETAILDATABLOCK name is assigned to the relation; in this case it will be BRANCH_BOOK. Default triggers and program units are created to maintain the coordination between the two blocks. The following triggers are created automatically: ON-CLEAR-DETAILS ON-POPULATE-DETAILS ON-CHECK-DELETE-MASTERRun a Master-detail Form Module Running a master-detail form module is similar to running a basic form module. Click on the Run icon from the toolbar. At the runtime you will see that:Confidential © SQL Star International Ltd. 58
  • 62. When you query the master block, the corresponding detail records are also retrieved. Deletion of master records is not possible if corresponding detail records exist. Insertion of a detail record is implicitly associated with the current master record.Create a Relation Manually A Relation is an object that Form Builder creates to maintain the relationship and control the coordination between the blocks. There are two ways of creating a relation: Implicit: Implicit relation as you are already aware of is created when you create a master-detail form module. The relation is also given a default name of MASTERDATABLOCK_DETAILDATABLOCK. Explicit: Explicit relation can be created by setting the properties in the New Relation dialog box. Explicit relation is created between two data blocks whose relation is not yet established. Once you create a relation manually, triggers and PL/SQL program units that control the coordination between the blocks are created implicitly.Steps to Create a Relation Manually To create a relation explicitly, say with PublisherDetails table as the master and Book table as the detail you need to: 1. Create a data block based on the database table PublisherDetails in the form module frmLibTrans 2. Select the Relation node under the master block PublisherDetails in the Object Navigator. 3. Click the Create icon in the toolbar. A New Relation box is displayed. 4. Specify the name of the detail block as Book 5. Specify the Master-delete property 6. Specify the join condition as 7. PublisherDetails.cPublisherID = Book.cPublisherID 8. Click OKControl a Relation The functionality of the relation is enhanced by controlling the block coordination and deletes. This is done by modifying the relation properties. By setting the Delete Record Behavior property you can control the deletion of a record in the master block when the associated records exist in the detail block. The following properties control the master deletes. Non-Isolated: By setting this property you can prevent the deletion of master records when corresponding detail records exist. Default property is set to ‘Yes’. Cascading: By setting this property you can delete all the detail records when a master record is deleted. But the commit message will show only the number of master records that were deleted. Isolated: By setting this property you can delete the master record even if corresponding detail records exist.Confidential © SQL Star International Ltd. 59
  • 63. NOTE The default setting is Non-Isolated. When you change the property from the default value to Cascading, Form Builder replaces the ON-CHECK-DELETE-MASTER trigger .with a PRE- DELETE trigger. Changing the property from Non-Isolated to Isolated deletes the ON-CHECK-DELETE-MASTER trigger. Coordination Property Set the coordination property to control the display of the detail block records whenever the master block is queried. The coordination property options are: Default: When a user or trigger changes the master record, this property enforces the coordination of the blocks. Deferred with Auto Query: Processing of the detail query is postponed until the cursor is in the detail block. Deferred Without Auto Query: Additional query criteria can be specified in the detail block before querying. Prevent Masterless Operations: Querying or inserting into a detail block is not allowed till the corresponding master record is displayed. Confidential © SQL Star International Ltd. 60
  • 64. SummaryIn this chapter, you have learnt that: • Object navigator is used to create an Empty Module. • You can create a Data Block manually or by using the Data Block Wizard. After creating the data block, use the Layout Wizard to create a good visual presentation for the application. • To create the block you need to choose appropriate options on the three wizard screens: Type screen, Table screen, Finish screen • The Layout Wizard has seven screens to navigate and enter the required information for designing the Layout. • When you create a form module, the Form Builder provides the form module with a default name MODULEXX. • To modify the layout of an existing data block, you have to re-enter the Layout Wizard. After invoking the Layout Wizard you can change the name of the data block • Once the process of creating a form module is complete, you should compile and save it. You can run a form module from a Web browser, Form runtime component, the Command line and the Form builder component. • You can also create a form by using a template. • When you run a form, it is either in enter query mode or normal mode. • In Normal mode anything that the user types is interpreted as an insert and anything that the user keys over an existing record is interpreted as an update. • A data block that is not associated with the database is known as a control block. • You can create a Master-detail form module to create a relation between blocks. • The functionality of the relation is enhanced by controlling the block coordination and deletes which is eventually done by modifying the relation properties.Confidential © SQL Star International Ltd. 61
  • 65. Lab ExerciseModule containing Single Block 1. Create a new form module. Create a new single block using data block wizard. Base it on the BOOK table and include all columns. 2. Using the layout wizard, place BOOK block on the new canvas. As you pass through the layout wizard change the prompt according to the following specification. Choose the Style as Form and show just one record at a time. 3. Rename the canvas name to CV_BOOKS 4. In the layout editor, reposition the items and edit the prompts. o Now on the canvas select the frame and remove. Create a rectangle on the canvas such that it fits the block items. o Add a label as Book Details. o Now change the canvas background color to gray4 and rectangle background color to gray16. 5. Save the new module as BOOK_mac_no where mac_no is the machine number on which you are working. 6. Run your form module and execute a query. Your book information should resemble as follows:Confidential © SQL Star International Ltd. 62
  • 66. • Query the books, which are present only in ‘01ADLNJ’ branch. • Give the details of the books published in the year from 1996 to 1998 . • Exit the run-time session and return to forms builder. • Change the form module name in the object navigator to BOOKS. • Save and compile the form module.Module containing multiple blocks: Master-DetailsRelationships1. Create a new form module. Next, Invoke the data block wizard to create a block. BRANCH based on BRANCH table. Create a block BRANCH by using the data block wizard. Base it on the BRANCH table and include all the columns except CPHONE and DESTBL. o Display the BRANCH block on a new content canvas called CV_BRANCH and show just one record at a time. o Use a form style layout.2. Create a new block by using the data block wizard. Base it on the MEMBER table and include all the columns.3. Create a relationship between BRANCH and MEMBER where BRANCH will serve as a master block and MEMBER will be the detail block.Confidential © SQL Star International Ltd. 63
  • 67. When, continuing in the layout wizard make the following changes in MEMBER block. o Display all items except CBRANCHID on the CV_BRANCH canvas. o Use a tabular style of layout. o Display 5 records in this detail block on the same canvas as the master block.After you finish, your form would look as below:Change the order of the blocks in the object navigator, moving the MEMBER blockafter the BRANCH block.Save the new module as BRANCHXX, where XX is the unique number. Now createanother new block with following specification.Base it on the TRANSACTION table. Place the items of this block on a new contentcanvas called CV_TRANSACTION. o Use a tabular style layout and include a scroll bar. o In the object navigator, move the TRANSACTION block after the MEMBER block. o Do not create any relationship between blocks at this stage.The transaction details would be something like this:Confidential © SQL Star International Ltd. 64
  • 68. 4. Create a relation called MEMBER_TRANSACTION explicitly between the MEMBER and TRANSACTION blocks. Ensure that TRANSACTION details should not be executed independent of MEMBER table. i.e. No query or insert operation is allowed unless parent is displayed. Save and Compile your form module. Click Run Form to run your form. Execute all the block. Navigate through the blocks so that you see the TRANSACTION block. Exit the run-time session, close the browser, and return to Forms Builder. Change the form module name in the Object Navigator to BRANCH and saveit.5. Create a non-base block in the BRANCHXX form. Name this block asCONTROL. o Set the Database Data Block, Query Allowed, Insert Allowed, Update Allowed, and Delete Allowed Database properties to NO. o Set the Query Data Source Type property to None. Set the single record property to yes. o Leave other properties as default. Move the CONTROL block to end of the all blocks. Note: The Compilation errors window displays a warning that advises you that the CONTROL block has no items. This is expected (until you add some items to the CONTROL block in a later lesson).Confidential © SQL Star International Ltd. 65
  • 69. Chapter 5 Discuss Data Block Properties Data Block Properties Manipulate the Frame Properties Opening Multiple Property Palette Multiple Object PropertiesConfidential © SQL Star International Ltd. 66
  • 70. ObjectiveAt the end of this chapter, you will be able to: • Describe the Properties of a Data block • Learn to manipulate the Frame properties • Know how to open Multiple property palette • Understand the concept while using Multiple object propertiesConfidential © SQL Star International Ltd. 67
  • 71. Data Block Properties Every object in the form builder has certain properties associated with it. These properties have default values assigned to them. You can change these default values by assigning new values in the Property Palette of each and every object created. A data block is the owner of the items created under it. All these items have their individual properties. The data block itself also has some properties. You can customize the appearance and behavior of the data block and its items by setting their properties. To change the behavior of a data block invoke the data block Property Palette and set the properties.Property Palette To invoke the Property Palette of an object, use one of the following methods: • In the Object Navigator: 1. Select the object 2. Select the Property Palette menu option from the Tools menu • Double-click the object icon in the Object Navigator • In the Layout Editor, double-click the object • In the Object Navigator or the Layout Editor 1. Select the object 2. Click the right mouse button 3. Select the Property Palette option from the pop-up menu that is displayedYou can also invoke property palette by selecting the object->F4 The tools provided by the Property Palette are: • Property List: The property list is a list, which contains the property names and their corresponding values. The properties are grouped under nodes. You can expand or collapse a node by using the property palette icons. You can navigate to each of the property name and set the required value. • Find field: This field enables you to search for a property name quickly and easily. • Toolbar: It provides quick access to commands. For example cut and paste.Using the Property Palette The Property Palette has the following property controls with which you can manipulate properties: • Text field: This field is displayed when the value of the property can be set by entering the text. If the text that has to be entered is long then an icon appears, by clicking the icon you can invoke an editor to enter the text. • Poplist: This is displayed when there is a fixed set of values. Click on the arrow to display the list and choose a value. You can also double-click on the property name to view the values.Confidential © SQL Star International Ltd. 68
  • 72. • LOV window: A list of values is displayed when there is a large list available. Invoke the list of values by clicking the icon in the property value column. Select the appropriate value by clicking it. • More button: This is displayed when additional settings are needed. Click the More button to open a dialog box.Property Palette Icons In the Property Palette every property has an icon on its left. The following are the icons that you will encounter in a Property Palette. • Circle: Signifies the default value. • Square: Signifies that the default value has been changed. • Arrow: Signifies an inherited property value. • Arrow with a cross: Signifies an inherited value that is overwritten. Changed Default Overridden InheritedVisual Attributes Font, color, and pattern properties set for form and menu objects are Visual Attributes. Visual Attributes are created in the Object Navigator. Once a visual attribute is created it can be used for different forms, menus and items. Every interface object in a form module has a property named Visual Attribute Group. By setting this property to ‘DEFAULT’ or user- defined visual attribute, you can influence the appearance of that particular item. Steps to create a visual attribute say vattLib and attach it to the Member data block in the frmLib form module: 9. Select the Visual Attribute node in the Object Navigator and click the Create icon. 10. Invoke the Property Palette, change the default name to vattLib and set the following properties: Foreground Color: ‘Black’ Background Color: ‘Grey20’ Font Name: ‘Arial’ Font Size: ‘10’Confidential © SQL Star International Ltd. 69
  • 73. Font Weight: ‘Light’ Font Style: ‘Plain’ 11. Invoke the Property Palette for the Member data block, set the Current Record Visual Attribute Group property to vattLib to highlight the current record at runtime. 12. Another type of visual attribute is the partial visual attributes. These are similar to visual attributes. The only difference is that you need to set only those properties that will be used by objects that use them.Manipulate the appearance and behavior of a Data Block A data block has properties that are divided into groups: • General • Navigation • Records • Database • Advanced Database • Scrollbar • Visual Attribute Group • Color • InternationalNavigation Properties Invoke the Property Palette of the data block by double clicking the data block node to the left of the data block. When you set the following properties, it allows you to control the navigation in a data block: • Navigation Style: When you try to navigate beyond the last item in a record, the cursor is returned to the first item of the same record. This is the default setting. You can control the cursor position by setting its property to any of the following options: Same Record: This is the default setting. If you try to navigate beyond the last item in a record the cursor will return to the beginning of the record. Change Record: The cursor will move to the next record when you try to navigate beyond the last item in a record. Change Data Block: The cursor will move to the next data block in the form module • Previous/Next Navigation Data Block: In a form module all the data blocks will have a pre-determined order for navigation. By default, the pre-determined order of navigation is based on the order in which data blocks are positioned in the Object Navigator. By specifying the name of the data blocks in the Previous and Next Navigation Data Block property fields, you can control the navigation to the previous and next blocks.Confidential © SQL Star International Ltd. 70
  • 74. Database Properties The database properties are important to the application developers. These properties will enforce integrity constraints. It will also allow query, insert, update, delete and the number of records that are to be retrieved on querying. Some of the important database properties that control the behavior of the data blocks are: • Database Data Block: Set this property to ‘Yes’ if the data block is based on a database object and ‘No’ when the data block is not based on a database object. For example, a control block. • Enforce Primary Key: Set this property to ‘Yes’ for the Form Builder to check that the records are unique and satisfy the primary key condition before they are inserted into the table. • Query Allowed: Set this property to ‘Yes’ to allow queries on the data block. • Insert/Update/Delete Allowed: Set this property to ‘Yes’ if you want the user to enable to manipulate data. If set to ‘No’ a user will not be able to perform DML operations on the data block. • DML Array Size: Set this property to control the number of records that will be sent to the server for batch processing. • WHERE Clause: By specifying a WHERE clause for the data block, you restrict the number of records that are retrieved. If the user gives a search condition in the Enter Query mode, then this WHERE clause is automatically appended to the user search criteria. • ORDER BY Clause: Set this property to determine the order of retrieval of the records. You can use the Query/Where dialog box at run time to modify this order. • Optimizer Hint: This property improves the performance and efficiency of the database transactions. Form Builder passes a hint string to the optimizer while constructing an implicit SQL statement on the data block. • Update Changed Columns: If a user is updating a record, set this property to ‘Yes’ to send values to the server of only those columns that were updated instead of the entire record. • Enforce Column Security: Items in the data block can be updated only if the user has the permission to update them. Set this property to ‘Yes’ to restrict access to sensitive database columns.Record Properties The following are the important record properties: • Query Array Size: This property controls the number of records that will be fetched from the database. • Number of Records Buffered: Set this property to specify the number of records that will be kept in the client memory. The default value is 3. • Current Record Visual Attribute Group: Set this property to associate a visual attribute to the data block to highlight the current record.Confidential © SQL Star International Ltd. 71
  • 75. • Number of Records Displayed: Set this property to specify the maximum number of records that can be displayed on the canvas. • Query All Records: Set this property to retrieve all the records that match the query criteria. • Record Orientation: Set this property to display the records in a data block vertically or horizontally. • Single Record: This property is specific to a control block. Set this property to ‘Yes’ for a data block containing summary calculated item.Scroll Bar Properties The following are the scroll bar properties: • Show Scroll Bar: Set this property to ‘Yes’ to display a scroll bar for the data block. Set this property to ‘No’ to delete an existing scroll bar. • Scroll Bar Canvas: Set this property to specify on which canvas the scroll bar has to be created and displayed. • Scroll Bar Orientation: Set this property to specify if the scroll bar has to be displayed horizontally or vertically. • Reverse Direction: Set it to ‘Yes’ to make the scroll bar scroll in the reverse direction.Manipulate the Frame Properties All the items within a data block are automatically arranged in a frame when you associate the frame with a block. Therefore, a data block can be associated with only one frame. Manipulate the frame properties to design the arrangement of items within a frame. A few of the frame properties are: • Layout Data Block: To specify the data block with which the frame should be associated. All the items of the data block are arranged in this frame. • Update Layout: Its settings are as follows: Automatically: Any changes in the frame layout property or movement or resizing of the frame results in the layout being automatically updated. Manually: The layout is updated when you use the Layout Wizard to modify the frame or when you click on the Update Layout in the Layout Editor. Alternatively you can select the Arrange menu and choose the Update option in the Layout Editor. Locked: The layout cannot be updated. • Frame Title Alignment: To specify the position of the frame title. • Number of Records Displayed: To specify the number of records those are to be displayed. • Layout Style: To specify ‘Form’ or ‘Tabular’ • Distance Between Records: To specify the distance between two records in a frame.Confidential © SQL Star International Ltd. 72
  • 76. • Bevel: To specify the type of frame border. The options are: Raised Lowered None Inset Outset PlainOpening Multiple Property Palette As you already know all the visual objects of the data block have properties associated with them. These properties have default values and the user can modify these values in the Property Palette. You can open multiple property palettes, compare and set these properties. You can display the properties of an object in multiple property palettes by selecting the object in the object Navigator and then by pressing F4. By Double clicking the object icon pressing the [Ctrl] key in the Object Navigator when a Property Palette is already open for an object. This will open another Property Palette for the object. You can display the Property Palettes for more than one object at a time: • Invoke the Property Palette of an object. • Click the Freeze icon on the Property Palette toolbar. • Now open the Property Palette for the second object by using F4. It will open in a separate window.Confidential © SQL Star International Ltd. 73
  • 77. Two palettes for one item Two palettes for two itemsMultiple Object Properties You can set properties for multiple objects in a data block at the same time. In the Object Navigator select the objects that you want to set properties for and invoke the Property Palette to display a combination of properties for all the objects that you selected. To choose a combination of properties set either of the two options: Union: You can set the combination to union by clicking the Union/Intersection button in the Property Palette toolbar. This will display the common as well as the unique properties of all the objects that you select. Intersection: This is the default option. Use this option to display only the common properties of all the objects that you select. • When you click on Union/Intersection button in the toolbar it will always toggle between the two options. • Steps to set properties for multiple objects: In the Object Navigator invoke the Property Palette for one of the objects. Press the [Ctrl] key and click on the objects whose properties are to be modified simultaneously. Holding the [Ctrl] key click the right mouse button and select the Property Palette option.Confidential © SQL Star International Ltd. 74
  • 78. Select the Union/Intersection button to display the required properties. Modify the properties as required. The modifications you make here are applied to all the objects that you select.Copying Properties You can copy properties and apply them to other objects in your form module by: Invoking the Property Palette and setting the values for the properties that are to be copied. The Property Palette can belong to a single object or a combination of objects. Selecting All properties: To copy all the property values, select the Edit menu in the Property Palette and choose the Select All option. Selecting specific properties: To copy some specific properties, press the [Ctrl] key and select each property individually by: • Clicking the Copy Properties icon in the Property Palette toolbar. • Selecting the object (from the Object Navigator) in which the properties are to be copied. Invoke its Property Palette. • Clicking the Paste Properties icon in the Property Palette toolbar. All the properties that you copied will be applied.Property Classes A Property Class is a Form Builder object that contains properties and property values, which can be inherited by other objects. Creating a Property Class and saving it for future applications will save a lot of development time, as there will not be a need of defining property values again for all the objects. More of this will be discussed later in subsequent chapters.Confidential © SQL Star International Ltd. 75
  • 79. SummaryIn this chapter, you have learnt that: • There are various Data Block properties and features of Property Palette and how to invoke a property palette, etc. • To invoke the Property Palette of an object, you can either select the object or you can select the Property Palette menu option from the Tools menu given in the Object Navigator: • The Property Palette has Text field, Poplist, LOV window, More button following property controls with which you can manipulate properties: • In the navigation properties, Navigation Style is the default setting by which you can control the cursor position by setting its property to the same record, change record and change data block. • The database properties allow query, insert, update, delete and the number of records that are to be retrieved on querying. • You can copy properties and apply them to other objects in your form module by invoking the Property Palette and setting the values for the properties that are to be copied which can belong to a single object or a combination of objects. • Some of the important record properties are Query array size, Number of records Buffered, Current record visual attribute group etc. • To design the arrangement of items within a frame, you can manipulate the frame properties like in case of Layout data block, Frame title alignment and Distance between records etc. • You can set properties for multiple objects in a data block at the same time. • A Property Class is a Form Builder object that contains properties and property values, which can be inherited by other objects.Confidential © SQL Star International Ltd. 76
  • 80. Lab Exercise 1. Create a visual attribute named Current_Record with following specification: Background Color: Gray16 Foreground Color: Black Fill pattern: Transparent Use this visual attribute for Member and transaction block present in the BRANCHXX module. 2. Check the navigation of the Member block. Make the necessary changes so that the user is able to navigate between the records using tab. 3. Ensure that the records retrieved in the BRANCH block are sorted by the CBRANCHID. 4. Try to open the property palette of Branch and Member blocks together and compare them. 5. Try multi-section of properties between any two blocks in BranchXXX. Compile and save the form.Confidential © SQL Star International Ltd. 77
  • 81. Chapter 6 Creating Text Items, LOVs and Editors Methods to Create Text Items Controlling the Appearance of a Text Item Creating a Multi-line Text Item Modify Text Items Navigation of a Text Item Enhancing the Functionality of a Text Item Using Helping facility List of Values (LOVs) Defining a LOV Creating LOVs Discuss the LOV Properties Invoking the LOV EditorsConfidential © SQL Star International Ltd. 78
  • 82. ObjectiveAt the end of this chapter, you will be able to: • Use Text items • Know the Methods to create Text items • See how to Control the appearance of a Text item • Create a Multi-line Text item • Associate Text with an item • Change the Prompts by replacing the existing prompts • Modify Text item • Control the navigation of a Text Item • Alter the Database Properties • Enhance the Functionality of a Text item • Learn the use of help facility • Identify, define and create List of Values (LOVs) • Remember the LOV Properties • Know how to associate an LOV with a Text Item • Invoking the LOV • EditorsConfidential © SQL Star International Ltd. 79
  • 83. Text Items As you already know a form module consists of data blocks and the data blocks in turn are made up of objects or items. A text item is a user interface object, which enables the user to manipulate data. You can modify the properties to alter the appearance and behavior of the text items. A text item will allow you to: • Query data • Insert data • Update data • Delete dataMethods to Create Text Items A text item can be created either by: • Using the Object Navigator • Using the Layout Editor • Converting an existing item • Using the wizardsCreating a Text Item using the Object Navigator The steps to create a text item in the Object Navigator are:1. Select the required data block.2. Select the Items node under the data block.3. Click the Create icon. A new item with a default name is displayed in the Object Navigator.4. Invoke the Property Palette by double-clicking the icon to the left of the new item.5. Set the other properties. NOTE Convert an existing item into a text item by invoking the Property Palette of the required item and set its Item P ‘T I ’Creating a Text Item using the Layout Editor The steps to create a text item in the Layout Editor: 1. Select the required data block from the Block pop list. 2. Click the text item button from the toolbar and place it on the canvas. 3. Invoke the text item Property Palette by double-clicking the text item.Confidential © SQL Star International Ltd. 80
  • 84. 4. Set the text item properties. NOTE The new text item that you created should be associated with a canvas for it to be displayed at runtime. You can do this by setting the Canvas property in the Property Palette of the new itControlling the Appearance of a Text Item You can control the appearance of a text item by setting the following group properties: • General Property • Item Type: Select the type of item from the item pop list. • Physical Property • Visible: Set this property to display or hide the item • Canvas: Set this property to display an item on a specific canvas. If you do not specify a canvas then the item will not be displayed. • X Position: Determines the X coordinate of the item on the canvas • Y Position: Determines the Y coordinate of the item on the canvas • Width: Determines the width of the text item • Height: Determines the height of the text item • Rendered: Setting this property to ‘Yes’ conserves the system resources. The resources used to display a rendered item are released when that item is no longer in focus. • Records Property • Current Record Visual Attribute Group: Specify the visual attribute that is to be associated with this item. • Distance Between Records: Specify the amount of space required between two instances of the item • Font and Color Property • Font Name: Select the font you require from the font list. • Font Size: Specify the size of the font • Font Style: Specify the font style • Font Spacing: Specify the amount of space between charactersConfidential © SQL Star International Ltd. 81
  • 85. • Foreground Color: Specify the foreground color for the text item • Background Color: Specify the background color for the text item • White on Black: Setting this property will display text in white color on a black background on a monochrome monitor • Prompt Property: Prompt is the label associated with the text item. You can manipulate these labels by modifying the following properties: • Prompt: Set the text label for the text item • Prompt Display Style: Set the display style of the prompt from First Record, Hidden and All Records. • Prompt Justification: Set this property to justify the prompt • Prompt Attachment Offset: Set this property to specify the distance between the prompt and the text item.Creating a Multi-line Text ItemYou can create a multi-line text item to display large text values like addressesand description. To create a multi-line text item for the vAddress text item in theMember data block, do one of the following: • Create a text item and then in its Property Palette set the Multi-line property to ‘Yes’. • Convert an existing item by invoking the Property Palette of the item and setting its Multi-line property.Associate Text with an ItemWhen you create a data block, items are created with a default prompt but whenyou create a text item manually the text item will not have a default prompt. Youcan specify a prompt for the item by creating a boilerplate text. To associate theprompt created to the text: 13. Invoke the Layout Editor 14. Create a boilerplate text for the text item 15. Select the text item and the boilerplate text that you have created 16. Click the Associate Prompt button on the toolbar Alternatively, you can create a prompt for your text item in its Property Palette by specifying the prompt in the Prompt property. Change the Prompts by replacing the existing prompts.Confidential © SQL Star International Ltd. 82
  • 86. Modify Text ItemsYou can modify the appearance and behavior of a text item by setting itsproperties in the Property Palette.Controlling a Text Item Set the following Data properties of a text item to control the way data is displayed. • Data Type: Specify the data type of values that the item should accept. • Maximum Length: Set this property to specify the maximum number of characters that are allowed for the text item. If the maximum length exceeds the display width of the item, Form Builder automatically enables the user to scroll horizontally. • Required: Set this property to ‘Yes’ so that the user would have to compulsorily enter a value before navigating out of the item or record.• Lowest Allowed Value: Set this property to specify the minimum value for the text item.• Highest Allowed Value: Set this property to specify the maximum value for the text item.• Synchronize with Item: Set this property to specify the item from which the text item will inherit values.Confidential © SQL Star International Ltd. 83
  • 87. • Copy Value from Item: Set this property to specify the data block and the item from which the text item will copy values into the text item. This property can be used to link data blocks. When you create a master- detail block, Form Builder will automatically set this property for the foreign key item in the detail block.• You should disable user input in this item to ensure that the foreign key relationship is not violated• Format Mask: Set this property to specify the format for the text item. Using the FX format mask in a date value ensures that the user must enter the date exactly as specified in the mask. You can use the standard SQL formats for dates and numbers. For example, DD/MM/YY and $999.99. Enclose embedded characters like hyphen (-) and brackets () in double quotes.• Initial Value: Set this property to specify a default value for the text item. These values can be changed at runtime. The initial value has to be compatible with the data type of the item. The initial value should be within the range, if the Lowest Allowed Value and the Highest Allowed Value are specified. To set an initial value use any of the following values: 3. Raw Example: 01ADLNJ 4. System variable Use the following variables to give the operating system date and time Variable Format $ D $ D D - A M T O E N $ - $ Y Y $ D $ D D - A M T O E N T - I Y M Y E Y S Y $ h $ h : m i:Confidential © SQL Star International Ltd. 84
  • 88. [ s s ] $ H $ h T : I m M i: E [ S s $ s $ ] Use the following variables to give the current database date and time Variable Format $ DD- $ MON D -YY B D A T E $ $ $ DD- $ MON D - B YYYY D hh: A mi:[ T ss] E T I M E S $ $ $ Hh: $ mi:[ D ss] B T I M E $ $Navigation of a Text Item The default navigation sequence is the same as the items displayed in the Object Navigator. You can control theConfidential © SQL Star International Ltd. 85
  • 89. navigation of a text item by setting its Navigation Properties. The important Navigation properties are: • Keyboard Navigable: Set this property to ‘Yes’, to navigate to an item during default navigation with the help of function keys or menu items. If you set ‘No’ this property to, Form Builder will skip the item during default navigation and go to the next item in the navigation sequence. • Previous Navigation Item: Set this property to specify from which item the user should navigate to the current item. • Next Navigation Item: Set this property to specify the item to which the user should navigate to from the current time. Set the Keyboard Navigable and Enabled properties to navigate and interact with the item. Keyboard NavigableEnabled YES NO Item can be navigated and Item is not navigated during the manipulated using the mouse. default navigation. But user can YES navigate and manipulate the item using a mouse Item is excluded during default Item is not navigated during default navigation. Manipulation with navigation and manipulation with NO the mouse is not allowed. mouse is also not allowed Altering the Database Item Properties You can modify and enhance the relationship between a text item and its associated database column by modifying the Database group properties. The following are the important Database properties: • Database Item: Set this property to specify if the item is based on a database table or a control block. • Column Name: Set this property to specify the corresponding column in the database table. • Primary Key: Set this property to specify that the item corresponds to the primary key column in the database table. • Query Only: Set this property to specify that the item can be queried but insertion and updation are not allowed. Confidential © SQL Star International Ltd. 86
  • 90. • Case Insensitive Query: Set this property to determine the case where a user can query. • Update Only If NULL: Set this property to specify that the item should allow update only if the current value of the item is null. • Lock Record: Set this property to specify that the record should be locked during an update. This property does not apply for the base table items.Enhancing the Functionality of a Text Item You can enhance the functionality of a text item by setting its Functional properties. The important Functional properties are: • Enabled: Set this property to allow navigation and manipulation of a text item with the mouse. • Justification: Set this property to justify the text in the item. • Wrap Style: Set this property to a multi-line text item to enable it to wrap on to the next line. • Case Restriction: Set this property to force the user input into ‘Upper’, ‘Lower’ or ‘Mixed Case’. • Conceal Data: Set this property to hide the value in a text item. • Popup Menu: Set this property to display the popup menu for the current form module.Using Help facility You can provide context sensitive help to the user by using the following Help properties: • Hint: Use this property to display item-specific help text in the message line of the console. • Display Hint Automatically: Set this property to automatically display the hint message.List of Values (LOVs) List of Values (LOV) is a form module object, which is displayed as a scrollable popup window containing a pick list, when invoked at runtime. An LOV window will allow a user to choose a value from the pick list or dismiss the window but it will not allow the user to enter any other values. An LOV can be accessed by any text item within the form module, as it is defined at the form level. Features of LOVs: • They can be created with multiple column values in it. • The values in the pick list change automatically when there is a change in the source data. • The user can invoke the LOV from any text item. • An LOV can be associated with multiple items.Confidential © SQL Star International Ltd. 87
  • 91. • LOVs can be created to use data that is already in the form, instead of accessing the database. • Auto reduction feature in the LOVs help the user to access a particular value easily and efficiently with a minimum number of keystrokes.Defining a LOV When defining a LOV, you use the following objects: • Record Group: It is a Form Builder object that stores the values that are displayed by an LOV. It is a table like structure with rows and columns, stored in the forms runtime memory. Record groups contain the values that are displayed by an LOV. You can create multiple LOVs based on the same record group. • LOV: It displays the values of the columns that are stored by the record group in the popup window. • Text Items: The text item is the one, which receives the values returned by the LOV. You can have the same LOV associated to several text items.Creating LOVs You can create an LOV using the LOV Wizard. The LOV Wizard can be invoked by one of the following methods in the Object Navigator: • Selecting the LOV Wizard option from the Tools menu • Clicking the LOV node and click the Create icon • Selecting the LOV node and after clicking the right mouse button, select the LOV Wizard optionSteps to Create an LOV To create an LOV say, lvbranch, in the Member data block in the frmLib form module, which will display the branch id and branch name to populate the branch id field at runtime, the steps are as follows:1. In the welcome screen of the LOV Wizard click Next.2. In the source screen, select an existing record group or create a new record group based on a query. Click Next.Confidential © SQL Star International Ltd. 88
  • 92. 3. Specify the query to create a record group by any of the following methods: • Clicking the Build SQL Query button to use the Query Builder. • Clicking the Import SQL Query button to import a query from a file. • Entering a query in the SQL Query Statement field. Click the Check Syntax button.Confidential © SQL Star International Ltd. 89
  • 93. • Click Next4. Select the columns that you require for the LOV. Select the cBranchID and the cBranchName columns. Click Next to display the column properties screen.Confidential © SQL Star International Ltd. 90
  • 94. 5. Specify the title as Branch ID and Branch Name, width and return value for all the updation columns that you have selected.6. Click the Lookup Return Item button and select the Member.cBranchID column to store the value returned by the LOV. Click Next to display the LOV display screen.Confidential © SQL Star International Ltd. 91
  • 95. 7. Specify the LOV title as Branch Details, width and height of the LOV popup window. Click Next.8. In the next screen the options are: • Specify the number of records that are to be retrieved at a time from the database.Confidential © SQL Star International Ltd. 92
  • 96. • Refresh record group before displaying LOV. • Let the user filter records before displaying. Click Next .9. Click Finish to create the lvBranch LOV.Discuss the LOV Properties The properties of LOVs are: • Title: To specify a title for your LOV. • Width: To specify the display width for the LOV. • Height: To specify the height for the LOV. • Filter Before Display: Set this property to display a dialog box that enables the user to enter a search condition before invoking the LOV. • Automatic Display: Set this property to automatically invoke the LOV when the cursor is in the associated text item. • Automatic Refresh: Set this property to ‘Yes’ if you want the record group to execute the query every time the LOV is invoked. • Automatic Skip: Set this property to ‘Yes’ if you want to navigate to the next item once a value is selected from the LOV.Confidential © SQL Star International Ltd. 93
  • 97. • Automatic Column Width: Set this property to automatically set the width of each column to display the entire column title. • Column Mapping Properties: Invoke the LOV Column Mapping dialog box by clicking the More button. Set the following properties: • Column Title: Specify a heading for the column. • Column Names: Set this property to specify a column for mapping. • Return Item: Specify the form item or variable to which the value of the LOV should be returned. Use any of the following: − block_name.item_name − GLOBAL.variable_name − PARAMETER.parameter_name − NULL, if the column value is not returned from the LOV • Display Width: Set this property to specify the width of the column display. If you want the column to be hidden, but the value to be returned then set this field value to 0.Confidential © SQL Star International Ltd. 94
  • 98. Associating an LOV with a Text Item You must specify the LOV name in the Property Palette of the text item to invoke the LOV from that item. Steps to associate LOV lvbranch to cBranchID text item are:1. In the Object Navigator, select the cBranchID text item.2. Invoke the Property Palette of the cBranchID text item by double-clicking the item node.3. Set the List of Values property to lvbranch by selecting it in the LOV pull down list.Invoking the LOVDuring runtime, the LOV lamp is displayed on the status line when the cursor is ina text item that has a LOV attached to it. Press the function key or from the Edit menu select the Display List option in the forms runtime. o Select a value from the displayed list. o Click OK. SELECT cBranchID FROM Branch Branch table LOVs and Record GroupsCreate Dynamic List of ValuesDynamic list of values is a LOV that can be attached to more than one item.Generally single LOV can be attached to only one field. In dynamic list of values,we attach a single LOV to more than one field. More on this will be dealt later.Confidential © SQL Star International Ltd. 95
  • 99. EditorsAn Editor is a dialog box associated with a text item. An editor not only providesthe space to type in large text but it also provides the functionality to find andreplace text. The following are the two types of editors in the Forms Developer: • Form Builder default editor • User created editor Every text item is provided with a default editor, but you can enhance the functionality of your application by creating your own editors and providing a larger window for large text items.Creating an Editor The steps required to create an editor are: • In the Object Navigator select the Editors node. • Click the Create icon from the toolbar. A new editor is created, which you can see in the Object Navigator. • Select the editor in the Object Navigator and invoke the Property Palette. • Set the required properties.Editor Properties The important Editor properties are: • Title: Set this property to display the title at the top or bottom of the editor window. • Wrap Style: Set this property to specify the display of the text when it exceeds the width of the editing area. Select from: • None • Character • Word • Show Vertical Scroll Bar: Set this property to display a scroll bar for the editor.Associating a Editor with a Text ItemConfidential © SQL Star International Ltd. 96
  • 100. Steps to associate an editor with a text item are: • In the Object Navigator select the text item from which the editor should be accessible. • Invoke the Property Palette of the text item and set the Editor property to any of the following: • Null: The text item will use ‘the default editor provided by the Forms Builder. • ‘Editor_Name’: The text item will use the user created editor.Invoking an EditorSteps to use an editor at runtime are: • Place the cursor in the text item that you want to edit. • Press the function key ([Ctrl] + E) to invoke the editor or from the Edit menu select the Edit option, the editor is displayed. • Now make the changes that you require to make. • Click OK to save your changes back to the text item.Confidential © SQL Star International Ltd. 97
  • 101. Summary In this chapter, you have learnt that: • A text item is a user interface object, which enables the user to manipulate data. A text item will allow you to Query, Insert, Update data and Delete data. • You can use Object Navigator, Layout Editor, wizards, etc to create a text item. • You can control the appearance of a text item by changing the general, physical, records, font and color property etc. • You can create a multi-line text item to display large text values like addresses and description. • When you create a text item manually the text item will not have a default prompt. You can specify a prompt for the item by creating a boilerplate text. • You can modify the appearance and behavior of a text item by setting its properties in the Property Palette. • You can control the navigation of a text item by setting its Navigation properties such as Keyboard navigable, previous navigation Item and Next navigation Item. • You can modify and enhance the relationship between a text item and its associated database column by modifying the Database group properties. • List of Values (LOV) is a form module object, which is displayed as a scrollable popup window containing a pick list, when invoked at runtime. • An LOV can be accessed by any text item within the form module, as it is defined at the form level. • LOV displays the values of the columns that are stored by the record group in the popup window. • You can create an LOV using the LOV Wizard by clicking on the create icon in the object navigator and, can also be invoked by selecting the LOV Wizard option from the Tools menu in the main menu. • An Editor is a dialog box associated with a text item. To invoke an editor you can place the cursor in the text item that you want to edit.Confidential © SQL Star International Ltd. 98
  • 102. Lab Exercise-6 1. Create a Text item, Label it as “Member name”; place it on the right top corner in the CV_BRANCH canvas of BRANCHXX form module • set the property to this text item so that the text item will act as a non-navigable item • Synchronize this text item with CFIRSTNAME Save, compile and run the form, see and test the changes. 2. Specify the properties for the nfine column of Transaction table to • Display ‘0’ as the default value before any values are displayed and • The format of the amount should be some thing like this for example:$3.00 Check out the changes in the output. 3. Change the following properties of the following Text items: CBRANCHID: • Set the property so that the text item should be navigable only through mouse. • Next Navigation item: VBRANCHADDRESS CBRANCHNAME: • Previous Navigation Item: CBRANCHADDRESS • Next Navigation item: CBRANCHLOCATION CBRANCHLOCATION: • Next Navigation Item: CBRANCHID Save, compile and run the form and check out the changes. 4. In BRANCHXX form module, create an LOV. Base the record group on Branch table. Include the columns cbranchid and cbranchname in the LOV. • Now attach this LOV to the cbranchid text item of the BRANCH data block. A Record group is created under the section Record Group with a default name. • Change the default record group name to BRANCH_RG. • Change the Default LOV name to BRANCH_LOVConfidential © SQL Star International Ltd. 99
  • 103. • To query the records go to enter query mode, select the existing values of cbranchid from BRANCH_LOV 5. Now Create a Record Group manually and name it as TRANSACTION_RG. • Create an LOV, while creating this LOV, and select the existing Record group as TRANSACTION_RG. • Base the record group on TRANSACTION table, include columns cmemberid in the LOV. Now attach this LOV to cmemberid text item of the TRANSACTION data block. Now change the default LOV name to TRANSACTION_LOV. • To insert a new record into the Transaction table, select the cmemberid from the TRANSACTION_LOV 6. Set the following Properties: BRANCH_LOV: • Record group: BRANCH_RG • Set the Property to display a dialog box the enables the user to enter a search condition before populating the LOV • Set the property such that the LOV should be automatically displayed when the cursor is placed in the text item. Set the below property for MEMBER_LOV: • Record Group: MEMBER_RG Save, compile and run the application 7. Create an Editor named MEMBER_EDITOR and set its color to gray12. Attach this Editor named “MEMBER_EDITOR” to vAddress to edit the address of a member in the MEMBER block.Confidential © SQL Star International Ltd. 100
  • 104. Chapter 7 Creating Input and Non-input Items Creating Input Items Ways to Create a Checkbox Properties to be changed Creating a List Item List Item Properties Creating a Radio Group Radio Group Properties Radio Button Properties Non-input Items Creating a Display Item Calculated Items Image Items Push Buttons Creating a Hierarchical Tree Creating a Bean itemConfidential © SQL Star International Ltd. 101
  • 105. ObjectiveAt the end of this chapter, you will be able to: • Create Input Items • Learn various ways to create a Checkbox and change its properties • Know about List Item, how to create and change its properties • Understand about Radio group • Discuss some Radio button properties • Get the idea about Non-input Items • Learn how to use Display Item • Know what are Calculated Items • Remember Image Items • Play with Push Buttons • Create a Hierarchical Tree • Understand the process to create a Bean itemConfidential © SQL Star International Ltd. 102
  • 106. Creating Input ItemsIn addition to text items there are other items provided by Form Builder, whichallow inputs from users. The following are the three input items: • Check box • List item • Radio groupInput items allow you to: • Insert records • Update records • Delete records • Query recordsCheck BoxA check box is a user interface object that allows user input. A check box isalways in one of the two states, checked or unchecked. It can be used for ‘Yes’ or‘No’ status fields. You can create a check box using one of the following methods: • Converting an existing item into a check box • Using the Check Box tool button in the Layout Editor • Clicking the Create icon in the Object Navigator and setting the Item Type property.Check Box PropertiesJust like text items, check boxes also have properties. The important check boxproperties are:3) Data Type: Set this property to specify the data type of the check box4) Label: Specify the label that appears to the right of the check box5) Initial Value: Set this property to specify the initial value. This property also determines if the check box is initially in checked or unchecked stage6) Value When Checked: Set this property to specify a value for the checkedstate7) Value When Unchecked: Set this property to specify a value for theunchecked state8) Check Box Mapping of Other Values: Set this property to specify how other values are handled.If your database table contains other values, then the check box should becapable of handling those values. By using the Check Box Mapping of OtherValues you can assign the other values to either the checked or uncheckedvalue. You can also force the check box not to handle other values by setting theproperty as ‘Not Allowed’.Confidential © SQL Star International Ltd. 103
  • 107. Ways to Create a CheckboxConverting an Existing Item into a Check BoxTo convert the cMaritalStatus text item to a check box cbMaritalStatus in theMember data block in the frmLib form module, you have to perform thefollowing steps: 17. Invoke the Property Palette of the cMaritalStatus item 18. Change the Item Type property and set it to ‘Check Box’ 19. Type Marital Status as the label for the check box 20. Set the Checked and Unchecked property values as ‘Y’ and ‘N’. 21. Specify the Check Box Mapping of Other Values property if you want to handle values other than the checked and unchecked values 22. Set the Initial Value property to determine if the check box is initially checked or unchecked.Creating a Check Box in the Layout EditorSteps to create a check box in the Layout Editor: 1. Select the canvas on which you want to display the check boxConfidential © SQL Star International Ltd. 104
  • 108. 2. Select the data block in which you want to create the check box 3. Click the Check Box tool button 4. In the canvas click at the place you want the check box to be displayed. A check box appears 5. Invoke the Property Palette for the check box 6. Set the properties specific to the check boxCreating a Check Box using the Object NavigatorSteps required to create a check box item in the Object Navigator are: 1. In the Object Navigator, select the Items node appearing under the block in which you want to create the desired item. 2. Click the Create icon. A new item is displayed. 3. Invoke the Property Palette of the new item 4. Change the Item Type property to ‘Check Box’ and set the check box specific propertiesProperties to be changedHandling Null ValuesYou can handle null values with one of the following methods: • Setting the Check Box Mapping of Other Values property • Setting the Checked or Unchecked state as nullIgnore the check box in the Enter Query mode using [Shift] + [click].Using a Check BoxAt runtime, a user can perform the following actions: • Set the check box value • Query checked/unchecked values • Ignore the check box values in the Enter Query mode.List ItemList Item is a user interface object that displays a list of choices from which theuser has to make a selection. The user can only make a single selection. Itdisplays a predefined set of choices without using a large area of the canvas.There are three types of list items, they are: 14. Poplist: It is a field with a down arrow on the right side. You can display the list by clicking the down arrow. It does not accept input values. 15. Tlist: It is a rectangular box with a scroll bar. You can view the entire list by scrolling up and down. 16. Combo box: Like poplist, combo box too is a field with a down arrow on the right side, which displays the list when clicked. It, however, accepts input value.Confidential © SQL Star International Ltd. 105
  • 109. Creating a List ItemYou can create a list item in one of the following ways: • Convert an existing item • Clicking the List Item tool button In the Layout Editor • Clicking the Create icon in the Object Navigator and setting the Item Type property.Converting an Existing Item into a List ItemThe steps to convert an existing item say cBranchID in the Book data block ofthe frmLibTrans form module into a list item lstBranchID are: 1. Open the frmLibTrans and select the Book data block 2. Display the Property Palette of the cBranchID item 3. Set the Item Type property to ‘List Item’ 4. Invoke the List Item Element window by clicking the More button for Elements in the List property 5. In the List Elements column, specify the element that will be displayed in your list item 6. In the List Item Value field, specify the value for the currently selected list element. 7. Click OK 8. Set the Other Values property to: • Accept all other values to one of the predefined list element values • Reject values which are not predefined as list values 9. Specify an initial value for the list itemConfidential © SQL Star International Ltd. 106
  • 110. Creating a List Item in the Layout EditorCreate a list item in the Layout Editor by: • Selecting the canvas on which you want to display the list item • Selecting the data block in which you want to create the list item • Clicking the List Item tool button • Clicking on the canvas at a place you want to display the list item • Invoking the list item Property Palette by double-clicking the list item • Setting the required propertiesCreating a List Item using the Object NavigatorSteps required to create a list item in the Object Navigator are: 1. In the Object Navigator, select the Items node appearing under the block in which you want to create the desired item. 2. Click the Create icon. A new item is displayed. 3. Invoke the Property Palette of the new item. 4. Change the Item Type property to ‘List Item’ and set the list item specific properties.Confidential © SQL Star International Ltd. 107
  • 111. List Item PropertiesThe item properties that are specific to a list item are: • List Style: Specify the list item style, select from: Poplist Tlist Combo Box • Mapping of Other Values: Specify how the other values are to be handled • Mouse Navigate: Set this property to specify whether Form Builder navigates and moves the input focus to the next navigable item when the user activates the item with a mouse. • Elements in List: Click the More button to open the List Item Elements window and specify: List Elements: As you want them to appear at runtime. List Item Value: With the value associated with each of the list elements.Confidential © SQL Star International Ltd. 108
  • 112. POP LISTT-ListCombo ListHandling Null ValuesForm Builder creates a pseudo choice to represent a null if your base tableaccepts a null value for the column. A list item will return a blank element if aquery returns a null valueOther Values in a List ItemSpecify how you want to handle other values if your base table accepts valuesother than those associated with the list elements by doing one of the following: • In the Mapping of Other Values property, associate the other values to one of the list elements. • Make the Mapping of Other Values property as a blank, to ignore other valuesRadio GroupA radio group consists of a group of radio buttons. Each of these radio buttonshas a definite value associated with it. No two radio-buttons in a group will havesame values associated with them. Use a radio group when an item has two ormore possible values but only one of these values can be true at a given time. Itis advisable to use a radio group when the choice is less.Confidential © SQL Star International Ltd. 109
  • 113. Creating a Radio GroupYou can create a radio group in one of the following ways: 1. Converting an existing item 2. Using the Layout Editor 3. Clicking the Create icon in the Object Navigator and setting the Item Type property.Converting an existing Item into a Radio GroupThe steps to convert an existing item say cGrade into a radio group rgGrade inthe Member data block in the frmLib form module are: 1. Open the form module frmLib and select the Member data block. 2. Select cGrade text item. 3. Double-click the item to invoke the Property Palette. 4. Set the Item Type property to ‘Radio Group’. 5. Set the Initial Value property and specify the name of the radio button. 6. Specify how the radio group should handle other values by setting the Mapping of Other Values property. 7. In the Object Navigator expand the node of rgGrade radio group created. 8. Select the Radio Button node under it. 9. Click the Create icon. 10. Invoke the Property Palette of the newly created radio button. 11. Specify the name, value and label for the radio button. 12. Set the required radio button properties.You can create additional radio buttons by repeating step 7 onwards. Create fourradio buttons for the radio group rgGrade and in their Property Palette set thefollowing properties: 1. Set the Name property as ‘rbGradeA’, ‘rbGradeB’, ‘rbGradeC’ and ‘rbGradeD’ 2. Set the Value property as ‘A’, ‘B’, ‘C’, and ‘D’ 3. Set the Label property as ‘5 – 13’, ‘14 – 20’, ‘21 – 50’, and ‘50 - >’ 4. Set the Prompt property as ‘Grade A’, ‘Grade B’, ‘Grade C’ and ‘Grade D’Creating a Radio Group using the Layout EditorThe steps to create a radio group in the Layout Editor are: 1. Select the canvas in which you want to display the radio group. 2. Select the data block in which you want to create the radio group. 3. Click the Radio Button tool button. 4. Click on the canvas at the position you want the radio button to be displayed. If your canvas already has a radio group then a Radio GroupConfidential © SQL Star International Ltd. 110
  • 114. dialog box is displayed asking you if the new radio button should appear in the same group or a new one. 5. Invoke the Property Palette of the new radio button. 6. Set the radio button with specific properties.Creating a Radio Group using the Object NavigatorSteps required to create a radio group in the Object Navigator are: 1. In the Object Navigator, select the Items node appearing under the block in which you want to create the desired item. 2. Click the Create icon. A new item is displayed. 3. Invoke the Property Palette of the new item. 4. Change the Item Type property to ‘Radio Group’ and set the radio group specific properties. 5. Select the Radio Button node under the radio group created. 6. Click the Create icon. 7. Invoke the Property Palette of the newly created radio button. 8. Specify the name, value and label for the radio button. 9. Set the required radio button properties.Radio Group PropertiesThe important radio group properties are: • Data Type: Set this property to specify the data type. • Mapping of Other Values: Set this property to specify how other values should be handled.Handling Null ValuesTo handle a null value: • Force a null value to a radio button implicitly by setting Mapping of Other Values property. • Assign a null value to a radio button by leaving the Radio Button Value property blank.Other Values in a Radio GroupSpecify how the radio group should handle other values by using one of thefollowing methods: • Associate other values to one of the radio buttons using the Mapping of Other Values property. • Ignore other values by leaving the Mapping of Other Values property blank.Confidential © SQL Star International Ltd. 111
  • 115. Radio Group Mapping of Other ValuesUsing a Radio GroupAt runtime, a user can perform the following actions: • Set the radio group values • Query radio button values • Ignore the radio button valueRadio Button PropertiesThe important radio button properties are: • Label: Set this property to specify a text that describes the radio button. • Radio Button Value: Set the value of the radio button, which will be used to insert or query the block.Non-input ItemsNon-input items as the name suggests, do not allow user input. However non-input items add functionality to your application by displaying data or by initiatingactions. There are two types of non-input items: • Non-input items that display data: Display items Image items Calculated items Hierarchical Tree • Non-input items that do not display data, but initiate actions: Push ButtonsDisplay ItemDisplay item as the name suggests is an item that displays data. It is similar to atext item except that it cannot be navigated or manipulated at runtime. The datain a display item can be derived either through calculation or from a databasetable.Here is the toolbox display item:Confidential © SQL Star International Ltd. 112
  • 116. Creating a Display ItemA display item is created in one of the three following ways: Converting an existing item Using the Layout Editor Clicking the Create icon in the Object Navigator and setting the Item Type property.Converting an Existing Item into a Display ItemTo convert an existing item to a display item, you have to perform the followingsteps: • Invoke the Property Palette of the existing item • Change the Item Type property and set it to ‘Display Item’Creating a Display Item using the Layout EditorThe steps to create a display item diTotalFine in the Transaction data block inthe frmLibTrans form module are: • In the Object Navigator, open the frmLibTrans form module and select the Transaction data block. • Invoke the Layout Editor. • Select the canvas on which you want the display item to be displayed. • Select the data block in which you want to create the display item. • Click the Display Item tool button. • Click the canvas at the position where you want the display item. A new display item is displayed. • Double-click the display item to invoke its Property Palette. • Specify the name as diTotalFine for the display item and set the display item specific properties.We will use the display item created later in the session and see how it displaysdata.Creating a Display Item using the Object NavigatorSteps required to create a display item in the Object Navigator are: • In the Object Navigator, select the Items node. • Click the Create icon. A new item is displayed. • Invoke the Property Palette of the new item by double-clicking. • Change the Item Type property to ‘Display Item’ and set the display item specific properties.Confidential © SQL Star International Ltd. 113
  • 117. Calculated ItemsA calculated item is a display item. It is a very useful way to keep users updatedabout important information. Calculations can be based on a formula or on asummary. Use a display item to create a calculated item. The following are thetwo types of calculation modes: • Formula: The calculated value is a horizontal calculation based on form items, variables and parameters. • Summary: It is a vertical calculation based on the values of a column throughout a data block.A calculated item can be created in one of the following ways: • Converting an existing item • Using the Layout Editor • Clicking the Create icon in the Object Navigator and setting the Item Type property.Calculated Item PropertiesThe important calculated item properties are: • Calculation Mode: To determine the method of calculation. Select from: 5. None 6. Formula 7. Summary • Formula: To specify a PL/SQL expression to calculate the item value 8. Summarized Block: To specify the block in which all the rows will be summarized to calculate a value for the calculated item. This property is specific to the summary function. 9. Summarized Item: To specify the item which will be summarized to calculate a value. This property is specific to the summary function. 10. Summary Function: To determine the type of summary function to be performed. The following functions are supported by the Form Builder: 17. AVG 18. COUNT 19. MAX 20. IN 21. STDDEV 22. SUM 23. VARIANCE NOTE Restricted Built-in subprograms are dealt in a later session.Confidential © SQL Star International Ltd. 114
  • 118. Creating a Calculated Item Based on a FormulaThe steps to create a calculated item are: 1. In the Object Navigator, create an item 2. Double-click the item to invoke the Property Palette 3. Set the Calculation Mode property to ‘Formula’ 4. Define the PL/SQL expression after clicking the More icon in the Formula propertyRemember the following when creating a calculated item. 1. The user-defined formula should not invoke restricted built-ins. That is, built-ins that affect navigation. 2. The formula should not execute DML statements. 3. Do not terminate the PL/SQL statement with a semicolon.Creating a Calculated Item based on a SummaryThe steps to create a calculated item in the Transaction data block offrmLibTrans form module based on a summary are: 1. In the Object Navigator, open the form module frmLibTrans and select the Transaction data block. 2. Invoke the Property Palette of diTotalFine display item created. 3. Specify the canvas name as canLibTrans. 4. Set the Calculation Mode property to ‘Summary’. 5. Specify a function to perform calculations from the Function poplist. 6. Select a block on which the calculations should be performed from the Summarized Block poplist. 7. Select the item on which calculations should be performed from the Summarized Item poplist.Remember the following while creating a calculated item based on a summary: • The summary block must reside in: The same block as the summarized item, or in a control block with Single Record property set to ‘Yes’ A control block or a data block whose Query All Records or Precompute Summaries properties are set to ‘Yes’ • Set Data Type property to ‘Number’ unless the summary function is MAX or MIN.Image ItemsImage items are items that can be used to store and display images. An imageitem displays automatically and it cannot be manipulated at run time. Images canConfidential © SQL Star International Ltd. 115
  • 119. be imported from the database or the file system. You can populate an imageitem by one of the following methods: • Importing the image from the database columns (LONG RAW or BLOB). • Populating an image item programmatically using triggers and built-in subprograms. • Cutting and pasting an image to the clipboard and selecting the image item at runtime, invoke the Edit menu and select the Paste option. • This is the image of a tool in the toolbox for an image item:Image File FormatsYou can store images in either the database or the file system. Form Buildersupports the following image formats: File Description BMP Microsoft Windows and OS/2 Bitmap Picture CALS CALS Type Raster GIF Compuserve JPEG Joint Photographic Experts Group JPEG JPEG File Interchange Format PICT Macintosh Quickdraw Picture RAS Sun Raster TPIC True vision Raster Graphics Array Picture TIFF Tag Image File FormatImage Item PropertiesThe image item specific properties are: • Image Format: Set this property to specify the storage format of the image items. • Image Depth: Set this property to specify the image depth setting for the image items. • Compression Quality: Set this property to specify the degree of compression to be used on the image item. • Display Quality: Set this property to specify the resolution that is used to display the image item. • Sizing Style: Set this property to specify how much of the image should be displayed if the image size and the item size do not match.Confidential © SQL Star International Ltd. 116
  • 120. • Show Palette: Set this property to display the image manipulation tools. The tools are: Select: To select an area in the image Zoom: To zoom in or out the image Pan: To pan unseen portions of the image Rotate: To rotate the image in a clockwise directionCreating an Image ItemYou can create an image item in one of the following ways: • Converting an existing item • Clicking the Create icon in the Object Navigator and setting the Item Type property. • Using the Image Item tool button in the Layout EditorCreating an Image Item from the Layout EditorThe steps to create an image item say imgBooks in the Book data block offrmLibTrans form module are: • In the Object Navigator, open the frmLibTrans and select the Book data block • Invoke the Layout Editor • Select the canvas on which you want to display the image item • Select the data block in which you want to create an image item • Click the Image Item tool button • Click on the canvas at the position, you want to display the image item. A new image item is displayed. • Double-click the image item to display the Property Palette • Set the name as imgBooks and other image item specific propertiesWe will populate this image item in the later session using triggers.Push ButtonsA push button is an object that initiates an action when a user clicks it. Pushbuttons cannot store or display values. There are two types of push buttons. Theyare: 1. Text button: It is a rectangular button with a descriptive text label.Confidential © SQL Star International Ltd. 117
  • 121. 2. Iconic button: It is displayed with a bitmapped graphic and is used in toolbars.Some of the actions that can be performed using a push button are: • Display a LOV (List of Values) • Invoke an editor • Commit data • Perform a query • Perform calculations • Move the input focus • Invoke a different windowPush Button PropertiesThe important push button properties are: • Label: To specify the label that you want on the push button at the runtime • Default Button: To make a button the default button for your block • Iconic: To display the push button as an icon • Icon Filename: To identify the file that contains the icon • Tooltip: To specify a help text at runtime • Tooltip Visual Attribute Group: To associate a visual attribute to the TooltipIconic Push ButtonThis is an iconic push button for Exit:Creating a Push ButtonA push button can be created by: • Using the Layout Editor. • Clicking the Create icon in the Object Navigator and setting the Item Type property.Creating a Push Button using the Layout EditorTo create a push button say pbOut in frmLib module, create a control blockControlBlk and: • Invoke the Layout EditorConfidential © SQL Star International Ltd. 118
  • 122. • Select the canvas on which you want to display the push button. • Select the control block Controlblk, in which you want to create the push button. • Click the Push Button tool. • Click the canvas at the position where you want the push button to be displayed. A new push button is displayed. • Invoke the Property Palette of the push button by double-clicking it • Specify the name as pbout and label as Out, set the other push button specific properties.We will add functionality to this push button in a later session using triggers.Creating a Hierarchical TreeThe steps to create a hierarchical tree item are: 1. In the Object Navigator, click the icon beside the desired block node 2. Click the Items node 3. Click the Create button in the Toolbar 4. A new item with a default name is inserted 5. Double-click the object icon beside the new item to display the Property Palette 6. Set the Item Type property to ‘Hierarchical Tree’ under the General node 7. Set the Canvas property to the name of the desired canvas under the Physical nodeConfidential © SQL Star International Ltd. 119
  • 123. NOTE To display an item at runtime, you must assign it to a canvas.Populating Hierarchical TreeThe data in the Hierarchical Tree is displayed in the form of a standard navigator,similar to that used in Forms Developer.A Hierarchical Tree can be populated with the values in a record group or querytext. Programmatically elements can be added, removed, modified in aHierarchical Tree. The amount of data that can be displayed at any one timedepends upon the expansion of individual data nodes, whether through built-insor a user clicking on a node.Creating a Bean itemThe Bean Area item enables you to: • Add a JavaBean to a form • Extend Forms functionality • Interact with client machine • Reduce network traffic This is the image of a tool in the toolbox for a bean item:Confidential © SQL Star International Ltd. 120
  • 124. A JavaBean is a component written in Java that can plug in to any applet or Javaapplication. The bean area item enables you to extend Forms functionality byadding a JavaBean to your form.With JavaBeans, you can interact with the client machine, performing suchfunctions as: • Uploading client files to the server machine • Obtaining information about the client machine • Modifying the user interface on the client • Checking the spelling of a text item • Displaying a progress bar, clock, calendar, or color picker with which the operator may be able to interact and select valuesSome of this functionality, such as the calendar, is possible using Forms nativefunctionality. However, using a JavaBean enables to interact with client withoutgenerating network traffic.Although JavaBeans can be used to input data, as in the case of the CalendarJavaBean, the bean area item itself does not accept user input.Confidential © SQL Star International Ltd. 121
  • 125. Confidential © SQL Star International Ltd. 122
  • 126. SummaryIn this chapter, you have learnt that: • You can create Input Items such as Check box, list item, radio group and input items that allow you to insert records, update records and Query records. • A check box is a user interface object that allows user input which is always in one of the two states, checked or unchecked. • To specify the list item style, you can select from Poplist, Tlist and Combo Box. • A radio group consists of a group of radio buttons. No two radio-buttons in a group will have same values associated with them. • You can create a radio group by converting an existing item or by using Layout editor. The important radio group properties are data type and mapping of other values. • Non-input items add functionality to your application by displaying data or by initiating actions. • The data in a display item can be derived either through calculation or from a database table. • You can create a display item by converting an existing item, using the Layout Editor and by using the Object Navigator. • A calculated item is a display item having two calculation modes, namely, formula and summary. • Image items are items that can be used to store and display images. You can populate an image item by importing the image from the database columns. • Push buttons like text button and iconic button cannot store or display values. • A Hierarchical Tree can be populated with the values in a record group or query text. • A Java Bean is a component written in Java that can plug in to any applet or Java application.Confidential © SQL Star International Ltd. 123
  • 127. Lab Exercise 1. In the BRANCHXX form module, Create an image item called CIMAGE in the CONTROL block and place it below the “member name” label. Note: For all the questions see the screenshot given below in the next page and do it accordingly. 2. Convert the existing CBranchLocation text item to a pop-list. 3. Change the existing cmaritalstatus column in the MEMBERS block to a checkbox such that • If the person is married the checkbox should be checked and if unmarried the check box should be displayed unchecked. • Display values other than married or unmarried as Checked. 4. Convert the existing CGRADE column of Member table into a Radio group with four radio Buttons namely A, B, C and D. o Set the appropriate corresponding values to the radio buttons. o Set the default value ‘A’. 5. Create one Iconic push button, name it as PB_LOV and place it beside the CbranchId text item of the CV_BRANCH canvas. (Functionality will be added to this button in the subsequent chapters) 6. Create a push button above the IMAGE_DESCRIPTION. o Name it as SHOW_HELP and label as “Show Help”. Save, compile and run the form. 7. Open BRANCHXX form module and create a new canvas namely CV_TREE. Place it in a new window namely WIN_TREE. Change the title of the window to “LIBRARYSTAFF” o Now create a hierarchical item on the canvas by selecting the hierarchical tree item from the tool box. o Name this tree as LIBSTAFF_TREE. (To populate the details of library staff based on LIBSTAFF table into the hierarchical tree item, the necessary trigger code is covered in later chapters.)Confidential © SQL Star International Ltd. 124
  • 128. 8. Convert the existing text item which was placed beside the label “member name” to display item and name it as IMAGE_DESCRIPTION and synchronize the current record’s CFIRSTNAME value with the display item. This should appear as in the screen shot given in the following figure: 9. Create display item for calculating the total fine of all the members who are payable in the library (Display should be included in Transaction block).Confidential © SQL Star International Ltd. 125
  • 129. 10. Now create a java bean and name it as color picker in the CONTROL block that will enable a user to choose a color from a color picker. ( this bean area is invisible to the users) • The path to the bean is oracle.forms.demos.beans.ColorPicker (this is case sensitive). • Create a button on the CV_BRANCH canvas to enable the user to change the canvas color using the ColorPicker bean. Label this button as “Canvas color” • Set the following properties on the button: Label: Canvas Color Background color: white The bean item should be completely non-navigable. • The implementation class for the bean item is set in the later chapter. Save, compile and run the formConfidential © SQL Star International Ltd. 126
  • 130. Chapter 8 Windows and Canvases Window Relationship between Windows and Canvases Creating a Window Creating Canvases Creating a Content Canvas Stacked Canvases Toolbar Canvases Tab CanvasConfidential © SQL Star International Ltd. 127
  • 131. ObjectiveAt the end of this chapter, you will be able to: • Learn about Window • Study the relationship between Windows and Canvases • Create a Window • Create Canvases • Know how to create a Content Canvas • Understand Stacked Canvases • Work with Toolbar Canvases • Work with Tab CanvasConfidential © SQL Star International Ltd. 128
  • 132. WindowA window is the outermost boundary of a form. It is like an empty picture frame.Form Builder automatically generates a Multiple Document Interface (MDI)window for your Forms applications. All the other windows that you create shouldbe within the MDI window. There are two types of windows:Document or Modeless window: Is not necessarily active when it is displayed.This is the default window type, which allows: The user to query and enter data Movement to other windows Interaction with the application menu and toolbarDialog or Modal window: Dialog windows are used to display messages to theuser. A dialog window: • Is a restricted window that forces the user to respond before moving to other windows. • Requires user input to exit or dismiss the window. For example, File dialog window is displayed in most of the GUI platforms, where as an LOV is a native Form Builder object, which requires user input to either exit or dismiss the LOV window. Modeless ModalConfidential © SQL Star International Ltd. 129
  • 133. Relationship between Windows and CanvasesA canvas is a surface on which items of the block are placed, to be visible at theruntime. Every canvas must be attached to a window. There are few points to bekept in mind while creating a canvas: The default canvas is the content canvas. A user must create at least one content canvas for each window. You can associate more than one canvas with a single window. At runtime only one content canvas will be displayed even though you have assigned multiple canvases at design time. At runtime the content canvas will fill the window completely.New WindowA window is automatically created when you create a form module. The user canchange the default name of the window (WINDOW1) or can delete the defaultwindow and create a new one. You can create additional windows to: Display multiple canvases simultaneously. Navigate different canvases without replacing the original one. Customize your form contents.Creating a WindowThe steps to create a window say winBookTrans in frmLibTrans form module,in the Object Navigator are: 1. Select the Windows node 2. Click the Create icon from the toolbar 3. A new window is displayed, double-click it and invoke the Property Palette 4. Change the default name to winBookTrans and set the other window specific propertiesWindow PropertiesThe important window properties are: General Properties • Name: Specify the name of the window, as you want it to appear in the Object Navigator. • Subclass Information: Set this property to allow you to subclass this window’s property to other window properties. Functional Properties Title: Specify the title that should appear in the title bar at runtime. If you do not specify a title then the window name will appear by default. Primary Canvas: Specify the name of the canvas that will be displayed in this window.Confidential © SQL Star International Ltd. 130
  • 134. • Window Style: Specify the window style to be either ‘Document’ or ‘Dialog’. • Modal: To determine if the window requires a user response or not. Default value is ‘No’. • Hide on Exit: To specify whether a document window is hidden when a user navigates to another window. • Close Allowed: To specify if a user can close the window. • Move Allowed: To allow the user to move a window. • Resize Allowed: To specify if a user can resize the window. Maximize Allowed: To allow a user to maximize a window. Minimize Allowed: To allow a user to minimize a window. That is, minimize a window so that it appears as an icon on window managers supporting this feature. Minimized Title: Specify the title that should appear below the iconified window when it is minimized. Inherit Menu: To display the current form menu.Creating CanvasesAs you already know a canvas is a Form Builder object that displays the usercreated objects at runtime. The visible portion of a canvas is known as theviewport. There are four types of canvases. They are: Content canvas Stacked canvas Toolbar canvas Tab canvasCreating a Content CanvasContent canvas is the default canvas type created for each window in anapplication. At design time more then one content canvas can be assigned to thesame window, however at runtime only one content canvas is displayed. This isbecause, a content canvas fills the entire content pane of the window in which itis displayed. When you resize the window, Form Builder automatically resizes thecontent canvas. To create a content canvas, say canBookTrans in frmLibTransform module: Implicitly: • Use the Layout Wizard: It enables you to select a new canvas in the Canvas screen. A canvas is created with a default name (CANVAS1). • Use the Layout Editor: If a form module does not contain a canvas, Form Builder will automatically create a canvas when the user invokes the Layout Editor. Explicitly: Steps to create a canvas explicitly in the Object Navigator are:Confidential © SQL Star International Ltd. 131
  • 135. • Select the Canvas node • Click the Create icon in the toolbar. A new canvas is displayed • Select the new canvas and invoke its Property Palette • Specify a new name as canBookTrans and set the properties specific to canvas • In the Object Navigator, select all the items in the Branch data block and invoke the Property Palette • Set their Canvas property to ‘canBookTrans’, to display the Branch data block in the new canvasContent Canvas PropertiesThe important content canvas properties are: Canvas Type: Specifies the type of canvas to be set by choosing from ‘Content’, ‘Stacked’, ‘Vertical Toolbar’, ‘Horizontal Toolbar’, or ‘Tab’. The default setting is ‘Content’. Window: Specifies the window in which you want the canvas to display. For example, to display canBookTrans, set its Window property to ‘winBookTrans’. Viewport X Position: Sets the X coordinate of the upper left corner of the view in relation to the upper left corner of the canvas. Viewport Y Position: Sets the Y coordinate of the upper left coordinate of the view in relation to the upper left corner of the canvas. Width: Sets the width of the canvas. Height: Sets the height of the canvas.Confidential © SQL Star International Ltd. 132
  • 136. Raise on Entry: Specifies whether navigation to an item on the canvas should affect the order in which canvases are stacked on a window. Setting this property to: • ‘No’ causes the Form Builder to raise the canvas to the front of the window only when the item to be navigated, is hidden behind another canvas in the same window. • ‘Yes’ causes the Form Builder to raise the canvas to the front of the window, only when the user navigates to an item on that canvas.Stacked CanvasesA stacked canvas is always displayed or stacked on top of a content canvas. Ithides whatever is beneath it. It can share a window with a content canvas andmultiple numbers of stacked canvases. Stacked canvases are smaller than thewindow in which they are displayed and are determined by viewport size. Stackedcanvases are useful to: Display static information such as, the name of the company, its logo, etc., by creating a stacked canvas that would always appear in front of the current content canvas. Even when the current content canvas is replaced, the stacked canvas would remain visible in the window. Display items or graphic images that users need to see only in certain conditions, such as the help text. Create a scrolling region, if the block created contains more items than that can fit in a window.When users tab to items that are outside the window’s frame, Form Builderautomatically scrolls the window. This however causes important field values tobe scrolled out of the user’s view. For instance, in the block based on theTransaction table, the transaction ID, Book ID, and Member ID should be visiblefor all transactions. Therefore, these fields could be placed on the content canvasand other fields can be scrolled out of sight on a stacked canvas. By doing so, thestacked canvas becomes the scrolling region and not the window.Stacked Canvas PropertiesThe important stacked canvas properties are: Viewport X Position: To set the X-coordinate of the viewport. Viewport Y Position: To set the Y-coordinate of the viewport. Viewport Width: To set the width of the viewport. Viewport Height: To set the height of the viewport. Show Horizontal Scroll Bar: To display the canvas with a horizontal scrollbar. Show Vertical Scroll Bar: To display the canvas with a vertical scrollbar.Creating a Stacked Canvas Using the Object NavigatorThe steps to create a stacked canvas using the Object Navigator are: • Select the Canvas node. • Click the Create icon. A new canvas is displayed.Confidential © SQL Star International Ltd. 133
  • 137. • Select the new canvas and invoke its Property Palette. • Specify the name of the canvas. • Set the Canvas Type property to ‘Stacked’ and set the other stacked canvas specific properties as required.23. Content canvas Stacked CanvasCreating a Stacked Canvas Using the Layout EditorThe steps to create a stacked canvas, say stcanPBDetails in frmLibTrans formmodule, by using the Layout Editor are: • Click the stacked canvas tool button in the toolbar and drag and place on the canvas. • Invoke the stacked canvas Property Palette and set the Name property as ‘cv_help’. • Set the Window property to ‘win_Books’. • Set the other properties as required. Go to the Object Navigator • Write text into the canvas and place a button on the stacked canvas to hide the stacked canvas.In the later session, we will deal with how to view stacked canvas only when it isrequired. So for this, you have to create a button whose functionality will bedefined to invoke the stacked canvas, as and when clicked by the user.Displaying a Stacked CanvasA stacked canvas can be displayed in response to navigation or programmatically,covered in later sessions.Here are the steps to display a stacked canvas that is stacked on a contentcanvas: o In the Layout Editor, select Stacked Views option from the View menu. A Canvases dialog box opens.Confidential © SQL Star International Ltd. 134
  • 138. o Select the stacked canvas that is to be displayed on the Layout Editor.Toolbar CanvasesA toolbar canvas unlike other canvases is not designed to display data. But itenhances the functionality of your application by allowing you to create your owntoolbars to hold buttons. There are three types of toolbars, they are: Vertical toolbar: You can create a vertical toolbar, which contains all your buttons and is displayed on the left or right of the window. Horizontal toolbar: You can create a horizontal toolbar that is displayed either on the top or bottom of your window. MDI toolbar: Use an MDI toolbar to use only one toolbar for multiple windows in your application.Use a toolbar canvas to: Provide a uniform look to all the canvases displayed in the same window. Provide alternative to the default menu. Enhance the functionality of your applications.Toolbar PropertiesThe important toolbar properties are: Canvas Type: Specify as ‘Horizontal’ or ‘Vertical’ toolbar. Window: Specify the window in which the toolbar is to be displayed. Width: Specify the width of the toolbar canvas. Height: Specify the height of the toolbar canvas.Creating a Toolbar CanvasThe steps to create a toolbar canvas are: o In the Object Navigator, select the Canvas node. o Click the Create icon. A new canvas is displayed. o Select the new canvas and invoke its Property Palette. o Set the Canvas Type property to either ‘Horizontal Toolbar’ or ‘Vertical Toolbar’. o Set the toolbar specific properties as required. o Select the window from the Object Navigator in which you want to display the canvas and invoke its Property Palette. o Set the window’s Horizontal/Vertical Toolbar property with the toolbar canvas created. o Select the form module from the Object Navigator that you will associate the canvas with and invoke its Property Palette. o Set the form modules Horizontal/Vertical Toolbar property with the toolbar canvas created.24.Confidential © SQL Star International Ltd. 135
  • 139. Horizontal ToolbarTab CanvasA tab canvas is a special type of canvas, which can be used to display a largeamount of data by breaking them into smaller logical groups. Tab canvases aredisplayed on top of a content canvas. Information is displayed on tabs. The tabson a tab canvas are like a group of stacked canvases.A tab canvas consists of one or more tab pages. Each tab page occupies equalspace and has a labeled tab by which the user can access information.Enhance the functionality of your application by using a tab canvas to: Create multiple canvases on a single canvas Display large amount of information by breaking them into smaller logical groups Hide dataCreating a tab canvas involves: Creating an empty tab canvas Creating one or more tab pages for your canvas Placing the items that you want to display on the tab pages.Tab Canvas Properties:The important tab canvas properties are: Name: Specifies a name for the canvas. Canvas Type: Specifies the canvas type. Viewport X Position: Sets the X coordinate of the upper left corner of the tab canvas in relation to the upper left corner of the window. Viewport Y Position: Sets the Y coordinate of the upper left corner of the tab canvas in relation to the upper left corner of the window. Viewport Width: Sets the width of the tab canvas. Viewport Height: Sets the height of the tab canvas. Corner Style: Sets the shape of the labeled tabs. Choose from • ChamferedConfidential © SQL Star International Ltd. 136
  • 140. • Square • Rounded Width Style: Set the property to vary the width of the tab Active Style: Set the property to determine if the tab page label is displayed as bold or normal. Tab Attachment Edge: Set the property to specify the location of tabs.After setting the tab canvas properties, invoke the tab page Property Paletteand set its Label property to specify the text that should be displayed on the tabpage’s tab at runtime.Creating a Tab Canvas in the Object NavigatorThe steps to create a tab canvas in the Object Navigator are: 1. Select the Canvas node in the Object Navigator. 2. Click the Create icon. A new canvas is displayed. 3. Invoke the Property Palette of the new canvas. 4. Set the Canvas Type property to ‘Tab’ and set the other tab page specific properties as required. 5. Expand the canvas node in the Object Navigator. Select the Tab Page node. Two tab pages are created by default namely PAGE1 and PAGE2. 6. Click the Create icon from the toolbar. A new tab page is displayed with a default name. 7. Invoke the Property Palette of the tab page and set the Label property.You can create additional tab pages by repeating steps 5 to 7.Confidential © SQL Star International Ltd. 137
  • 141. Creating a Tab Canvas in the Layout EditorThe steps to create a tab canvas say tbcanBook in the frmLibtrans in theLayout Editor are: 1. Click the Tab Canvas tool button in the toolbar. 2. Click and drag the mouse on the content canvas to display the tab canvas. 3. Invoke the Property Palette of the tab canvas. Set the Name property as ‘tbcanBook’. 4. Set the Window property to ‘winBookTrans’, and set the other properties as required. 5. Create two tab pages and set their names as tbPgBkDetails and tbPgBkCatgPublisher. 6. Set their labels as Book Details and Category and Publisher.Displaying Items on a Tab PageAfter you have created a tab canvas and its tab pages, place items on the tabpages for the items to be displayed at runtime. The steps required to display theitems in the Book data block in the tbcanBook canvas are: 1. Invoke the Property Palette of cBookID, cBookName, cAuthorName, and cBookID. 2. Set the Canvas property to ‘tbcanBook’. 3. Set the Tab Page property to ‘tbPgBkDetails’.Confidential © SQL Star International Ltd. 138
  • 142. 4. Invoke the Property Palette of cCategoryID, cPublisherName, dPublishedYear, and nNoOfCopies. 5. Set the Canvas property to ‘tbcanBook’. 6. Set the Tab Page property to ‘tbPgBkCatgPublisher’.Confidential © SQL Star International Ltd. 139
  • 143. SummaryIn this chapter, you have learnt that: • Form Builder automatically generates a Multiple Document Interface (MDI) window for your Forms applications. • Dialog windows are used to display messages to the user. • Every canvas must be attached to a window so that it should be visible at runtime. You can associate more than one canvas with a single window. • The user can change the default name of the window (WINDOW1) or can delete the default window and create a new one. • The visible portion of a canvas is known as the viewport. The four types of canvases are Content canvas, Stacked canvas, Toolbar canvas and Tab canvas. • A stacked canvas is always displayed or stacked on top of a content canvas, which hides whatever is beneath it. • The toolbar enhances the functionality of your application by allowing you to create your own toolbars to hold buttons. There are three types of toolbars like vertical, horizontal and the MDI toolbar. • A tab canvas is a special type of canvas, which can be used to display a large amount of data by breaking them into smaller logical groups.Confidential © SQL Star International Ltd. 140
  • 144. Lab Exercise 1. In BRANCHXX form module, create a new modeless Window and name it as WIN_TRANSACTION. Give a title to the window as TRANSACTION. Assign CV_TRANSACTION canvas to this WINDOW. 2. Create one stacked canvas in the BRANCHXX form module, name it as STACKED and place all the items of the Member block except cmemberid onto the stacked canvas. Include both horizontal and vertical scrollbars to the stack canvas as shown below: o Place this STACKED canvas on CV_BRANCH at the following positions: Viewport X position: 80 and Viewport Y position: 212. 3. Create one more stacked canvas in the BRANCHXX form module, Include horizontal and vertical scrollbars to the canvas. o Change the name to CV_HELP; design the stacked canvas as shown below. Name the button as HIDE_HELP and label it as “Hide”.Confidential © SQL Star International Ltd. 141
  • 145. (Purpose of this stacked canvas is, when the “show help” push button is clicked, this help should be displayed. We will add the functionality in the next chapter.) 4. Create Tab canvas in the BOOKXX form module and include 3 tabs namely o Tab1: Name it as BOOKS and base it on Books table. o Tab2: Name it as CATEGORY and base it on Category table. o Tab3: Name it as PUBLISHER and base it on Publisherdetails table. 5. Create two horizontal toolbar canvases in the BRANCHXX form module. Name them as TOOLBAR_BRANCH and TOOLBAR_TRANS respectively. o Assign TOOLBAR_BRANCH to WIN_BRANCH window and assign TOOLBAR_TRANS to WIN_TRANSACTION window. o Create a push button, label it as “Image” and create an iconic button for EXIT. Use Exit.gif to display iconic image. o Place these buttons on the TOOLBAR_BRANCH canvas attached to branch window. We will add functionality to these buttons in the next chapter. o Create two push buttons and place on TOOLBAR_TRANS canvas. Label them as “Member Fee” and “Staff” respectively. o Attach TOOLBAR_BRANCH canvas with the MDI at form level that is; make this toolbar as the standard toolbar. 6. Create a canvas CV_MEMBERFEE. Create a window WIN_MEMBERFEE, give the title as MEMBERFEE. Now, o Create a datablock based on MEMBERFEE table and place it on the CV_MEMBERFEE as shown below. Attach CV_MEMBERFEE to WIN_MEMBERFEE window. Save, compile, and run the form module.Confidential © SQL Star International Ltd. 142
  • 146. Chapter 9 Triggers Introduction to Triggers Trigger Characteristics Trigger Components Create Triggers Trigger properties Trigger Editors Writing the Trigger Code Built-in Subprograms in Triggers Built-in Definitions in the Form Builder Debugging TriggersConfidential © SQL Star International Ltd. 143
  • 147. ObjectiveAt the end of this chapter, you will be able to: Describe triggers Know about the characteristics of Trigger Learn different Trigger components Create Triggers Understand Trigger properties Describe Trigger editors Write the Trigger code Know built-in subprograms in Triggers Learn about built-in definitions in the Form Builder Debug TriggersConfidential © SQL Star International Ltd. 144
  • 148. Introduction to Triggers Triggers are one of the most important features of forms. They are used to add functionality to forms. A trigger is a PL/SQL code that is executed when an event occurs. This PL/SQL code adds functionality to your application. Trigger Characteristics The trigger name defines what event will invoke it. For example, a WHEN- BUTTON-PRESSED trigger executes its code each time the user clicks the button to which the trigger is attached. The Form Builder defines a wide range of events with which you can associate a trigger. These events can be classified as: Query related events Validation events Navigation events Mouse related events Key related events Error and message events The Triggers you write in the Form Builder are different from those that you write in the database. The trigger attached to a particular form module belongs only to the same form module (any event in other forms will not invoke that trigger).Trigger Components Trigger components comprise the following: Scope Type CodeTrigger Scope Triggers work depending on the scope they have. The scope of the trigger depends on its position in the form object hierarchy, that is, the type of object under which you create the trigger. The three levels in form hierarchy are: Form Level Block Level Item LevelDepending on the levels of hierarchy, we have following triggers:Confidential © SQL Star International Ltd. 145
  • 149. Trigger Types Fire when An event occurs across the entire form. An event occurs in the current block. An event occurs in the current item The following diagram illustrates the scope of the triggers:Confidential © SQL Star International Ltd. 146
  • 150. Form Level Event Block Level dbMember txtMemID txtFirstName txtLastName txtAddress Event Block Level Event dbBook The scope of a trigger plays an important role when there is more than one trigger with the same name but at different levels. The trigger, which is most appropriate, will fire for that event. The Execution Hierarchy property of the trigger controls the firing sequence of the triggers when there is more than one trigger of same type at the same level. The default value of Execution Hierarchy property of the trigger is ‘Override’. You can very well alter the trigger firing sequence by setting the Execution Hierarchy property of the trigger. The following table gives you the brief idea of the trigger Execution Hierarchy property: Description The trigger that is most specific to the cursor location will fire.Confidential © SQL Star International Ltd. 147
  • 151. Description The trigger will fire after firing the same trigger at the next higher level The trigger will fire before firing the same trigger at the next higher level The diagram below shows you the default execution hierarchy of triggers. On-Message Form 1 Level Pass the Event Block On-Message Level 2 Pass the Event Item On-Message Level 3 Even Pass the EventTrigger types Triggers are divided according to their type and scope. The trigger type defines the type of event that fires it. According to their availability, triggers are classified as: Built-in User-namedConfidential © SQL Star International Ltd. 148
  • 152. NOTE All the built-in trigger names always contain a hyphen (- All the built-in trigger names always contain a hyphen (-). ). For example: For example: WHEN-BUTTON-PRESSED WHEN-BUTTON-PRESSED Trigger prefix Description KEY- Fires when the function keys are pressed. ON- Fires on the occurrence of the trigger event. PRE- Fires before the action of the trigger event. POST- Fires just after the action of the trigger event. WHEN- Fires the trigger when an appropriate event occurs.Trigger code The trigger code defines the action to be performed when the trigger fires. Trigger code is an anonymous PL/SQL block in the PL/SQL Editor. When writing a trigger you could: Use standard constructs (assignments, control statements, and so on). Use SQL statements that are passed to the server for execution. Make calls to other user defined subprograms that are in the Form Builder or the database. Make a call to the built-in subprograms and packages, which are part of Forms Developer. Points to remember while using SQL statements in a trigger are: DML statements must be used only in the transactional triggers. This is because these triggers fire during the commit process. Transactional Control Statements (COMMIT, ROLLBACK, and SAVEPOINT) cannot be used in the trigger statements. This is because these actions get carried out as a result of some of the built-in subprograms issued in the trigger statements.Confidential © SQL Star International Ltd. 149
  • 153. Create Triggers The purpose of creating a trigger is to add functionality to the existing triggers.Selecting Triggers in the Form Builder The built-in list of the triggers are selected by: Using the Smart Triggers option Using the Object Navigator Using the Layout Editor Using the PL/SQL EditorUsing Smart Triggers Smart triggers are the one, which are more appropriate to the specific level. Creating triggers using smart triggers is very simple and easy. The steps involved in accessing the smart triggers are: 1. Select an object for which you want to define a trigger from either the Object Navigator or the Layout Editor. Right click the object. You get the pop up menu that displays an option called Smart Triggers. 2. Expand the Smart Triggers option further to give you the list of most appropriate triggers that are associated with the selected object. 3. Select one of these triggers and the PL/SQL Editor is opened to write the trigger code. Below is the diagram of a smart trigger:Confidential © SQL Star International Ltd. 150
  • 154. The diagram below shows you the PL/SQL Editor. Using the Object Navigator The steps to access the trigger from the Object Navigator are: 1. In the Object Navigator select the Trigger node of the form, block or item.Confidential © SQL Star International Ltd. 151
  • 155. 2. Select Program-> Smart trigger. This creates icon on the toolbar. The list of triggers is displayed as shown in the following figure. 3. Choose the appropriate trigger from the list of triggers that has been invoked. 4. The PL/SQL Editor is invoked, where you can write the trigger code.Using the Layout EditorThe steps to access the trigger from the Layout Editor are: 1. In the Layout Editor, select the object and right click the mouse to display the popup list. Select PL/SQL from the popup list. 2. This will invoke a list of triggers. Choose the appropriate trigger in it. 3. This will invoke a PL/SQL Editor where you can write the trigger code.Using the PL/SQL EditorThe steps to access the trigger from PL/SQL Editor are: 1. In the Object Navigator, choose the form, block or item you want to create a trigger. 2. Select Program->PL/SQL Editor from the menu, this will invoke the list of triggers. 3. Choose the appropriate trigger from the list; this will invoke the PL/SQL Editor, where you can write the code for the trigger. The figure below shows you the option of selecting the PL/SQL Editor.Confidential © SQL Star International Ltd. 152
  • 156. Trigger properties Triggers have relatively few properties. The trigger name defines when it is invoked and the trigger code defines its functionality. The screen grab given below, shows you the trigger Property Palette. The properties of the trigger are categorized into mainly two types: General Functional The table below gives you the General properties of the trigger and their functionality: Property Name FunctionNa To give an internal name to the trigger.Subinformation To ease the task of changing global properties for a trigger.Cts To record any information about the trigger. The table below gives you the Functional properties of the trigger and their functionality: Confidential © SQL Star International Ltd. 153
  • 157. Property Name Function Trigger style It is read only value set to PL/SQL Trigger text Contains a More… Button that opens the PL/SQL Editor for entering and editing the triggers codes. Fire in Enter-Query Mode Specifies whether the trigger should fire when the forms are in the Enter Query mode. This property is only applicable to the triggers related to actions that are valid in the Enter Query mode. Execution Hierarchy Defines whether this trigger should override the higher-level one, execute before it, or execute after it, if the same trigger is defined at all levelsTrigger Editors The Trigger Editor is a tool to edit the code of a trigger. It can be used to add, modify or delete the trigger code. There are two types of editors that are available with the Forms Builder. PL/SQL Editor Database Trigger EditorPL/SQL Editor The PL/SQL Editor has the following features: Automatic indenting Syntax highlighting Text manipulation by dragging and dropping Unlimited undo and redoConfidential © SQL Star International Ltd. 154
  • 158. Creation of four views of the current program unit in the PL/SQL Editor by using split bar buttons as shown below Display and copy the PL/SQL constructs and built-in subprograms into the editor using the Syntax Palette. This reduces coding time. Steps to invoke the Syntax Palette are: 1. Select Tools->Syntax Palette from the main menu. 2. Choose the basic construct available in the Syntax Palette and click the Insert button. 3. The code will be placed on to the PL/SQL Editor.The diagram below shows you the Syntax Palette and the use of it:Confidential © SQL Star International Ltd. 155
  • 159. The above diagram shows the working of the Syntax Palette. When you click on Insert button of the Syntax Palette, the basic PL/SQL construct that you select will be copied on to your PL/SQL Editor. Similarly, you can make use of the Built-in subprograms. You can do the global search and replace the text string or expressions in your PL/SQL Editor. Steps involve in searching and replacing the text strings and expressions are: 1. Invoke the Find and Replace in Program Units dialog box by selecting Edit- > Find and Replace PL/SQL from the menu. 2. Type the character string that you need to search in the PL/SQL Editor in Find What text field. 5. Type the character string that is to be replaced with the old text in Replace With text field. a. Click on the Find All button to find text strings that are there in the code mentioned in the Find What text field. b. Click on the Replace All button to replace the old text with the new text mentioned. c. The following screen grab shows you the Find and Replace functionality provided in the Program Units dialog box:Confidential © SQL Star International Ltd. 156
  • 160. NOTE Modified text in triggers needs to be recompiled. Compiling triggers with SQL statements need to have database connection.Database Trigger Editor The Database Trigger Editor is used to edit and create a database trigger. Following steps show how the editor is used: 1. In the Object Navigator, expand the Database Objects node. This displays the Schema node in that database. 2. Expand the Schema node to view all the database objects. 3. Expand the Tables node within the Schema node to view all the tables in that schema. 4. Select the desired table and expand its node.Confidential © SQL Star International Ltd. 157
  • 161. 5. Select the Trigger node under it and click the Create icon. The Database Trigger Editor will be displayed on your screen. 6. In the Database Trigger Editor, click the New button to create the new trigger. Write the code of the trigger in the trigger body pane of the Database Trigger Editor. Given below is the database trigger editor:Writing the Trigger Code The trigger code consists of three sections: A declaration section for variables, constants, and exceptions An executable section An exception handling sectionThe declaration and exception handler sections are optional. If your trigger codedoes not require the defined variables, you need not include the BEGIN and ENDkeywords.Variables in Form Builder Two types of variables used for storing values are: PL/SQL variables: These variables must be declared in the DECLARE section. They are not prefixed by a colon (:). Form Builder variables: The Form Builder variables are not declared in the DECLARE section. The Form Builder maintains them. They are known as external variables and need to be prefixed with a colon (:) to distinguish them from PL/SQL objects.Types of Form Builder variables are listed below in the following table:Confidential © SQL Star International Ltd. 158
  • 162. Form Builder – Syntax Scope UseVariable TypesItem :block_name.item_name Current form and Interaction with user. attached menu.Global :GLOBAL.variable_name All modules in Storing session-wide current session. character data.System :SYSTEM.variable_name Current form and Form status and control. attached menu.Parameter :PARAMETER.name Current module. Passing values in and out of the module.Built-in Subprograms in Triggers Form Builder provides a set of predefined subprograms. They are divided into 2 categories: Standard Extensions Packages: These built-ins are incorporated in the standard PL/SQL command set of the Form Builder. They can be called from triggers directly with out any package prefix. Form Builder provides more than one hundred such built-ins; such as NEXT_ITEM, GO_ITEM, COMMIT_FORM, etc. Other Form Builder Packages: The subprograms in other built-in packages provide functionality related to a particular supported feature. These require the package name as a prefix when called. You can use built-in subprograms in trigger or in a user-defined subprogram in which you use PL/SQL. The built-ins are divided into two groups: Unrestricted built-ins: These built-ins can be used in any subprogram or a trigger. Restricted built-ins: These built-ins are allowed only in certain triggers and subprograms.Built-in Definitions in the Form Builder The steps to include the definition of the built-ins when writing code for a subprogram or a trigger in the Form Builder are: 1. Place the cursor where the built-in subprogram needs to be called. 2. Expand the Built-in Packages node in the Object Navigator, and select the procedure or function you need. 3. Copy the built-in prototype arguments or name, or both by selecting Edit- >Paste Name or Edit->Paste Arguments from the main menu. 4. The definition of the built-in is copied to the cursor position in the PL/SQL Editor.Confidential © SQL Star International Ltd. 159
  • 163. Package UseDDE Provides support for dynamic data exchangeDEBUG Provides support for debugging program units.EXEC_SQL Support for executing dynamic SQL within PL/SQL.OLE2 For using OLE2 automation Objects.ORA_FFI For calling the Foreign (C) functions from PL/SQLORA_NLS For extracting high-level information for native language environment.ORA_PROF For tuning PL/SQL program units.TEXT_IO To read and write information from and to files.TOOL_ENV To interact with oracle environment variables.TOOLS_ERR To access and manipulate the error stack.TOOL_RES To manipulate resource files.VBX For controlling and interacting with VBX controls.WEB For working the web environment.The built-in subprogram can be a procedure or a function. The built-in procedure is known as a complete statement in a trigger or program unit with mandatory arguments. The built-in functions are known as being a part of a statement in a trigger or program unit, at a position where the function’s return value will be used. Again, the function call must include the mandatory arguments.For example, the SHOW_LOV built-in is a function that returns a Boolean value.The following table shows the useful built-ins for adding functionality to items:Confidential © SQL Star International Ltd. 160
  • 164. Built-in Subprograms DescriptionEDIT_TEXTITEM procedure Shows forms runtime item editor for the current text item.ENTER_QUERY procedure Clears the current block, and creates a sample recordEXECUTE_QUERY procedure Clears the current block, opens a query, and fetches a number of selected recordsEXIT_FORM procedure Exits the current formGET_ITEM_PROPERTY function Returns specified property values for the specified itemGO_BLOCK procedure Goes to the specific blockGO_ITEM procedure Goes to the specific itemHIDE_VIEW procedure Hides the specified canvasLIST_VALUES procedure Shows the LOV attached to the specified itemMESSAGE procedure Shows the specified text on the message lineSET_ITEM_PROPERTY Changes setting of specified property for an itemprocedureSHOW_ALERT function Shows the given alert, and returns a numeric value when the operator selects one of the three alert buttonsSHOW_EDITOR function Shows the specified EDITOR at given coordinates and passes a string from the editorSHOW_LOV function Invokes the specified LOV and returns boolean value, indicating whether user selected a value from the listSHOW_VIEW procedure Displays the indicated canvas at the coordinates specified by the X and Y positions of the canvas property settings. To create a trigger in frmLib form module: • Invoke the Layout Editor of the Member block and create a button pbExecute labeled ‘Execute’. • Right click the button to display the pop up menu. • Select the Smart Triggers from the pop up menu, which in turn displays appropriate triggers for Button. • Select WHEN-BUTTON-PRESSED trigger to invoke the PL/SQL Editor. • Write the following code in the WHEN-BUTTON-PRESSED trigger body in the PL/SQL Editor. EXECUTE_QUERY; When you click the button it will execute the query and fetch the records into the form. When-Window-closed trigger:Use this trigger to programmatically close a window when the operator issues thewindow-manager Close command. You can hide the window that contains thecurrent item.Confidential © SQL Star International Ltd. 161
  • 165. Debugging Triggers Triggers are checked for errors in logic and syntax like any other PL/SQL blocks.Debugging Process You can debug the triggers in the following ways: Compiling: Syntax errors and object reference errors are recorded when you compile the trigger. These errors can be rectified or corrected in the PL/SQL Editor before you run the trigger. Running a form with run time parameter DEBUG_MESSAGE =’Yes’. In the Debug mode, you can request messages to be displayed to indicate when the particular trigger has been fired. This will help you in tracing out when the triggers are being fired, their origin and level in the form module and also the time at which they fire. Invoking the PL/SQL Debugger: The Debugger is used to monitor the execution of the code within a trigger or in any other program units. You can check the code in a line-by-line basis, and you can monitor programs and variables to perform the tasks, they assigned to do.Running Forms in Debug Mode The Debug mode is used to monitor the triggers that fire using the PL/SQL Debugger. To debug the form module, you need to rebuild the forms run-time module. To run the form in the Debug mode, you need to: Open the code that is to be debugged and set a breakpoint by right clicking in the executable section and select Insert break point option. 1. Click the Run Form Debug button in the Object Navigator, or select Debug-> Debug Module from the main menu. This builds and also runs the form module automatically. The PL/SQL Debugger is used to: Perform step-by-step walk through in the program units to examine their progress. Examine or modify the state of variables during execution. Set the break points to pause execution, so that you can analyze the state of your application at a particular point. Add or modify the PL/SQL statements during execution.The following screen shows the PL/SQL Debugger and its components:Confidential © SQL Star International Ltd. 162
  • 166. The Debug ConsoleThe debug console is a workspace in Forms Builder that enables us to see variousaspects of the running a form in its environment.Display the debug console by selecting Debug --> Debug Console from the menu.It displays automatically when you encounter a breakpoint in a form that isrunning in debug mode.Within the console several types of panels are displayed: 1. Stack Panel: Display us the Hierarchy of the Execution of the subprograms i.e. the chain of subprograms starting from the initial entry point down to the currently executing subprograms. 2. Variables Panel: This variables panel displays the variables of the current form with the current values. When the form is suspended, the variable values can be changed to a new value, which is further used in the program. 3. Watch Panel: The Watch panel provides a centralized area to keep track of any valid scalar variables except stored package variable that we specify in the program. 4. Form Values Panel: This is used to display the values of all items and parameters in modules that are currently running. 5. Breakpoints Panel: It displays any breakpoints set in the code during the current Forms Builder session.Confidential © SQL Star International Ltd. 163
  • 167. 6. PL/SQL Packages Panel: This panel is used only to browse and examine the PL/SQL packages which are been instantiated while executing the form. 7. Global and System Variables Panel: This Panel displays the current system and global variables and their values used in the form module.Running the Form Module using the Debugger Running the form module using the debugger is very simple and easy. Let us take the form module (frmLib), which you have built already. 1. Click the run in debug mode icon in the toolbar. 2. As it encounters the breakpoint set in the executable part of the code, the debug console blinks at the bottom of the task bar in your system. 3. PL/SQL debugger enables us to step the program unit using various buttons: • Step Into: Executes the next statement. • Step out: Complete the current subprogram and steps to the next calling program. • Step Over: Takes the control to the next statement without stepping into a nested subprogram. • Stop: It terminates the debugging process and terminates the application execution. • Pause: It temporarily stops the debugging process, which can be resumed again by pressing the same button.Confidential © SQL Star International Ltd. 164
  • 168. Summary In this chapter, you have learnt that: • The trigger name defines what event will invoke it. • Events can be classified as query-related events, validation events, navigation events, mouse related events, key related events, error and message events. • Trigger components comprises Scope, Type and Code. • The trigger type defines the type of event that fires it. According to their availability, triggers are classified into built-in and User-named triggers. • Smart triggers are the one, which are more appropriate to the specific level. • The trigger name defines when it is invoked and the trigger code defines its functionality. • The Trigger Editor is a tool to edit the code of a trigger that can be used to add, modify or delete the trigger code. • The PL/SQL Editor has Automatic indenting and syntax highlighting, etc. • The Database Trigger Editor is used to edit and create a database trigger. • Form Builder provides a set of predefined subprograms like standard extensions packages and builder packages. • You can debug the triggers by compiling and invoking the PL/SQL Debugger etc. • The PL/SQL Debugger is also used to perform step-by-step walk through in the program units to examine their progress..Confidential © SQL Star International Ltd. 165
  • 169. Lab ExercisePerform the following on BRANCHXX Form 1. Add functionality to the push buttons created in the TOOLBAR_BRANCH canvas. When the Image button is clicked it should work as Toggle button i.e; o When the button is clicked, the image item should disappear and the label of button should change to “Image on”; when the button is clicked again, the image item should appear and the label should change to “image off” dynamically. 2. Create iconic push buttons on the TOOLBAR_BRANCH canvas for performing previous block, previous record, next record, next block, executing a query, save and exit. o Add functionality to the above buttons. 3. Make a Provision for the user to exit the form using close button on window. 4. Write functionality such that o When library staff window is closed the focus should go to the member fee window. o When member fee window is closed the focus should go to the Transaction window. o When Transaction window is closed the focus should go to the Branch window. 5. Add functionality to SHOW_HELP Button to display the CV_HELP canvas. 6. Write trigger on HIDE_HELP Button (created on stacked canvas in the previous chapter) to hide the CV_HELP. 7. Open BRANCHXX form module. In When-Button-Pressed trigger of Image button: IF GET_ITEM_PROPERTY(CONTROL.image,VISIBLE)=TRUE THEN SET_ITEM_PROPERTY(CONTROL.image, VISIBLE, PROPERTY_FALSE); SET_ITEM_PROPERTY(CONTROL.image_off,LABEL,Image On); ELSE SET_ITEM_PROPERTY(CONTROL.image, VISIBLE, PROPERTY_TRUE); SET_ITEM_PROPERTY(CONTROL.image_off,LABEL,Image Off); END IF;Confidential © SQL Star International Ltd. 166
  • 170. • Modify the ‘CONTROL.IMAGE’ in the code to ‘Images’ of CONTROL.IMAGE Button • Compile and run it. Press the Image button and test that Image is not displayed. • Now run the form in Debug mode by setting a break point in the When-Button Pressed trigger of the IMAGE button. • Test the importance and how much it is helpful to identify the errors of running the form in debug modeConfidential © SQL Star International Ltd. 167
  • 171. Chapter 10 Item Interaction Triggers and Alerts Functionality of Input Items List Items Check Boxes Radio Buttons Functionality of Non-Input Items Displaying LOVs by Using Buttons Populating Image Items Adding Data to a hierarchical Tree View Adding Functionality to Bean Area Run Time Messages Built-in Functions for Success and Failure Suppressing Messages Triggers Intercepting System Messages AlertsConfidential © SQL Star International Ltd. 168
  • 172. ObjectiveAt the end of this chapter, you will be able to: • Understand Functionality of Input Items • Learn about List Items, Check Boxes and Radio Buttons • Understand the Functionality of Non-Input Items • Know how to display LOVs by Using Buttons • Populate Image Items • Add Data to a hierarchical Tree view • Add functionality to Bean area • Learn from Run time messages • Understand Built-in functions for success and failure • Know various ways to Suppress messages • Describe Triggers intercepting system messages • Get the idea about AlertsConfidential © SQL Star International Ltd. 169
  • 173. Functionality of Input ItemsThere are various types of GUI items that the user can interact either by pressinga function key or by using a mouse.Item Interaction TriggersThe following item interaction triggers are fired when users interact with inputitems: WHEN-LIST-ACTIVATED trigger is fired when an element in a list item is double-clicked, and is fired only for T-list style list items. WHEN-LIST-CHANGED trigger is fired when a different element is selected from a list item or de-selects the element that is already selected. WHEN-RADIO-CHANGED trigger is fired when a radio button is selected in a radio group, or de-selects the radio button that is already a radio button WHEN-CHECKBOX-CHANGED trigger is fired when the state of a check box is changed.List ItemsYou have two types of triggers to use in list items. They are: WHEN-LIST-ACTIVATED trigger: This trigger is fired only when the user double clicks an element in a ‘T-list’. WHEN-LIST-CHANGED trigger: It is fired when the user changes the value of a list item.The following item Property Palette shows the Item Type and List Styleproperties set to ‘List Item’ and ‘Tlist’ respectively:Confidential © SQL Star International Ltd. 170
  • 174. WHEN-LIST-CHANGED trigger: This trigger is fired when the user changes the element of the list. This trigger is not fired if an element is changed programmatically by using the DUPLICATE_ITEM built-in, or by invoking a procedure. An element can be added by using the ADD_LIST_ELEMENT built-in and can be removed by using the DELETE_LIST_ELEMENT built-in. The syntax for which is: ADD_LIST_ELEMENT (‘LIST_ITEM_NAME’, INDEX, ‘LABEL’, ‘VALUE’); Example: ADD_LIST_ITEM (‘cbranchlocation’, 1,’ ’Adelphia’, ’Adelphia’); DELETE_LIST_ELEMENT (‘LIST_ITEM_NAME’, INDEX); Where, LABEL is the name of the element VALUE is the new value for the element. INDEX is the number that identifies the position of element in the list.Confidential © SQL Star International Ltd. 171
  • 175. Check BoxesWhen a checkbox gets selected or deselected, the value associated with thatcheckbox is changed. CHECKBOX_CHECKED function gives a Boolean valueindicating the state of the given check box.The trigger used to provide additional functionality to check boxes is WHEN-CHECKBOX-CHANGED trigger. This trigger fires when the state of a check box ischanged, either by using the keyboard or clicking it with the mouse. This triggercan be defined at item, block or form level. For example, create a non-databasedisplay item diStatus labeled ‘Status’ in ControlBlk of frmLib. Write a WHEN-CHECKBOX-CHANGED trigger that would display the value ‘Married’ in diStatuswhen the checkbox is checked and the value ‘Unmarried’ when the checkbox isunchecked. IF CHECKBOX_CHECKED (cbMaritalStatus) = TRUE THEN :diStatus:=Married; ELSE :diStatus:=Unmarried; END IF;Radio ButtonsIn a radio group, only one radio button can be selected. The trigger used toprovide additional functionality to radio buttons is WHEN-RADIO-CHANGEDtrigger. This trigger fires when a radio button is selected or deselected in a radiogroup, either by using the keyboard or by clicking with the mouse. This triggercan also be defined at item, block or form level.For example, by selecting a radio button, the user can change the value of theradio group item.Example for When-Radio-changed: declare n number; begin if :member.nage between 5 and 13 and :member.cgrade !=A then n:=show_alert(Grade); :MEMBER.CGRADE:=A; ELSIF :member.nage between 14 and 20 and :member.cgrade !=B then n:=show_alert(Grade); :MEMBER.CGRADE:=B; ELSIF :member.nage between 21 and 50 AND :member.cgrade !=C then n:=show_alert(Grade); :MEMBER.CGRADE:=C;Confidential © SQL Star International Ltd. 172
  • 176. ELSIF :member.nage between 51 and 100 AND :member.cgrade !=D then n:=show_alert(Grade); :MEMBER.CGRADE:=D; END IF; END;Functionality of Non-Input ItemsThe following item interaction triggers are fired when users interact with non-input items: WHEN-IMAGE-ACTIVATED trigger is fired when the user double clicks an image item. WHEN-IMAGE-PRESSED trigger is fired when the user clicks an image item. WHEN-BUTTON-PRESSED trigger is fired when a button is selected either by clicking with a mouse or using the keyboard.Displaying LOVs by Using ButtonsA LOV is a scrollable window that consists of a single or a multi-column selectionlist, as shown below. You cannot dismiss an LOV unless the user selects a valuefrom the list or chooses the Cancel button.An LOV provides the following functionality: It is displayed on the user request. At the design time, it can be attached with one or more text items. It contains values derived from record groups.Confidential © SQL Star International Ltd. 173
  • 177. Record GroupWhen a LOV is defined, it gets associated with a named record group by default.A record group consists of rows and columns that are very much similar to thedatabase table. Using LOV, the user can scroll, select records that are stored inthe underlying record group.An LOV can be invoked in two ways: • LIST_VALUES Built-in • SHOW_LOV Built-inLIST_VALUES Built-inLIST_VALUES built-in displays the list of values for the item with which an LOV isassociated. This built-in by default uses the NO_RESTRICT parameter. FormBuilder cannot use the automatic search and complete feature if theNO_RESTRICT parameter is used. By automatic search and complete feature, wemean that an LOV evaluates the current value of the text item (to which an LOVis attached) as a search value. Form Builder automatically uses that value as ifthe user had entered the value into the LOVs search field and pressed [List] tonarrow the list.If the item value would narrow the list to only one value, Form Builder does notdisplay the LOV, but automatically reads the correct value into the field.To see its usage, create a button pbListDisplay in ControlBlk of frmLib moduleand label it as ‘Display List of Values’. Write the following code in the WHEN-BUTTON-PRESSED trigger to invoke lvBranch LOV:LIST_VALUES;Points to remember while using LIST_VALUES built-in are: Arrange the button created (pbListDisplay) on the canvas where it can easily be associated with the item to which the LOV has been attached. Set the button’s Mouse Navigate property to ‘No’. While using LIST_VALUES, ensure that the cursor resides in the item to which an LOV has been attached.SHOW_LOV Built-inSHOW_LOV displays the LOV at the specified coordinates SHOW_LOV (lov_id LOV); SHOW_LOV (lov_id LOV, x NUMBER, y NUMBER); SHOW_LOV (lov_name VARCHAR2,x NUMBER, y NUMBER);Where, lov_id is the unique ID assigned to the LOV. FIND_LOV built-in is used to return the ID to an appropriately typed variable. lov_name is the name given to the LOV. The data type of the name is VARCHAR2. x specifies the x coordinates of the LOV. y specifies the y coordinates of the LOV.Confidential © SQL Star International Ltd. 174
  • 178. The SHOW_LOV built-in returns a Boolean value of: ‘True’ if a record is selected from the LOV ‘False’ if a record is not selected from LOV. Write the following code in the WHEN-BUTTON-PRESSED trigger of pbListDisplay: DECLARE vValueChosen BOOLEAN; BEGIN vValueChosen:=Show_Lov (lvBranch); IF NOT vValueChosen THEN Message (You have not selected a value.); RAISE Form_Trigger_Failure; END IF; END; Invoking Dynamic LOVs: Dynamic LOVs allow us to use one LOV for multiple items. Associating LOV at run time: SET_ITEM_PROPERTY (LOV_NAME,’my_lov’); We can also use a dynamic record group: DECLARE rg_id NUMBER; BEGIN SET_LOV_PROPERTY (MEMBER_LOV, TITLE,AGE); rg_id := POPULATE_GROUP_WITH_QUERY(MEMBER_RG,SELECT cmemberid ID, cfirstname NAME FROM member where nage between 35 and 70);SYNCHRONIZE;LIST_VALUES;IF :global.id IS NOT NULL THEN :member.cmemberid := :global.id; :member.cfirstname := :global.name;ELSE :global.id := NULL; END IF; END; Populating Image Items Form Builder supports various graphics file formats. Confidential © SQL Star International Ltd. 175
  • 179. Format Image Item BMP Read/Write JFIF Read/Write PCX Read Only PICT 1 & 2 Read/Write GIF Read/Write CALS Read/Write PCD Read Only RAS Read/Write TIFF 4, 5 & 6 Read/WriteThe two types of images included in Form Builder are: Graphic Objects: A graphic object is a static image imported from the file system or database. Such objects are generally used as background pictures. Image Items: An image item is an interface control. An image item can also be a data block item or a control block item. Two types of triggers are fired when the user interacts with an image item: WHEN-IMAGE-ACTIVATED WHEN-IMAGE-PRESSEDREAD_IMAGE_FILE ProcedureReads an image of the given type from the given file and displays it in the formbuilder image item.The syntax is: READ_IMAGE_FILE (file_name VARCHAR2,file_type VARCHAR2, item_idITEM); READ_IMAGE_FILE(file_name VARCHAR2,file_type VARCHAR2,item_nameVARCHAR2);Where, file_name is the valid file name. file_type is the valid image file type: BMP, CALS, GIF, JFIF, JPG, PICT, RAS, TIFF, or TPIC. item_id is assigned to the image item when the Form builder creates it. Use the FIND_ITEM built-in to return the ID to an appropriately typed variable.Confidential © SQL Star International Ltd. 176
  • 180. item_name is the name given to the image item when it is created.To display an image when an image item is pressed: 25. Create an image item imgLib in ControlBlk of frmLib module. Give it a suitable prompt say ‘Library Image’. 26. To display the image when pressed, write the following code in the WHEN- IMAGE-PRESSED trigger: READ_IMAGE_FILE (c:A002033.gif,gif,imgLib); 27. When you press the image at runtime, you get the following output:Adding Data to a hierarchical Tree ViewThe steps to add data to a hierarchical tree view are: 1. Populate a tree with values in a record group or by using the POPULATE_TREE built-in 2. Use ADD_TREE_DATA built-in to add data to a tree under a specific node 3. Using built-in subprograms to modify elements in a tree 4. Add or delete nodes and the data elements under the nodesConfidential © SQL Star International Ltd. 177
  • 181. SET_TREE_PROPERTY ProcedureThis procedure sets the value of the indicated hierarchical tree property.Its syntax is: SET_TREE_PROPERTY (item_name VARCHAR2, property NUMBER, value NUMBER | VARCHAR2 | RECORDGROUP); SET_TREE_PROPERTY (item_id ITEM, property NUMBER, value NUMBER | VARCHAR2 | RECORDGROUP);Where, item_name is the name of the object created at design time. item_id is assigned to the item when Form Builder creates it. FIND_ITEM built-in is used to return the ID to an appropriately typed variable. property specifies one of the following properties: RECORD_GROUP: The data set of the Hierarchical Tree is replaced with a record group and causes it to display. QUERY_TEXT: The data set of the Hierarchical Tree is replaced with an SQL query and causes it to display. ALLOW_EMPTY_BRANCHES: Possible values are PROPERTY_TRUE and PROPERTY_FALSE. value specifies the value appropriate to the property you are setting: PROPERTY_TRUE: This is to be set to the true state. PROPERTY_FALSE: This is to be set to the false state.Adding Functionality to Bean AreaWe have already learned how to add a Java Bean to form using Bean Area Item.However, Beans such as Color Picker may not have visible components for whichwe need to create a button.Whether the bean is visible or not, some communication must be presentbetween java classes and run-time form.The form must know the bean, either by registering a bean and its events at run-time or setting Implementation Class Property at design time.Confidential © SQL Star International Ltd. 178
  • 182. Methods Properties EventsTo communicate with the Java Beans we use a package called FBEAN package.This package contains Forms built-ins that are used to communicate withJavaBeans in PL/SQL.Most of the built-ins take some common arguments: Item Name or Item ID (obtained with the FIND_ITEM built-in): It is the first argument taken by FBEAN built-ins. Item Instance: It acts like a reference to which instance of item should the bean contain. This is applied only where the Bean Area is part of a multirow block and more than one instance of the Bean Area is displayed. You can use the value ALL_ROWS (or FBEAN.ALL_ROWS) for the Item Instance value to specify that command is to be applied to all of the instances of this Bean Area in the block. Value: It accepts BOOLEAN, VARCHAR2, or NUMBER data types.Confidential © SQL Star International Ltd. 179
  • 183. Some of the built-ins in the FBEAN package are: Built-in Parameters GET_PROPERTY ITEM,INSTANCE,PROPERTY_NAME returns VARCHAR2 SET_PROPERTY ITEM,INSTANCE,PROPERTY_NAME, VALUE INVOKE ITEM,INSTANCE,METHOD_NAME[,ARGUMENTS] ENABLE_EVENT ITEM,INSTANCE,EVENT_LISTENER_NAME, SUBSCRIBE REGISTER_BEAN ITEM,INSTANCE,BEAN_CLASS (The last argument is the full class name of the bean, such as oracle.forms.demos.beans.ColorPicker) You can pass arguments to these built-ins as either a delimited string or as an argument list.Bean Deployment:As the bean itself is a Java class or set of Java class files separate from the formmodule, you need to know where to put these files.Confidential © SQL Star International Ltd. 180
  • 184. Either in the directory structure referenced by the form applet’s CODEBASEparameter or in the server’s CLASSPATH of the middle-tier server. The defaultCODEBASE is the formsjava subdirectory of ORACLE_HOME. The CODEBASE and ARCHIVE parameters are set in theformsweb.cfg file.If it is JInitiator, in a JAR file in the middle-tier server’s CODEBASE directory, andincluded in the ARCHIVE parameter so that the JAR file is downloaded to andcached on the client. For example: archive_jini=frmall_jinit.jar, colorpicker.jarRespond to an Event:At run-time when the user tries to communicate with a Java Bean, an event erroroccurs. In order to escape from this error, forms will fire When-Custom-Item-Event trigger if we use FBEAN.ENABLE_EVENT to register a listener for the event.The code to be written in this trigger is::SYSTEM.CUSTOM_ITEM_EVENT and :SYSTEM.CUSTOM_EVENT_PARAMETERSThese two variables contain name of the event and information the bean issending to the form.The steps involved to communicate with the bean are: 1. The user clicks the bean area for a Calendar bean. This bean area has a visible component on the form that looks like a button. The label is set to the hire date for an employee. 2. The Calendar bean is invoked and displays a calendar initially set to the employee’s hire date. 3. The user changes the date on the bean by picking a new month and year, and then clicking on a day, which initiates the DateChanged event. 4. The When-Custom-Item-Event trigger obtains the changed date and assigns it back to the employee hire_date item, also changing the label on the bean area “button.”Coding a When-Custom-Item-Event Trigger:To respond to JavaBeans events, you code the action that you want to take placewhen an event occurs.For example, when a user selects a date from the Calendar bean, Custom-Item-Event trigger fires. In the code for the When-Custom-Item-Event trigger on theCalendar bean area item, you need to obtain the name of the event. If it is theDateChange event, you must obtain the new date and assign it to a form item,such as the employee’s hire date. You can use the system variables containingthe event and parameter information.declare hBeanEventDetails ParamList; eventName varchar2(80); paramType number; eventType varchar2(80);Confidential © SQL Star International Ltd. 181
  • 185. newDateVal varchar2(80); newDate date := null; begin hBeanEventDetails := get_parameter_list (:system.custom_item_event_parameters); eventName := :system.custom_item_event; if (eventName = DateChange) then get_parameter_attr(hBeanEventDetails, DateValue, ParamType, newDateVal); newDate := to_date(newDateVal,DD.MM.YYYY); end if; :employees.hire_date := newDate; end;The preceding example is for a bean that uses hand-coded integration. If you usethe FBEAN package to integrate the bean, the name of the value passed back tothe form is always called ‘DATA’.For example:get_parameter_attr (:system.custom_item_event_parameters, DATA, paramType, eventData);(Where paramType and eventData are PL/SQL variables you declare in the When-Custom-Item-Event trigger, like paramType and newDateVal in the precedingexample).Run Time MessagesMessages are displayed at runtime to inform users of certain events occurring inthe session. These messages could be suppressed or modified by users dependingon the nature of the application.The different types of messages used to communicate with the user are: Working message: This message informs the user that the form is currently processing. Such type of message is displayed on the message line. The system variable used to suppress this message is SUPPRESS_WORKING. Error message: This message informs the user of the error that prevents the current action. It is displayed on the message line by default. These errors can be suppressed using the ON-ERROR trigger. Informative message: This message informs the user of the current state of processing or context sensitive information. These messages can be suppressed using the ON-MESSAGE trigger. System alert: Information given to users through Alerts requires users acknowledgement or a reply to a question before processing continues. They are displayed in a modal window.There are certain messages and alerts that the user can build into an application. Application alert: These alerts are designed as part of application and are issued to the user for a response using the SHOW_ALERT built in.Confidential © SQL Star International Ltd. 182
  • 186. Application message: These are the messages that are built into an application using the MESSAGE built-in.Built-in Functions for Success and FailureThere are certain built-in functions that indicate whether an action performed issuccessfully executed or not. Built-in Function Returned Value FORM_SUCCESS True: When action is successful False: Occurrence of an error or a fatal error FORM_FAILURE True: Action is not successful and some error that is not fatal has occurred False: Either action is successful or some fatal error has occurred FORM_FATAL True: Fatal error has occurred False: Either action is successful or some error has occurred that is not fatal.To understand how the built-ins mentioned above could be used, consider thefollowing example:In the ControlBlk of frmLibTrans module, a button pbGoBranch labeled‘Branch’ is created. The following code is written in the WHEN-BUTTON-PRESSEDtrigger: GO_BLOCK (‘BRANCH’); EXECUTE_QUERY;This trigger works fine so long as Branch block exists. However, if Branch blockdoes not exist or is not enterable then GO_BLOCK built-in procedure would fail.Confidential © SQL Star International Ltd. 183
  • 187. This would cause EXECUTE_QUERY procedure to query a wrong block. Toovercome this, use FORM_SUCCESS function to decide if the query should beperformed or not depending on the success of the GO_BLOCK procedure. We cando this as follows: GO_BLOCK (‘BRANCH’); IF FORM_SUCCESS THEN EXECUTE_QUERY; ELSE MESSAGE (‘Navigating to Branch Block failed due to an error’); END IF;Identifying the Error using Built-insWhenever there is an error, you can identify what type of error it is. Three built-infunctions used to identify the errors are: Built-in Returned Value Functions ERROR_TYPE The error is of what type: FRM: Form Builder Error ORA: Oracle Error ERROR_TEXT Description of an error ERROR_CODE Number of an errorSuppressing MessagesTo control the messages while using the form builder applications, use: SYSTEM.MESSAGE_LEVEL: This system variable is used to suppress the specific "severity levels" of messages. ON-ERROR and ON-MESSAGE triggers: These triggers are used to replace the standard processing of messages. SYSTEM.SUPPRESS_WORKING: This system variable is used to suppress the “working …” message at runtime.Confidential © SQL Star International Ltd. 184
  • 188. Level Description 0 All types of messages. 5 Reaffirms an obvious condition. 10 User has made a procedural mistake. 15 User is trying to perform such function for which the form is not designed. 20 Indicates the condition where the user cannot continue an intended action due to a problem with a trigger or another outstanding condition. 25 Indicates a condition due to which the form is not performing correctly. >25 Indicates a message severity level that you cannot suppress.Message Severity LevelsRuntime messages are ranked by severity. SYSTEM.MESSAGE_LEVEL systemvariable is used to control the severity level. There are six levels of messageseverity listed here in increasing order.SYSTEM.MESSAGE_LEVEL stores any one of the following message severitylevels: 0, 5, 10, 15, 20, or 25. The values assigned can be any value between 0and 25, but values lower than 0 or higher than 25 will generate an error. Thedefault value is 0.To assign a value to the SYSTEM.MESSAGE_LEVEL system variable, syntax is: :System.Message_Level := value;For example, create a push button pbRecord (labeled as Record Up) in theMember block of frmLib form module and write the following WHEN-BUTTON-PRESSED trigger to move up one record, using the built in procedure. If the useris already in the first record a message conveying the same should be displayed:(This is a severity level 5 message.) :SYSTEM.MESSAGE_LEVEL := ‘5’; UP; IF NOT FORM_SUCCESS THEN MESSAGE (‘You are in the first record’); END IF; :SYSTEM.MESSAGE_LEVEL := ‘0’;Confidential © SQL Star International Ltd. 185
  • 189. Triggers Intercepting System MessagesTriggers can intercept the system messages before they are displayed. Thesetriggers suppress the display of a message unless issued from the trigger itself.You can define these triggers at any level. These triggers are: 1. ON-ERROR trigger: This trigger is fired when the Form Builder displays a system error message. This trigger is used to: Identify both Form Builder and Oracle server errors and take corrective actions based on the errors that have occurred. To replace the standard error message with a customized message To get the details of an error use the following built-in functions: • ERROR_CODE • ERROR_TEXT • ERROR_TYPE • DBMS_ERROR_TEXT • DBMS_ERROR_CODE For example, to customize the standard system message for error 40202 (“field must be entered”), write the following code: If ERROR_CODE = 40202 THEN MESSAGE (‘Fill the field Tran ID for a transaction’); ELSE MESSAGE (ERROR_TYPE || ‘-‘ || TO_CHAR (ERROR_CODE) || ‘:’ || ERROR_TEXT); END IF; RAISE FORM_TRIGGER_FAILURE; 2. ON-MESSAGE trigger: This trigger suppresses informative messages with customized messages. This trigger is used to: Trap and respond to an informative message. Exclude the message that is inappropriate. To get the information about why the specific message occurs use the following built-in functions: • MESSAGE_CODE • MESSAGE_TEXT • MESSAGE_TYPEFor example, to modify the message, “Cursor is at beginning of field value”(40204), write the following code: IF MESSAGE_CODE = 40204 THENConfidential © SQL Star International Ltd. 186
  • 190. MESSAGE (‘Cursor is at the starting point placed at the beginning of field value’); ELSE MESSAGE (MESSAGE_TYPE || ‘-‘ || TO_CHAR (MESSAGE_CODE) || ‘:’ || MESSAGE_TEXT); END IF;AlertsAn alternative method used to communicate with users is Alerts. Since alerts aredisplayed in a modal window, they force users to respond to the message beforeprocessing can continue.Alerts are used to: Display messages, which users cannot ignore. Ask a question to a user, which could have up to three appropriate answers, such as ‘Yes’, ‘No’, or ‘Cancel’.To use alerts, you need to follow two stages: • Create the alert at design time and set its required properties • Handle the display and responses to the alert using built-ins.There are three styles of alerts: STOP CAUTION NOTEEach style denotes a different level of message severity. A unique icon thatdisplays in the alert window represents message severity visually.The following screens show the STOP, CAUTION, and NOTE alert styles:Confidential © SQL Star International Ltd. 187
  • 191. There are numerous built-in alerts that display pre-defined messages. The usercan create custom alerts that display in response to application-specific events.When an alert displays a message due to the occurrence of some event, the usershould respond by selecting any one of the predefined alert buttons. If any ofthe buttons is selected then the alert is immediately dismissed.Creating an AlertTo create an alert: 1. Click the Alerts node of frmLib module in the Object Navigator 2. Click the Create button in the Toolbar. 3. Double-click the alert object icon to display the Property Palette. 4. Define the name in the Property Palette say alExit. 5. Set the Alert Style property either to ‘STOP’, ‘CAUTION’, or ‘NOTE’. 6. Set the Message property by entering the message you want the alert to display at runtime such as ‘Do you want to close this form’. 7. Give the names to one or more buttons by entering a text label in the Button1 Label, Button 2 Label, and Button 3 Label fields. 8. Choose the Default Alert Button, either ‘Button 1’, ‘Button 2’, or ‘Button 3’.Confidential © SQL Star International Ltd. 188
  • 192. NOTE The default text labels are ‘OK’ for Button 1 and ‘Cancel’ for Button. At least one button must have a label. Buttons that do not have labels are not displayed. Buttons are displayed in the alert in the order that they appear in the Property Palette. SHOW_ALERT Function This function describes how to display an alert at run time and get the user response to the calling trigger. It gives a number that indicates which of the button the user has pressed in response to the alert. The syntax is: SELECTED BUTTON: = SHOW_ALERT (‘ALERT_NAME’); Where, ALERT_NAME: The name of an alert. An ALERT_ID can also be used in place of ALERT_NAME. For example when the user attempts to close the form the alert alExit created in frmLib can be invoked. If the user says ‘OK’ then the EXIT_FORM is called to close the form IF SHOW_ALERT (alExit) = ALERT_BUTTON1 THEN EXIT_FORM; END IF; Confidential © SQL Star International Ltd. 189
  • 193. Controlling AlertsAt run time, using the SET_ALERT_PROPERTY built-in procedure, you can changean alert message. Once an alert message is changed, the user can reuse thesame Alert object, but display a different message each time it is invoked.SET_ALERT_PROPERTY ProcedureThis procedure changes the message text for an existing alert.The syntax is: SET_ALERT_PROPERTY (alert_id ALERT, property NUMBER, message VARCHAR2); SET_ALERT_PROPERTY (alert_name VARCHAR2,property NUMBER, message VARCHAR2);Where,alert_id is assigned to an alert when the Form Builder creates it.alert_name is the name of an alert.property is the specific alert property that the user set: ALERT_MESSAGE_TEXT: Indicated that the user is setting the text of the alert message. TITLE: Indicates the title of the alert. Message indicates the message that is going to replace the current alert message.SET_ALERT_BUTTON_PROPERTY ProcedureThis procedure replaces the label of one of the buttons in an alert.The syntax is: PROCEDURE SET_ALERT_BUTTON_PROPERTY(alert_id ALERT, buttonNUMBER, property VARCHAR2, value VARCHAR2); PROCEDURE SET_ALERT_BUTTON_PROPERTY(alert_name VARCHAR2, button NUMBER, property VARCHAR2, value VARCHAR2);Where alert_id: The ID that is assigned to an alert when the Form Builder creates it. alert_name: The name of an alert. button: Indicates the alert button which the user wants to change property: Indicates the label text for the alert button.Confidential © SQL Star International Ltd. 190
  • 194. value: Indicates the value to be applied to the property.We will see how these built-ins can be used in a later session.DBMS_ERROR_CODE and DBMS_ERROR_MESSAGE are used to handle backenderrors.Confidential © SQL Star International Ltd. 191
  • 195. SummaryIn this chapter, you have learnt that: o There are various item interaction triggers that are fired when users interact with input items. o There are two types of triggers to use list items, like WHEN-LIST- ACTIVATED trigger and WHEN-LIST-CHANGED trigger. o WHEN-LIST-CHANGED trigger is fired when the user changes the element of the list. o The trigger used to provide additional functionality to radio buttons is WHEN-RADIO-CHANGED trigger. o A LOV is a scrollable window that consists of a single or a multi- column selection list cannot be dismissed unless the user selects a value from the list or chooses the Cancel button. When a LOV is defined, it gets associated with a named record group by default. o Two types of triggers are fired when the user interacts with an image item are WHEN-IMAGE-ACTIVATED and WHEN-IMAGE- PRESSED. o To communicate with the Java Beans, we use a package called FBEAN package, which contains Forms built-in used to communicate with JavaBeans in PL/SQL. o The different types of messages used to communicate with the user are working message, error message, informative message and system alert. o Some system variables for suppressing messages are SYSTEM.MESSAGE_LEVEL, ON-ERROR and ON-MESSAGE triggers and SYSTEM.SUPPRESS_WORKING. o Built-in functions indicate whether an action performed is successfully executed or not. o Alerts are an alternative method used to communicate with users displayed in a modal window. They force users to respond to the message before processing can continue. Alerts are used to display messages, which users cannot ignore.Confidential © SQL Star International Ltd. 192
  • 196. Lab Exercise • Write a trigger for Image item such that when the image item is clicked an image should be displayed. • Populate the library staff data into the hierarchical tree item. • Populate the values into the LOV of cbranchid of Branch block and cmemberid of Transaction block using the show_lov built-in and list_values built in respectively. • Include the functionality to the bean area created in the previous chapter to invoke the color picker. • Create a generic alert in BRANCHXX called Alert that allows Ok and Cancel buttons. • Use only the above alert for save and exit, write code such that this single alert is used for both actions. The information displayed by the alert should vary respectively. • Alter the WHEN-BUTTON-PRESSED trigger on CONTROL.Exit_Button that uses Alert to ask the operator to confirm saying ‘Exit from the application?’. • Alter the WHEN-BUTTON-PRESSED trigger on CONTROL.Save_button to use the same alert to ask operator to confirm saying ‘Do you want to save the changes?’. • Display the Errors in the console window into an Alert. To do this create two procedures • To display error related messages • To display information related messages • Invoke these procedures on the form-level in the appropriate trigger.Confidential © SQL Star International Ltd. 193
  • 197. Chapter 11 Item Validation and Query Trigger Validation of Items Levels for Validation Control Validation Using Object Properties Validation Unit Validating from List of Values (LOVs) Using Validation Triggers Built-ins for Validation Validating Data Entered by the User Validation Status Query Processing Query Array Processing Using Query Triggers Coding Triggers for Enter Query Mode Query Information at Run TimeConfidential © SQL Star International Ltd. 194
  • 198. ObjectiveAt the end of this chapter, you will be able to: • Describe validation of items • Know about levels for validation • Understand how to Control Validation • Learn how to use object properties • Define validation unit • Know the way to validate from List of Values (LOVs) • Infer the use of validation triggers • Built-ins for Validation • Validate data entered by the user • Describe Validation Status • Understand Query Processing • Describe Query Array Processing • Use query triggers • Retrieve query information at run time • Know different modes of query triggersConfidential © SQL Star International Ltd. 195
  • 199. Validation of ItemsWhen performing the default validation on any item, the Form Builder makes surethat the item follows all the rules of validation for that item. Defining appropriatetriggers can enhance the default validation. When we define the Validation Unitform property, the user can also control the extent and frequency of validation ina form.Levels for ValidationValidation process is performed at several levels so as to ensure that individualvalues and records follow appropriate rules. The levels at which validation occurare: • Item level: The status of each item is recorded by the Form Builder to ascertain whether they are currently valid or not. In case an item has been changed without being yet marked as valid, then to ensure that the item’s value confirms to the item’s properties, the Form Builder performs standard validation checks. These checks are performed before the firing of any validation triggers defined for the items. Following are the standard checks performed: Data type. Required (if it is required, then check whether the item is null). Format mask. Validate from list (covered later in the session) Lowest and highest range of values allowed. • Record level: Record validation consists of validating all the items in the record after leaving the record. If the record is not valid, then the status of each item in the record is checked for their validity after which a validation trigger defined for the record (if any) fires. Only when a record passes these checks, its status is set to valid. • Block level: Block validation checks all records in the block. • Form level: Form validation checks all blocks in the form.Confidential © SQL Star International Ltd. 196
  • 200. Form Level Block Level Record Level Item LevelThe above diagram represents the four levels at which the validation occurs. Theitem level is the lowest level.Control ValidationValidation occurs when the user navigates out of the validation unit by pressingcertain function keys or when a trigger executes certain built-in subprogramssuch as: • When the ENTER built-in is invoked or [Enter] is pressed. • When a trigger invokes the COMMIT_FORM built-in. In this case Form Builder validates the form regardless of the validation unit.Using Object PropertiesValidation can be controlled by setting certain properties in the Property Palettefor each and every item within the form.To set object properties: • Double-click the Form Module icon in the Object Navigator to display the Property Palette. • Under the Database node, set the Validation Unit to the desired status, as shown below.Confidential © SQL Star International Ltd. 197
  • 201. Validation UnitThe Validation Unit property determines the scope of validation. It defines themaximum amount of data that can be entered in the form before Form Builderstarts validation. The validation unit corresponds to a unit of data in the forms. Itcan be set to any of the following values in the Property Palette: • Default • Item • Record • Block • FormThe property is set as ‘Item’ by default. Item level validation unit indicates thatchanges are validated when the user navigates out of the changed item. Thisensures that both standard validation and firing of the validation triggers can bedone immediately.Confidential © SQL Star International Ltd. 198
  • 202. At other levels (record, block, and form), these checks are put off until usernavigates out of that unit. Validation unit is set above the item level: • If any database references are involved in validation, and therefore, you want to defer the network traffic till the user has completed a record. • If the application executes at block level.Validating from List of Values (LOVs)To use LOVs to validate a text item: • In the Object Navigator, double-click the object icon to display the Property Palette. • Under the List of Values (LOV) node, set the Validate from List property to ‘Yes’. • When Validate from List property is set to ‘Yes’, Form Builder compares the current value of the text item with the values in the first column that are displayed in the LOV.Following are some of the events that occur, depending on the circumstances: • By default, if any one of the values of first column of the LOV matches with the value of the text item, then the validation succeeds, else the LOV is not displayed and the processing is continued. • If the value of the text item matches a partial value of the LOV value, then the full column value of the LOV is returned to the item (if the item is defined as the return item in the LOV) and the item passed through the validation phase. • If the value of the text item matches multiple records in the LOV, then the LOV is displayed to enable the users to choose the appropriate value. • If the value in the text item does not match with one of the values, which are there in the first column of the LOV, then the Form Builder displays the LOV and considers the text item value as the search criteria to reduce the list. • If the user selects a value from the LOV, then Form Builder dismisses the LOV and specifies the selected value to their corresponding return items. • Whenever an LOV is used for validation, Form Builder marks the text item as valid if the end user selects a value from the LOV.Confidential © SQL Star International Ltd. 199
  • 203. Using Validation TriggersValidation triggers are fired when Form Builder validates data in an item orrecord. Form Builder performs validation checks during navigation that occursdue to operator input, programmatic control, or default processing, such as acommit operation.There are two types of Validation triggers: • WHEN-VALIDATE-ITEM trigger: This trigger is fired after the process of item validation. • This trigger is defined at the item, block or form level. For example, to ensure that issue date is before the return date, the WHEN-VALIDATE-ITEM trigger is placed on :Transaction.dReturnDt of frmLibTrans module, as shown below. IF :TRANSACTION.DISSUEDT > :TRANSACTION.DRETURNDT MESSAGE (‘Issue date cannot be after return date’); RAISE FORM_TRIGGER_FAILURE; END IF; • WHEN-VALIDATE-RECORD trigger: This trigger is fired after the process of record validation. This trigger is defined at the block or form level. This trigger is used to make additional checks on the record items, in the order they were entered. For example, the following WHEN-VALIDATE-RECORD trigger on Transaction block of frmLibTrans module ensures that books are not returned before they are issued: IF :TRANSACTION.DISSUEDT > :TRANSACTION.DRETURNDT MESSAGE (‘Issue date cannot be after return date’); RAISE FORM_TRIGGER_FAILURE;Confidential © SQL Star International Ltd. 200
  • 204. END IF;It is a common practice to process input to an item using a When-Validate-Itemtrigger. The trigger itself is processed on the Forms Services. Even validation thatoccurs with a format mask on an item involves a trip to the middle tier.You should consider using Pluggable Java Components (PJCs) to replace thedefault functionality of standard client items, such as text boxes. Then validationof items, such as the date, maximum or minimum values, is contained within anitem. This technique opens up opportunities for more complex, application-specific validation, such as automatic formatting of input—for example, telephonenumbers with the format (XXX) XXX-XXXX. Even a simple numeric format isenforced instantly, not allowing alphabetic keystrokes to be entered into the item.This validation is performed on the client without involving a network round trip,thus improving performance. For example, the Key Filter PJC does not allow theoperator to enter an alphabetic character into the Quantity item. The onlymessage that is displayed on the message line is the item’s Hint.Pluggable Java Components are similar to JavaBeans, and in fact, the two termsare often used interchangeably. Although both are Java components that you canuse in a form, there are the following differences between them: • JavaBeans are implemented in a bean area item, whereas PJCs are implemented in a native Forms item, such as a text item or check box. • PJCs must always have the implementation class specified in the Property Palette, but JavaBeans may be registered at run time with the FBean package.You implement a PJC to replace an item by setting the item’s ImplementationClass property to the class of the PJC. You may use the SET_CUSTOM_PROPERTYbuilt-in to set properties of the PJC that restrict input or else validate the item. Atrun time, Forms looks for the Java class contained on the middle tier or in thearchive files with the path specified in the Implementation Class for the item. Ifyou open keyfilter.jar in WinZip, you find that the path to KeyFilter.class isoracleformsdemos.Built-ins for ValidationThere are certain built-in subprograms in triggers that are used to affectvalidation: Built-ins Use ENTER Validation of data is done in the current validation unit. GET_ITEM_PROPERTY Get the validation status of an item with ITEM_IS_VALID property SET_ITEM_PROPERTY Set the validation status of an item with ITEM_IS_VALID propertyConfidential © SQL Star International Ltd. 201
  • 205. Built-ins Use CLEAR_BLOCK Form Builder removes all records from the current block. CLEAR_FORM Form Builder removes all records from the current form. EXIT_FORM Provides a means to exit a form SET_FORM_PROPERTY Sets the property of a given form VALIDATE This built-in forces the Form Builder to execute validation processing for the indicated validation scope. The different validation scopes are: DEFAULT_SCOPE: Validation is performed for the default scope. FORM_SCOPE: Validation is performed for the current form. BLOCK_SCOPE: Validation is performed for the current block RECORD_SCOPE: Validation is performed for the current record. ITEM_SCOPE: Validation is performed for the current item. NOTE If the default scope is changed using SET_FORM_PROPERTY (Validation Unit) and the VALIDATE built-in (DEFAULT_SCOPE) is called, then the default scope is overridden. In this case, Form Builder will not validate at the default scope but validates at the scope defined by SET FORM PROPERTY built-in.Validating Data Entered by the UserIf the user enters an invalid value in the item, while populating other items, amatching row with the corresponding result will not be found and the SELECTstatement would raise any of the following two exceptions: • NO_DATA_FOUND: If not even a single row is returned from the query. • TOO_MANY_ROWS: If more than one row is returned from the query.For example, create a display item diBookName in the Transaction block offrmLibTrans module and populate it with the book names retrieved from theBook table corresponding to the current book ID entered by the user:Confidential © SQL Star International Ltd. 202
  • 206. SELECT CBOOKNAME INTO :TRANSACTION.CBOOKNAME FROM BOOK WHERE CBOOKID = :TRANSACTION.CBOOKID;While entering the Book ID, if the value is not found in the Book table, theNO_DATA_FOUND exception is raised. As a result, the trigger fails as there is noexception handler to handle it. In such a case, the user receives the followingmessage:FRM-40735: <trigger type> trigger raised unhandled exception <exception>Validation StatusThe first step in validating items and records is checking the status. Statuschecking means whether the form should perform any other additional validation,such as standard validation checks.Item Validation StatusThe three states for an item validation are: • New: When a record is created, Form Builder marks every item in that record as a new item. This is true even if Form Builder populates an item with a default or copied value • Changed: An item is marked as changed item under the following conditions: When any alteration is there in the item, Form Builder immediately marks it as a changed item. Whether a new value is typed into an item or a trigger copies a value into an item, an item is marked as a changed item. When any item in a new record is altered, the Form Builder marks all items in the record as changed records. • Valid: An item is marked as a valid record under the following conditions: When the Form Builder successfully validates an item. Form Builder marks an item as valid item in record that is retrieved from the database. When the Form Builder successfully commits data to the database, it sets all the items in the form as valid items. Form Builder does not validate any changes caused by triggers during the commit transaction.Confidential © SQL Star International Ltd. 203
  • 207. NOTE If an item status is ‘New’ or ‘Changed’, then the validation continues. If an items status is valid, then the item validation stops.Record Validation StatusThe three states for a record are: • New: When the record is first created. • Changed: If an item in the record is marked as a changed record. • Valid: Under the following conditions: When the Form Builder successfully validates all the changed items in a changed record (changing their statuses to Valid). The record remains as changed record if all items in a changed record do not pass validation. When the Form Builder successfully validates all new items in a new record. Record that is retrieved from the database. When the Form Builder successfully commits data to the database. NOTE If a record status is changed, validation continues. If a records status is ‘New’ or ‘Valid’, record validation stops.Query ProcessingTriggers are linked with a query in any one of the following ways: • Queries Triggers fire due to the query. (PRE-QUERY trigger and POST- QUERY trigger, are the two such types of trigger) • Triggers that fire in the Enter Query mode if the Fire in Enter Query Mode property of the trigger is enabled. • For example, WHEN-VALIDATE-ITEM, WHEN-VALIDATE-RECORD, ON- ERROR, ON-MESSAGE, etc. are initiated, either by the user or by any built-in subprogram, the following events take place: 28. A PRE-QUERY trigger (if defined) fires in the Enter Query mode.Confidential © SQL Star International Ltd. 204
  • 208. 29. If the PRE-QUERY trigger fails, the query is terminated. But if it succeeds, based on the conditions in the block, the Form Builder constructs the SELECT query statement. 30. The query statement is then performed. 31. Form Builder retrieves the column values of a row from the database into the new record in the block. 32. The record is marked as a valid record. 33. Then a POST-QUERY trigger is fired. If it is not fired successfully, then the record, which is marked as a valid record is removed from the block. 34. If there is any change in the record, then the Form Builder validates it. 35. Continue with the same process again from the step 3 to process the remaining records in this query block.There is a default SELECT statement linked with every base table.A form executes this SELECT statement when a query is made against the basetable block. For every item in the block, the default query returns a value fromthe database column. By default, the query is unrestricted, and selects all therows from the base table.The ORDER BY clause for a block SELECT statement can be specified by settingthe Order By block property. If an ORDER BY statement is specified in the QueryWHERE dialog box, then it overrides the blocks default ORDER BY clause.The WHERE clause for a block SELECT statement can be specified by setting theWhere Clause property in the Property Palette of the block. This WHERE clause isapplied to every query issued from the block. With the default SELECT statement,the Where and Order By block properties allow you to restrict and order therecords returned to a base table block.At runtime you can modify the WHERE and ORDER BY clauses programmaticallyby executing the SET_BLOCK_PROPERTY built-in procedure.The SELECT query statement issued during query processing is: SELECT Base_Column, INTO : Base_Item, FROM Base_Table WHERE Default_Where_Clause AND (Query_Where_Condition) ORDER BY Default_Order_By_Clause | Query_Where_Order_By (This | vertical bar indicates that either of the two can be present).Confidential © SQL Star International Ltd. 205
  • 209. NOTE A base table block is a block that is related with a specific database table or view. An item, which is directly related to a base table column, is a base table item. Transactional Triggers for Overriding Query ProcessingThere are certain transactional triggers that are used to replace default queryprocessing.Query Array ProcessingForm Builder processes one record at a time where as with array processing,group of records can be processed at one time to increase the performance byreducing the network traffic. Fired When Built-ins Trigger ON-CLOSE A query is closed. ON-COUNT A default count query processing is COUNT_QUERY executed to determine the rows that match the query condition. ON-SELECT A SELECT statement is issued by the SELECT_RECORDS Form Builder ON-FETCH A query is first opened. ON-FETCH FETCH_RECORDS trigger fires immediately after the ON- SELECT trigger fires. That is, after the first records are fetched into the block. PRE-SELECT The Form Builder has built the SELECT statement but is not yet issued. POST-SELECT Form Builder has built and issued the SELECT statement but has not retrieved the records.Enable Array ProcessingTo enable array processing for queries:Confidential © SQL Star International Ltd. 206
  • 210. • Set preferences: Select the Tools menu and select the Preferences option. Click the Runtime Tab. Select the Array Processing check box. • Set properties: Select the Data Block node in the Object Navigator. Double click the Data Block icon to display the Property Palette. Under the Records category, set the Query Array Size property to a number that represents the number of records in the array for array processing.Query Array Size Property • This property defines the maximum number of records that should be retrieved by the Form Builder at one time from the database. The response time is fastest when the array size is 1, because only one record at a time is to be fetched and displayed. However, if the array size is set to 20, it means that 20 records will be fetched before any one of them is displayed.Query All Records Property • This property describes whether all records matching the query condition should be retrieved or not. • ‘Yes’: Retrieves all records from the query. • ‘No’: Retrieves only those numbers of records that is specified in the Query Array Size block property.Using Query TriggersQuery triggers are fired just before and after the query is executed in a block.These triggers are fired due to the query process and are usually defined at theblock level or above.These triggers allow an enormous amount of control over the queries both beforethey are created and after their data results have been returned.There are two types of query triggers: • PRE-QUERY trigger • POST-QUERY triggerUsing PRE-QUERY TriggerPRE-QUERY trigger fires when the query is executed or during the count queryprocessing, just before the Form Builder constructs and issues the SELECTstatement. PRE-QUERY trigger is fired before the query is performed. It is definedat the block or form level. PRE-QUERY trigger validates the current querycondition or provides additional query conditions programmatically.PRE-QUERY trigger can be used to:Confidential © SQL Star International Ltd. 207
  • 211. • Check the query conditions, and if the conditions are not fulfilled then the query fails. • Add more conditions to the query for assigning values to the base table items. • For example, place the PRE-QUERY trigger on the Book block in the frmLibTrans that permits queries only if there is a restriction on the cBookID, cBookName or cAuthorName. IF (:BOOK.CBOOKID) ||(:BOOK.CBOOKNAME) ||(:BOOK.CAUTHORNAME) IS NULL THEN MESSAGE (‘query by cbookid or cbookname Or cauthorname’); RAISE FORM_TRIGGER_FAILURE; END IF;Using POST-QUERY TriggerWhen a query is initiated, the POST-QUERY trigger fires each time and the FormBuilder fetches a record into the block. This trigger fires once for each recordplaced on the block list of records. It is defined at the block or form level.POST-QUERY trigger can be used to: • Populate control items or items in other blocks. • Calculate details about the records that are retrieved by a query. • For example to place the POST-QUERY trigger on Transaction block, create two display items diFirstName and diLastName in the Transaction data block of frmLibTrans module and populate them with the first name and last name values retrieved from the Member data block. SELECT MEMBER.CFIRSTNAME, MEMBER.CLASTNAME INTO :TRANSACTION.DIFIRSTNAME, : TRANSACTION.DILASTNAME FROM MEMBER WHERE MEMBER.CMEMBERID =: TRANSACTION.CMEMBERID;Coding Triggers for Enter Query ModeCertain triggers are fired in Normal mode and, also in Enter Query mode.Triggers firing in Enter Query ModeFire in Enter Query Mode property checks that whether a trigger is fired when arelated event occurs in Enter Query mode. The firing of trigger in Enter Querymode is by default set to ‘Yes’ in Fire in Enter Query Mode property. If it is set to‘No’ then the trigger will be fired only in Normal mode.The following types of triggers are valid in Enter Query mode:Confidential © SQL Star International Ltd. 208
  • 212. • KEY_triggers • ON-ERROR • ON-MESSAGE • WHEN-triggers • WHEN-DATABASE-RECORD • WHEN-IMAGE-ACTIVATED • WHEN-NEW-BLOCK-INSTANCE • WHEN-NEW-FORM-INSTANCE • WHEN-CREATE-RECORD • WHEN-REMOVE-RECORD • WHEN-VALIDATE-RECORD • WHEN-VALIDATE-ITEMQuery Information at Run TimeSystem variables and built-ins can be used to get control over the queries thatare given by you.Using System VariablesAt run time query information can be obtained by using: • SYSTEM.MODE: This mode indicates whether the form is in Normal, Enter Query, or Query mode. • NORMAL MODE indicates that the form is currently in normal processing mode. • ENTER QUERY MODE indicates that the form is currently in Enter Query mode. • QUERY MODE indicates that a query is currently being processed. • SYSTEM.LAST_QUERY: This variable indicates the SELECT query statement that the Form Builder uses to populate a block during the forms run time session.Obtaining Query information at Run TimeThere are certain built-ins used for obtaining query information. • GET_BLOCK_PROPERTY: Information is returned about a specific block. The following properties are useful for obtaining query information: DEFAULT_WHERE: The default WHERE clause is returned in effect for the block, as indicated by the current setting of the Where block property. ORDER_BY: The default ORDER BY clause is returned in effect for the block, as indicated by the current setting of the Order By block property.Confidential © SQL Star International Ltd. 209
  • 213. RECORDS_TO_FETCH property returns the number of records Form Builder expects an ON-FETCH trigger to fetch and create as queried records. QUERY_OPTIONS property specifies the query the Form Builder would be doing by default if you had not circumvented default processing. QUERY_HITS property indicates the number of records that are identified by the COUNT_QUERY operation. QUERY_ALLOWED specifies whether the Form Builder should execute a query in the block. • SET_BLOCK_PROPERTY: Sets the specified block properties of a given block. The properties which can be set are: DEFAULT_WHERE Give a note on one_time_Where ORDER_BY QUERY_ALLOWED QUERY_HITS • GET_ITEM_PROPERTY: Property values are returned for the specific item. The following item properties are useful for obtaining query information: QUERYABLE property determines whether the item is to be included in a query against the base table of the owning block. QUERY_LENGTH property specifies the maximum number of characters that the end user can enter in the text item when the form is in enter query mode. CASE_INSENSITIVE_QUERY property determines whether the case- insensitive queries on the text item can be performed or not. QUERY_ONLY property specifies that only queries can be performed. • SET_ITEM_PROPERTY: Sets the specified properties to modify all instances of an item in a block. The properties which can be set are: CASE_INSENSITIVE_QUERY QUERYABLE QUERY_ONLYIdentifying the Current ModeWhen the Fire in Enter Query Mode property is set to ‘Yes’, the trigger is fired inboth the Enter Query and in Normal mode. A trigger performs various functionsdepending upon the mode in which the trigger is fired. To identify in which modethe trigger is fired SYSTEM.MODE system variable is used. A system variablekeeps record of an internal Form Builder state.For example to identify in which mode the trigger is fired consider the followingWHEN-BUTTON-PRESSED trigger for a query button. If the user clicks the buttonin Execute Query mode, then the query is executed, otherwise the form is placedin the Enter Query mode: IF: SYSTEM.MODE = ‘QUERY MODE’ THEN EXECUTE_QUERY;Confidential © SQL Star International Ltd. 210
  • 214. ELSE ENTER_QUERY; END IF;Illegal Built-in RoutinesThe following built-in routines are illegal, meaning that they cannot be called froma trigger when a form is in Enter Query mode: ABORT_FETCH BLOCK_MENU CALL_INPUT CLEAR_BLOCK CLEAR_FORM COMMIT_FORM CREATE_QUERIED_RECORD CREATE_RECORD DELETE_RECORD DOWN DUPLICATE_RECORD FETCH_RECORDS FIRST_RECORD GO_BLOCK GO_RECORD INSERT_RECORD LAST_RECORD LOCK_RECORD LOGON LOGON_SCREEN LOGOUT NEW_FORM NEXT_BLOCK NEXT_RECORD NEXT_SET POST PREVIOUS_BLOCK PREVIOUS_RECORD SCROLL_DOWN SCROLL_UP SELECT_RECORDS UPConfidential © SQL Star International Ltd. 211
  • 215. SummaryIn this chapter, you have learnt that: When we define the Validation Unit form property, the user can also control the extent and frequency of validation in a form. Validation process occurs at item, block, record and form level. Validation occurs when the user navigates out of the validation unit by pressing certain function keys or when a trigger executes certain built-in subprograms. It can be controlled by setting certain properties in the Property Palette. The Validation Unit property determines the scope of validation, which is the maximum amount of data that can be entered in the form before Form Builder starts validation. Validation triggers are fired when Form Builder validates data in an item or record. Form Builder performs validation checks during navigation that occurs due to operator input, programmatic control, or default processing, such as a commit operation. If the user enters an invalid value in the item, while populating other items, a matching row with the corresponding result will not be found and the SELECT statement would raise some exception. The three states for an item validation are new, changed and valid. Form Builder processes one record at a time where as array processing group of records can be processed at one time to increase the performance by reducing the network traffic. Query triggers are fired just before and after the query is executed in a block. The two types of query triggers are PRE-QUERY trigger and POST-QUERY trigger. Fire in Enter Query Mode property checks that whether a trigger is fired when a related event occurs in Enter Query mode. System variables and built-ins can be used to get control over the queries that are given by you. There are certain built-ins used for obtaining query information like the GET_BLOCK_PROPERTY, RECORDS_TO_FETCH property etc. Illegal Built-in Routines cannot be called from a trigger when a form is in Enter Query mode.Confidential © SQL Star International Ltd. 212
  • 216. Lab Exercise1. Ensure that no data is allowed other than the values present in the LOV associated with cbranchid.2. In BRANCHXX module write a trigger such that when the user enters return date less than the issue date into the TRANSACTION table, the field must display the error message that ‘Return date cannot be less than the issue date’.3. Write trigger codes such that the Grade should get selected accordingly to the age entered in the MEMBERS block. Lowerage Upperage Grade 5 13 A 14 20 B 21 50 C 50 100 D4. Create two display items in the TRANSACTION block and name them as firstname and lastname.5. Write a trigger at TRANSACTION block level such that the names of the members executed in the MEMBERS block are to be displayed in the display items according to the current cursor record.6. Write a trigger in BOOKXX at the Book block to query the record by bookid or bookname or authorname.Confidential © SQL Star International Ltd. 213
  • 217. Chapter 12 Navigation Navigation and Navigational Unit Navigation Properties Types of Navigation Using Navigation Triggers Built-in SubprogramsConfidential © SQL Star International Ltd. 214
  • 218. ObjectiveAt the end of this chapter, you will be able to: • Describe navigation and navigational unit • Know about navigation properties • Understand types of navigation • Use navigation triggers • Learn the use of built-in subprogramsConfidential © SQL Star International Ltd. 215
  • 219. Navigation and Navigational UnitNavigation occurs when the user or a trigger moves the input focus from oneobject to another.An object can be navigated to either by the user-using [Tab] key during defaultnavigation, or by executing a navigational built-in procedure.For example, when the user presses [Tab] (default) or executes the EXIT_ITEMbuilt-in, the Form Builder moves the input focus to the next navigable item.Navigational UnitAn invisible internal object that determines the navigational state of a form isknown as a navigational unit. The navigational unit helps keep track of the object,which is currently the focus of a navigational process. The navigational unit couldbe any object occurring in the following hierarchy: Outside the form Inside the form Block Record ItemForm Builder enters and leaves objects during navigation. While navigating, FormBuilder changes the navigational unit as it moves through the object hierarchymentioned above, until it reaches the target item. For instance, while entering anobject, Form Builder changes the navigational unit from the object above in thehierarchy and while leaving an object; Form Builder changes the navigational unitto the object above.The visible external object that determines the object, which is currently thefocus of a navigational process, is a cursor. Until the navigational unit hasbecome the target item, Form Builder will not move the cursor.In case navigation fails, Form Builder attempts to reverse the navigation path bymoving the navigational unit back to its initial location. The cursor, however,continues to remain in its initial location. In case Form Builder is unable to movethe navigational unit back to its initial location, it exits the form.Navigation PropertiesNavigation can be controlled at form, block and item levels by setting thefollowing navigation related properties:o Form: Following properties are applicable at form level: First Navigation Block: Specifies the block that the Form Builder navigates during form startup. This property can also be set programmatically, to specify a different block as the first navigation block. Mouse Navigation Limit: Specifies how far the user can navigate to with the mouse. Mouse Navigation Limit property can be set to the following levels: ‘Form level’ allows the user to navigate to any item in the current form (default setting).Confidential © SQL Star International Ltd. 216
  • 220. ‘Block level’ allows the user to navigate to only those items that are within the current block. ‘Record level’ allows the user to navigate only to those items that are within the current record. ‘Item level’ prevents the user to navigate out of the current item.The following screen shows the default setting of Mouse Navigation Limit property:2. Block: The following properties are applicable at block level: Navigation Style: Specifies how a previous item or next item is processed when the input focus is in the first navigable item or last navigable item in the block. The options to choose from are: Same Record Change Record Change Data Block Next Navigation Data Block: Specifies the block as the next navigation block with respect to the current block. Previous Navigation Data Block: Specifies the block as the previous navigation block with respect to the current block.Confidential © SQL Star International Ltd. 217
  • 221. The following screen shows the setting of Next Navigation Data Block property:3. Item: The following properties are applicable at the item level: Enabled: Specifies whether an end user can use the mouse to manipulate an item. The item gets grayed out when the property is set to ‘No’. Mouse Navigate: Specifies whether the navigation is performed when the user activates the item with a mouse. This property is applied to only mouse driven applications like:Confidential © SQL Star International Ltd. 218
  • 222. 24. Push Button 25. Check Box 26. List Item 27. Radio Button 28. Hierarchical Tree Keyboard Navigable: Specifies whether the user or an application can set the input focus in the item during default navigation. When set to ‘Yes’ for an item, the item is navigable. When set to ‘No’ Form Builder skips the item. Next Navigation Item: Specifies the item as the next navigation item with respect to the current item. Previous Navigation Item: Specifies the item as the previous navigation item with respect to the current item.The following screen shows the setting of Next Navigation Item property:Confidential © SQL Star International Ltd. 219
  • 223. Types of NavigationFollowing are the two types of navigation: External Navigation: This navigation occurs when the user clicks any item due to which a trigger is fired or by using function keys, due to which the focus is moved from one object to another. For instance, in frmLibTrans module, we have the input focus on the Branch block and if the user clicks an item in the Book block, then the focus moves to that block. This is called external navigation. Internal Navigation: To understand internal navigation, consider the navigation process that occurs while you enter a form module. On entering a form module say frmLibTrans, you see the input focus in the first enterable item TranID of the first navigable block Transaction. However, the events that must have occurred for the input focus to enter the first item are not visible to the user. These events are as follows: Entering the form (frmLibTrans) Entering the block (Transaction) Entering the record (the first record) Entering the item (cTranID) This internal navigation is also known as logical navigation. The following diagram illustrates internal navigation: INTERNAL NAVIGATION EXIT ITEM EXIT RECORD Next Record EXIT BLOCK ENTER BLOCK ENTER RECORD ENTER ITEMUsing Navigation TriggersNavigation triggers fire in response to navigational events.For example, when the user clicks a text item in another block, navigation eventsoccur and the input focus is moved from the current item to the target item.Navigation events occur at different levels (Form, Block, Record and Item).Navigational triggers are of two types:Confidential © SQL Star International Ltd. 220
  • 224. Pre- and Post- triggers: These triggers fire as the Form Builder navigates through different levels. These triggers fire in response to navigation initiated by the user. When-New-Object-Instance triggers: These triggers fire at the end of a navigational sequence that places the input focus on a different item. Specifically, these triggers fire just after Form Builder moves the input focus to a different item.Pre-navigation TriggersPre-navigation triggers fire during navigation, that is, just before the entry to theobject specified. Following are the types of Pre-navigation triggers in thesequence in which they fire: PRE-FORM trigger: It fires before the form starts up. This trigger is defined at the form level. This trigger can be fired to perform the following tasks: Assign unique primary key values from sequences. Restrict access to a form. Initialize global variables. For example, to prevent the library clerk from entering any book issue transaction details in the Transaction block before 10:00 a.m. and after 7:00 p.m., write the following code in the PRE-FORM trigger at form level of frmLibTrans module: IF USER= ‘Clerk’ AND TO_CHAR (SYSDATE, ‘HH24’) NOT BETWEEN 10 AND 19 THEN MESSAGE (‘Cannot enter transaction details at this hour.’); RAISE FORM_TRIGGER_FAILURE; END IF; PRE-BLOCK trigger: This fires during navigation from one block to another. This trigger is defined at block or form level. This trigger can be fired to perform the following tasks: Allow or disallow access to a block. Set variable values For example, to prevent a user say Librarian from accessing a particular block say Transaction, the following code could be written in the PRE-BLOCK trigger (at block level) in frmLibTrans module: IF USER= ‘Librarian’ THEN MESSAGE (‘You are denied access to view and manipulate library transaction details’); END IF; PRE-RECORD trigger: It fires during navigation to a different record. This trigger can be defined at block or form level. PRE-TEXT-ITEM trigger: It fires during navigation from one text item to another. This trigger can be defined at the item, block or form level. This trigger can be fired to perform the following tasks:Confidential © SQL Star International Ltd. 221
  • 225. Obtain a value based on other items that are previously entered into the same record. For future references, record the current value of the text item. For example, the following code in PRE-TEXT-ITEM trigger at block level (Member) of frmLib module sets the visual attribute for the current item navigated to as vattLib: SET_ITEM_PROPERTY (:SYSTEM.CURRENT_ITEM, VISUAL_ATTRIBUTE, ‘vattLib’);Post-navigation triggersPost-navigation triggers fire during navigation, that is, just after exiting theobject specified. Following are the types of Post-navigation triggers in thesequence in which they fire. POST-FORM trigger fires when a form exits. Thistrigger is defined at form level. This trigger can be fired to perform the followingtasks: • To erase any global variables no longer required by the form. • To display a message to the user upon form exit. POST-BLOCK trigger: This fires when the focus moves off the current block. This trigger can be defined at block or form level. This trigger can be fired to validate the current record of the block. For example, the following code written in POST_BLOCK trigger (for Transaction block of frmLibTrans module) calculates the average fine and the number of members who have paid fines when users leave the block: (To do so, create two non-database items and label them as ‘Avg Fine’ and ‘Count Fine’ and place them in ControlBlk) SELECT AVG (nFine) INTO :AvgFine FROM Transaction; SELECT COUNT(nFine) INTO :CountFine FROM Transaction; POST-RECORD trigger: This fires whenever the user or the application moves the input focus from one record to another. This trigger can be defined at block or form level. For example, write the same code (written within the POST-TEXT-ITEM trigger) in POST_RECORD trigger to set a visual attribute for an item as the user scrolls down through a set of records. POST-TEXT-ITEM trigger: It fires during the exit from a text item. This trigger can be defined at item, block or form level. This trigger is used to calculate or change item values. For example, when you exit the current item of Member block in frmLib module, its visual attribute should be set to vattLibTrans as follows:Confidential © SQL Star International Ltd. 222
  • 226. SET_ITEM_PROPERTY (:SYSTEM.CURRENT_ITEM, VISUAL_ATTRIBUTE, ‘vattLibTrans’);When-New-Object-Instance triggerWhen-New-Object-Instance triggers fire immediately on navigating to the objectspecified. Following are the types of When-New-Object-Instance triggers: • WHEN-NEW-FORM INSTANCE trigger: This fires when Form Builder navigates to the first navigable item in the first navigable block. In a multiple-form application, this trigger does not fire when focus changes from one form to another. This trigger is defined at form level. For example, write the following code in WHEN-NEW-FORM-INSTANCE trigger in frmLib module that would execute the query immediately when the user enters the runtime window: EXECUTE_QUERY; • WHEN-NEW-BLOCK-INSTANCE trigger: This fires when the input focus moves to an item in a different block. This trigger is defined at the block or form level. For example, write the following code in WHEN-NEW-BLOCK-INSTANCE trigger (for Transaction block in frmLibTrans module) that would prevent DMLs from being performed on a particular block by specified users: IF USER= ‘Librarian’ THEN SET_BLOCK_PROPERTY (‘Transaction’, INSERT_ALLOWED, PROPERTY_FALSE); SET_BLOCK_PROPERTY (‘Transaction’, DELETE_ALLOWED, PROPERTY_FALSE); SET_BLOCK_PROPERTY (‘Transaction’, UPDATE_ALLOWED, PROPERTY_FALSE); END IF; • WHEN-NEW-RECORD-INSTANCE trigger: This fires when the input focus moves to an item in a record that is different than the record that previously had input focus. This trigger can be defined at block or form level. For example, write the following code within WHEN-NEW-RECORD- INSTANCE trigger of Transaction block of frmLibTrans module to set the visual attribute as vattLib if the user navigates to an odd numbered record and visual attribute as vattLibTrans if user navigates to an even numbered record: (To do so, create a non-database text item labeled as ‘Serial No’ in ControlBl) IF :cTranID IS NOT NULL THEN :SNo:=:SYSTEM.CURSOR_RECORD; IF MOD (:SNo, 2) !=0 THENSET_BLOCK_PROPERTY (‘Transaction’, CURRENT_RECORD_ATTRIBUTE,‘vattLib’); ELSEConfidential © SQL Star International Ltd. 223
  • 227. SET_BLOCK_PROPERTY (‘Transaction’, CURRENT_RECORD_ATTRIBUTE,‘vattLibTrans’); END IF; END IF; • WHEN-NEW-ITEM-INSTANCE trigger: This fires when the input focus moves to an item. The trigger is fired when the Form Builder is ready to accept input in an item that is different than the item that previously had input focus. This trigger is defined at item, block or form level. This trigger can be fired to perform the following tasks: Perform an action whenever an item gets input focus. Call restricted (navigational) built-ins.Navigation TrapWhen the Pre- and Post- navigation triggers fail, the internal cursor attempts toreturn to the current item (SYSTEM.CURSOR_ITEM).Navigation trap occurs when a Pre-navigation trigger fails and attempts to returnthe logical cursor to its initial item. However, if the initial item has a Pre-Text-Item trigger that also fails, then the cursor has nowhere to go, and a fatal erroroccurs and the form exits.Built-in Subprograms There are certain built-ins that are used to initiate navigation programmatically. They are: • GO_ITEM built-in navigates to an indicated item. The syntax is: GO_ITEM (item_id ITEM); GO_ITEM (item_name VARCHAR2); Where, item_id: specifies the ID assigned to the item when you create it. item_name: specifies the name of the item. • GO_RECORD built-in navigates to the record with the specific record number. The syntax is: GO_RECORD (record_number NUMBER); Where, record_number: specifies any value that PL/SQL can evaluate to a number. • GO_BLOCK built-in navigates to an indicated block. The syntax is: GO_BLOCK (block_name VARCHAR2); Where,Confidential © SQL Star International Ltd. 224
  • 228. block_name: specifies the name of the block. • GO_FORM built-in navigates from the current form to the indicated target form. The syntax is: GO_FORM (form_id FORMMODULE); GO_FORM (form_name VARCHAR2); Where, form_id: specifies the ID assigned to the form when it is instantiated at runtime. form_name: specifies the name of the target form. • NEXT_ITEM built-in navigates to the next higher sequence number with respect to the current item. If there is no such item, then the NEXT_ITEM navigates to the first item in the same record. The syntax is: NEXT_ITEM; • NEXT_RECORD built-in navigates to the first enabled navigable item in the record with the next higher sequence number with respect to the current record. The syntax is: NEXT_RECORD; • NEXT_BLOCK built-in navigates to the first navigable item in the next enterable block in the navigation sequence. The syntax is: NEXT_BLOCK; • NEXT_KEY built-in navigates to the enabled navigable primary key item with the next higher sequence number with respect to the current item. The syntax is: NEXT_KEY; • NEXT_SET built-in retrieves another set of records from the database and navigates to the first record. The syntax is: NEXT_SET; • UP built-in navigates to the instance of the current item in the previous record. The syntax is: UP; • DOWN built-in navigates to the instance of the current item in the next record. The syntax is:Confidential © SQL Star International Ltd. 225
  • 229. DOWN • PREVIOUS_ITEM built-in navigates to the navigable item with the next lower sequence number with respect to the current item. The syntax is: PREVIOUS_ITEM; • PREVIOUS_RECORD built-in navigates to the first enabled navigable item in the record with the next lower sequence number with respect to the current record. The syntax is: PREVIOUS_RECORD; • PREVIOUS_BLOCK built-in navigates to the first navigable item in the previous enterable block in the navigation sequence. The syntax is: PREVIOUS_BLOCK; • SCROLL_DOWN built-in scrolls the current block list of records so that previously hidden records with higher sequence numbers are displayed. The syntax is: SCROLL_DOWN; • SCROLL_UP built-in scrolls the current block list of records so that previously hidden records with lower sequence numbers are displayed. The syntax is: SCROLL_UP;Confidential © SQL Star International Ltd. 226
  • 230. SummaryIn this chapter you have learnt that: Navigation occurs when the user or a trigger moves the input focus from one object to another. You came to know about its properties along with types of Navigation. You can navigate an object to either by the user-using [Tab] key during default navigation, or by executing a navigational built-in procedure. Navigation can be controlled at form, block and item levels by setting the following navigation related properties. First Navigation Block specifies the block that the Form Builder navigates at form startup and Mouse Navigation Limit specifies how far the user can navigate to with the mouse. There are the two types of navigation called the External Navigation and Internal Navigation. Navigation triggers fire in response to navigational events. They are of two types: Pre- and Post- triggers and When-New-Object-Instance triggers. There are certain built-ins that are used to initiate navigation programmatically like GO_ITEM, GO_RECORD and GO_BLOCK etc.Confidential © SQL Star International Ltd. 227
  • 231. Lab ExerciseIn BRANCHXX form module:1. Dynamically set the navigation of the form such that if BRANCH block is the default block, then change the navigation to TRANSACTION and revert back the changes.2. Assign functionality to the form such that except Scott if any other user logs in, he should not be able to manipulate the data.3. Create two visual attribute, name them as CURRENT_RECORD and VATTLIB. o Set the following properties for CURRENT_RECORD: Fore ground color: Black Back ground color: gray16 Fill Pattern: Transparent Font name: verdana Font size: 10 o Set the following properties for VATTLIB: Fore ground color: gray92 Back ground color: r75g75b100 Font name: courier new Font size: 10 Write functionality such that VATTLIB visual attribute is applicable for even number of record and CURRENT_RECORD visual attribute is applicable for odd number of record.4. Write a trigger such that the hierarchical tree item is populated that we have created in the previous chapters.5. Write functionality for cmemberid column such that when current cursor position is in the cmemberid, the corresponding member image should be displayed. ( gather some images and give them the memberid as names)6. Prevent the library clerk from entering any book issue transaction details in the Transaction block before 9:00 a.m. and after 6:00 p.m.Confidential © SQL Star International Ltd. 228
  • 232. Chapter 13 Key and Mouse Event Triggers Introduction to Key Triggers Redefining Function Keys Types of Key Triggers Mouse-Event Key Triggers Associating Function Keys with Interface Controls Mouse Event TriggersConfidential © SQL Star International Ltd. 229
  • 233. ObjectiveAt the end of this chapter, you will be able to: Describe key triggers Redefine function keys Know various types of key triggers Define mouse-event key triggers Associating function keys with interface controls Understand mouse event triggersConfidential © SQL Star International Ltd. 230
  • 234. Introduction to Key TriggersForm applications being built are all currently menu driven. However, the actionsperformed by the function keys cannot be overlooked.The functionality in most of the function keys is already predefined. However,Form Builder enables developers to reprogram that functionality so that theyperform actions related to the application. This is made possible by creating keytriggers.Redefining Function KeysA key trigger is a subprogram that gets executed on the occurrence of a certainevent, such as the pressing of a function key for which the key trigger has beendefined.Key triggers resemble ON-triggers. This is because; defining key triggers onfunction keys cause their default functionality to be replaced with the PL/SQL textof the trigger.Characteristics of Key TriggersThe characteristics of key triggers are as follows: Key triggers cannot be used to redefine function keys that are managed by the terminal or Window Interface Manager (instead of Forms). Example of such function keys is Clear Item, Left, Right, and Toggle Insert/ Replace. Key triggers can be defined at all the three levels: form, block, and item level. Key triggers can include SELECT statements and built-in functions (both restricted and unrestricted). Key triggers can fire in Enter Query mode. Key triggers can be used to disable the functionality of the key.Types of Key TriggersKey triggers can be classified into the following three types: Function key triggers Key-Fn triggers KEY-OTHERS triggerFunction Key TriggersIf a function key is not redefined, its default functionality is performed by a built-in function associated with it, on pressing the key. The default functionalityhowever, can be overridden by associating a trigger with the existing functionkey.The triggers available for the default function key assignments are known asfunction key triggers.The default function key assignments are as follows:Confidential © SQL Star International Ltd. 231
  • 235. Function Key Help [F1] Display Error [Shift +F1] Show Keys [Control+F1] Count Matching [Shift+F2] Records Duplicate Field/Item [F3] Next Primary Key [Shift+F3] Duplicate Record [F4] Clear Record [Shift+F4] Block Menu [F5] Clear Block [Shift+F5] New Record [F6] Delete Record [Shift+F6] Enter Query [F7] Clear Form [Shift+F7] Execute Query [F8] Print [Shift+F8] List Of Values [F9] Accept [F10] Cancel [Esc] Clear Field/Item F5 Delete Backward [Del] or [Backspace] Down [Control+L] or [Down] Edit [Control+E] Exit F4 Left [Left] Next Block [Shift+Pagedown] [Down] Next Field/Item [Tab] or [Control+Tab] Next Set of Records Shift+F8 Previous Block [Shift+Page Up] Previous Record [Up] Previous Field/Item [Shift+Tab] or [Shift+Ctrl+Tab] Return [Enter] Scroll Down [Page Down] Scroll Up [Page Up] Show Keys [Ctrl+F1] Up [Up]The above function keys are displayed as follows at runtime on pressing[Ctrl+F1]:Confidential © SQL Star International Ltd. 232
  • 236. The built-in functions and function key triggers associated with the abovementioned function keys are: Function keys Built-in Functions Function Key Triggers Accept COMMIT_FORM KEY-COMMIT Enter Query ENTER_QUERY KEY-ENTQRY Execute Query EXECUTE_QUERY KEY-EXEQRY Block Menu BLOCK_MENU KEY-MENU Clear Block CLEAR_BLOCK KEY-CLRBLK Next Block NEXT_BLOCK KEY-NXTBLK Previous Block PREVIOUS_BLOCK KEY-PRVBLK Clear Form CLEAR_FORM KEY-CLRFRM Clear Record CLEAR_RECORD KEY-CLRREC Insert Record CREATE_RECORD KEY-CREREC Delete Record DELETE_RECORD KEY-DELREC DUPLICATE_RECORD KEY-DUPRECConfidential © SQL Star International Ltd. 233
  • 237. Function keys Built-in Functions Function Key Triggers Duplicate Record NEXT_RECORD KEY-NXTREC Next Set Of NEXT_SET KEY-NXTSET Records Previous Record PREVIOUS_RECORD KEY-PRVREC Duplicate Item DUPLICATE_ITEM KEY-DUP-ITEM Next Item NEXT_ITEM KEY-NEXT-ITEM Previous Item PREVIOUS_ITEM KEY-PREV-ITEM Scroll Down SCROLL_DOWN KEY-SCRDOWN Scroll Up SCROLL_UP KEY-SCRUP Down DOWN KEY-DOWN Up UP KEY-UP List of Values LIST_VALUES KEY-LISTVAL Edit EDIT KEY-EDIT Print PRINT KEY-PRINT Exit EXIT_FORM KEY-EXIT Help HELP KEY-HELPWrite a KEY-EXIT trigger at form level in frmLib module that will display the alertalExit showing the message ‘DO YOU WANT TO CLOSE THIS FORM?’ SET_ALERT_PROPERTY (alExit, ALERT_MESSAGE_TEXT,DO YOU WANT TO CLOSE THIS FORM?); IF SHOW_ALERT (alExit)=ALERT_BUTTON1 THEN EXIT_FORM; END IF;The alert message is displayed as follows at runtime when the user tries to closea form:Confidential © SQL Star International Ltd. 234
  • 238. A form level KEY-EXEQRY trigger execute queries sorted according to the librarymember’s ages is written as follows:Key-Fn TriggersThe triggers defined to supplement or change the functionality associated withthe logical runtime keys (F0 through F9) are known as Key-Fn triggers.Confidential © SQL Star International Ltd. 235
  • 239. Before Key-Fn triggers are defined, the database administrator must map thelogical keys to physical keys or key sequences. These triggers fire when thephysical key or key sequence is pressed.Key-Others TriggerThe trigger used to disable function keys that are not relevant to your applicationis known as KEY-OTHERS trigger. It can be associated with any key that can havekey triggers associated with them, but whose functionality is not currentlyreprogrammed by any function key trigger.Mouse-Event Key TriggersThe function key triggers, whose default functionality can be directly achievedwith the mouse, are called mouse-event key triggers.Mouse-event key triggers: KEY-NEXT-ITEM KEY-PREV-ITEM KEY-NXTREC KEY-PRVREC KEY-UP KEY-DOWN KEY-SCRUP KEY-SCRDOWN KEY-NXTBLK KEY-PRVBLKKEY-NEXT-ITEM (or KEY-PREV-ITEM) trigger is a mouse-event key triggerbecause its functionality can be achieved directly by clicking the item you want tonavigate. In such a case KEY-NEXT-ITEM trigger will not fire.However, KEY-CREREC trigger is not a mouse-event key trigger. This is because arecord cannot be inserted simply by clicking the mouse. The mouse can achievethe creation of a record only if a trigger defined to create records fires due to theaction of the mouse.Key Trigger PropertiesThe two Property Palette properties that are applicable only to Key triggers are:Confidential © SQL Star International Ltd. 236
  • 240. Property Name Description Display in Keyboard Determines whether the description of a Key Help trigger is to be displayed in the run-time Keys window. Keyboard help Text Specifies the text that is to appear in the run- time Keys window if the Display in keyboard Help property is set to ‘Yes’.The properties are set in the Property Palette as follows:Confidential © SQL Star International Ltd. 237
  • 241. NOTE Platform specific resource files are available for key mapping. For Microsoft Windows platform, the key definition file is FRMUSW.RES. Oracle Terminal should be used to edit Client Server resource file. For Web application, the key definition file is FRMWEB.RES. This Java resource file can be edited with any suitable operating system editor. When the properties are set, the Keys window is displayed at runtime as shown below:Confidential © SQL Star International Ltd. 238
  • 242. Key triggers are commonly used to: • Disable and enable function keys • Replace the default functionality of function keys • Disable a set of function keys using KEY-OTHERS trigger • Perform multiple actions based on a single key stroke NOTE Among the capabilities mentioned above, disabling default function and performing multiple actions cannot be duplicated by a menu command.Invoke an LOV using KEY-LISTVAL trigger.For example, write a KEY-LISTVAL trigger to invoke lvBranch LOV on pressingEdit->Display List (without having to be in the Enter Query mode). DECLARE X BOOLEAN; BEGIN X: =SHOW_LOV (‘LVBRANCH’); END; Check if child records exist before deleting a parent record using KEY- DELREC trigger Prevent primary key value duplication using KEY-DUPREC trigger Change toolbar button behavior when in Enter Query mode using KEY- ENTQRY as follows:Key triggers should not be used to: Carry out validation Modify navigation Perform data manipulationLimitations of Key triggers are: Key-Fn triggers are ignored in Edit mode. KEY-OTHERS trigger is ignored when users are responding to form runtime prompt or viewing a list of values.Confidential © SQL Star International Ltd. 239
  • 243. Associating Function Keys with Interface ControlsSame functionality can be activated in either of the following ways: Pressing a function key Clicking a button Selecting a menu item Directly manipulating with the mouseFor example, you can exit a form in one of the following ways: Pressing [ctrl+q] Clicking the Exit icon Selecting Exit menu item from Action menu Clicking directly with the mouse.In such a case, where the same functionality can be achieved in various ways,you can specify the PL/SQL code to be executed only once. This is made possibleusing the DO_KEY built-in function.DO_KEY built-in function executes the key trigger corresponding to the built-insubprogram specified as its parameter. If no such key trigger exists then thespecified built-in subprogram is executed. The syntax to use the DO_KEY built-infunction is:DO_KEY (<Built-in_name>);For example, you can exit a form by selecting a menu item for exiting or clickinga button defined for exiting a form. The functionality for either is set by:Defining a KEY-EXIT trigger36. Using DO_KEY in: The menu item code The WHEN-BUTTON-PRESSED trigger as DO_KEY(‘EXIT_FORM’);Since the same functionality is performed by different interfaces, they shouldhave the same display names: In the Keys window for function keys In the menu option for the menu bar On the buttonMouse Event TriggersIn Form Builder everything that a user does with the mouse in an application,constitutes an event. These events are known as mouse events, and can causespecific event triggers to fire.Mouse EventsMouse events can be classified into the following two types: Mouse movement events, which comprise:Confidential © SQL Star International Ltd. 240
  • 244. 9) Entering an item or canvas 10) Exiting from an item or canvas 11) General mouse movement Mouse button action events, which comprises Click Double click Up DownMouse Movement TriggersThe three mouse event triggers that fire in response to mouse movements are: Trigger Fires in Response to WHEN-MOUSE-ENTER Moving the mouse into an item or canvas WHEN-MOUSE-LEAVE Moving the mouse out of an item or canvas WHEN-MOUSE-MOVE Moving the mouse within an item or canvasThe following diagram depicts the three mouse movement triggers: Button When-Mouse-Enter Button When-Mouse-Leave When-Mouse-MoveMouse movement triggers can be defined at: The form level, where they are active in the form The block level, where they are active in any item in the block The item level, where they are active only within that itemMouse Position System VariablesThe system variables used to track the various mouse movements are:Confidential © SQL Star International Ltd. 241
  • 245. System Variables Returns SYSTEM.MOUSE_FORM Name of the form module the mouse is currently in SYSTEM.MOUSE_CANVAS Name of the canvas the mouse is currently in SYSTEM.MOUSE_ITEM Name of the item the mouse is currently in SYSTEM.MOUSE_RECORD The record number the mouse is currently in SYSTEM.MOUSE_RECORD_OFFSET The record number the mouse is currently in, relative to the first visible record SYSTEM.MOUSE_X_POS The X coordinate of the mouse’s current position on canvas or within item SYSTEM.MOUSE_Y_POS The Y coordinate of the mouse’s current position on canvas or within item NOTE Mouse movement triggers do not fire when users enter the canvas using menu commands. Use mouse movement triggers sparingly in client server applications because they have the potential to fire frequently. These triggers are disabled in Web-deployed forms. MASTER trigger.The following diagram depicts the various mouse position system variables:Confidential © SQL Star International Ltd. 242
  • 246. In order to obtain the exact position of the mouse within forms application, useWHEN-MOUSE-MOVE in association with SYSTEM.MOUSE_X_POS andSYSTEM.MOUSE_Y_POS.To do so, write the following WHEN-MOUSE-MOVE trigger at form level topopulate the two display items namely dsXPos and dsYPos in control blockControlBlk of frmLib module with the X and Y position values: : dsXPos:=:SYSTEM.MOUSE_X_POS; : dsYPos:=:SYSTEM.MOUSE_Y_POS;To understand the usage of WHEN-MOUSE-ENTER and WHEN-MOUSE-LEAVE,write a WHEN-MOUSE-ENTER trigger that would change the button label ofpbOut in ControlBlk of frmLib module to ‘In’ and write a WHEN-MOUSE-LEAVEtrigger to change its label back to ‘Out’ as follows at item level:WHEN-MOUSE-ENTER trigger SET_ITEM_PROPERTY (‘pbOut’, LABEL, ‘In’);WHEN-MOUSE-LEAVE trigger SET_ITEM_PROPERTY (‘pbOut’, LABEL, ‘Out’);Confidential © SQL Star International Ltd. 243
  • 247. NOTE The Mouse-Event triggers can be used to provide context sensitive help to the end usersMouse Button Action TriggersThe four-mouse event triggers that fire in response to mouse button presses are: Trigger Fires in Response to WHEN-MOUSE-DOWN The mouse button being pressed down while the mouse is pointing to an item or a canvas WHEN-MOUSE-UP The mouse button being released while the mouse is pointing to an item or a canvas WHEN-MOUSE-CLICK The user clicking the mouse within an item or a canvas WHEN-MOUSE-DOUBLECLICK The user double clicking the mouse within an item or a canvas NOTE Mouse button action triggers can be defined at the form, block, and item level. For click and double click mouse button actions to work, the mouse must be on the item or the canvas.Confidential © SQL Star International Ltd. 244
  • 248. When users click or double click an item or canvas, they cause triggers thatprecede WHEN-MOUSE-CLICK and WHEN-MOUSE-DOUBLECLICK to fire in thefollowing sequence: 1. WHEN-MOUSE-DOWN 2. WHEN-MOUSE-UP 3. WHEN-MOUSE-CLICK 4. WHEN-MOUSE-UP 5. WHEN-MOUSE-DOUBLECLICKThe following WHEN-MOUSE-DOUBLECLICK trigger invokes lvBranch LOV ondouble clicking cBranchID text item in the MEMBER data block: DECLARE X BOOLEAN; BEGIN X: = Show_Lov (lvBranch); END; TIP In a Web-deployed form, when a mouse button action is initiated, the Java user interface refers to the Forms Server to identify its corresponding mouse button trigger. In case the relevant mouse button trigger is not defined, the user interface generates the required event if at least one mouse button trigger has been defined in the form. Therefore, mouse button triggers should be used sparingly.Mouse Button System VariablesThe system variables used to track which mouse button was pressed and whichspecial key was used are: System Variables ReturnsConfidential © SQL Star International Ltd. 245
  • 249. System Variables Returns SYSTEM.MOUSE_BUTTON_PRESSED Number representing the mouse button that was pressed; (1-3), where 1 represents the left mouse button SYSTEM.MOUSE_BUTTON_MODIFIERS The special key that was used to modify the usual mouse button action, such as [Shift+Caps Lock +], [Ctrl+], [Alt+Command+], [Super+], and [Hyper+].The mouse cursor style can be changed dynamically using the built-in procedureSET_APPLICATION_PROPERTY as follows:SET_APPLICATION_PROPERTY (CURSOR_STYLE, ‘value’);Where, the valid cursor style values are: ‘Default’ symbol ‘Busy’symbol ‘Crosshair’symbol ‘Help’symbol ‘Insertion’symbolWHEN-MOUSE-DOWN and WHEN-MOUSE-UP triggers could be used in associationwith SET_APPLICATION_PROPERTY built-in procedure to change the cursor styleat runtime.The following PL/SQL Editor screen shows the code written in WHEN-MOUSE-DOWN trigger:Confidential © SQL Star International Ltd. 246
  • 250. Similarly, WHEN-MOUSE-UP trigger can be written to bring the cursor style backto ‘Default’ as follows:SET_APPLICATION_PROPERTY (CURSOR_STYLE,DEFAULT);Confidential © SQL Star International Ltd. 247
  • 251. SummaryIn this chapter, you have learnt that: • A key trigger is a subprogram that gets executed on the occurrence of a certain event, such as the pressing of a function key. • Key triggers cannot be used to redefine function keys that are managed by the terminal or Window Interface Manager. • Key triggers can be classified into Function key triggers, Key-Fn triggers and KEY-OTHERS trigger. • KEY-NEXT-ITEM (or KEY-PREV-ITEM) trigger is a mouse-event key trigger because its functionality can be achieved directly by clicking the item you want to navigate. • Key triggers are commonly used to disable and enable function keys, replace the default functionality of function keys etc. • Key triggers should not be used to carry out or modify validation etc. • Mouse movement events, Mouse button action events are two classifications of mouse events. • To obtain the exact position of the mouse within forms application, use WHEN-MOUSE-MOVE in association with SYSTEM.MOUSE_X_POS and SYSTEM.MOUSE_Y_POS. • WHEN-MOUSE-DOWN and WHEN-MOUSE-UP triggers could be used in association with SET_APPLICATION_PROPERTY built-in procedure to change the cursor style at runtime.Confidential © SQL Star International Ltd. 248
  • 252. Lab Exercise 1. The cursor style should get changed when it is placed on the execute button in BRANCHXX and to cursor shape dumble when the execute button is clicked. 2. Write a trigger to invoke an LOV dynamically for cmemberid and nage columns such that the same LOV is used to populate the list of values but the values populated for the cmemberid should vary from nage according to the queries specified. Ex: List of values for cmemberid should contain all the values of the table. List of values for nage should contain the age values between 35 and 70. 3. Write a trigger at form level to close the form. Modify the existing code to achieve the task. Hint: Use a key trigger and built-in responsible to simplify this code.Confidential © SQL Star International Ltd. 249
  • 253. Chapter 14 Transaction Triggers Control Transaction Processing Commit Triggers Obtaining Cursor Information in PL/SQL Life of an Update Commit Sequence of Events Keeping an Audit Trail Running against a non-oracle database Transactional Triggers Array DML Getting and Setting the Commit Status Using Built-in SubprogramsConfidential © SQL Star International Ltd. 250
  • 254. ObjectiveAt the end of this chapter, you will be able to: Control Transaction Processing Understand about commit triggers Know to obtain cursor information in PL/SQL Learn about the life of an update Commit sequence of events Learn to keep an audit trail Running against a non-oracle database Know what are Transactional triggers Work on array DML Get and set the commit status Use built-in subprogramsConfidential © SQL Star International Ltd. 251
  • 255. Control Transaction ProcessingWhen you save changes made in the form, a process involving events in thecurrent database transactions take place. This process includes: Applying the changes to the base tables. This is the default Form Builder transaction processing. Firing transactional triggers to perform additional actions in the saving process as defined by the developer.When both the processes successfully end, Form Builder commits the transactionthereby making the changes permanent.The transaction process occurs as a result of either: Clicking Save Calling of COMMIT_FORM built-in procedure within a trigger code.In both the above-mentioned cases, the transaction processing involves twostages: Post: Writes changes to the database Commit: This makes the changes permanent in the database. In default processing, if an error occurs or if the transactional trigger fails, then the Form Builder rolls back the applied changes to a savepoint. When all of the forms in an application have the Savepoint Mode property. ‘On’ (the default), the Form Builder issues a savepoint each time a form is loaded into memory at form startup. Savepoint Mode property specifies whether Form Builder should issue save points during a session. This property is primarily for those applications that run against non-Oracle data sources.Commit TriggersDuring the normal flow of commit processing the commit triggers are fired.Following are the types of commit triggers:PRE-COMMIT trigger: This trigger is fired before Form Builder starts processingthe records for change. This trigger is fired after Form Builder determines thatthere are inserts, updates, or deletes in the form. This trigger is defined at formlevel and is fired only once. This trigger can be fired to perform an action likesetting up special locking requirements, at any time the database commit isoccurring. For example, to prevent any user from adding, deleting, or modifyingrecords in frmLibTrans after or before library hours, write the following code: IF TO_CHAR (SYSDATE,HH24) NOT BETWEEN 10 AND 19 THEN MESSAGE (You are not permitted to add, delete, or update any records in this form); END IF; PRE-DELETE trigger: This trigger is fired before a row is deleted. It fires once for each record that is marked for delete. This trigger can be defined at block or form level. This trigger can be defined to perform the following tasks:Confidential © SQL Star International Ltd. 252
  • 256. Delete the detail record of a master record Checks the record deletion whether if that record is a master record and its corresponding detail record still exists.For example, the following code could be written in the PRE-DELETE trigger ofBranch block in frmLibTrans module so as to disallow the user from deletingthose records of the Branch block that have members: DECLARE vCountMembers NUMBER; BEGIN SELECT COUNT (*) INTO vCountMembers FROM Member WHERE cBranchID=:Branch.cBranchID; IF vCountMembers > 0 THEN MESSAGE (Member’s exist in this Branch ID. Hence, the branch details cannot be deleted); RAISE FORM_TRIGGER_FAILURE; END IF; END; PRE-INSERT trigger: This trigger is fired before a row is inserted. It fires once for each record that is marked for insert. This trigger can be defined at block or form level. This trigger can be defined to perform the following tasks: Change item values. Keep a note of the date when a record is created. For example, to prevent duplicate Member IDs from being inserted, write the following code in PRE-INSERT trigger defined for Member block of frmLib module: DECLARE vMemID CHAR (9); BEGIN SELECT cMemberID INTO vMemID FROM Member WHERE cMemberID=:Member.cMemberID; IF vMemID=:member.cMemberID THEN MESSAGE (Duplicate Member IDs not allowed); RAISE FORM_TRIGGER_FAILURE;Confidential © SQL Star International Ltd. 253
  • 257. END IF; END; PRE-UPDATE trigger: This trigger is fired before a row is updated. It fires once for each record that is marked for update. This trigger can be defined at block or form level. The code written in PRE-INSERT trigger could also be written in PRE-UPDATE trigger. POST-DELETE trigger: This trigger is fired after a row is deleted. It is also defined at block or form level. POST-INSERT trigger: This trigger is fired just after a record is inserted. It is defined at block or form level. POST-UPDATE trigger: This trigger is fired after a row is updated. It fires once for each row that is updated in the database during the commit process. It is defined at block or form level. POST-FORM-COMMIT trigger: This trigger is fired if there are records in the form that have been marked as inserts, updates, or deletes but before the Form Builder has issued the database Commit to finalize the transaction. It is defined at form level. POST-DATABASE-COMMIT trigger: This trigger is fired after the database commit occurs. It is defined at form level.To understand the usage of the above-mentioned post-DML triggers look at thefollowing examples:Use POST-INSERT, POST-UPDATE, and POST-DELETE triggers to determine thenumber of DMLs performed, while exiting a form. To do so, initialize globalvariables in the WHEN-NEW-FORM-INSTANCE trigger of frmLib module asfollows: :GLOBAL.INSERT:=0; :GLOBAL.DELETE:=0; :GLOBAL.UPDATE:=0;At Member block level, write the following codes in POST-INSERT, POST-DELETE,and POST-UPDATE triggers respectively: POST-INSERT :GLOBAL.INSERT:=:GLOBAL.INSERT+1; POST-DELETE :GLOBAL.DELETE:=:GLOBAL.DELETE+1; POST-UPDATE :GLOBAL.UPDATE:=:GLOBAL.UPDATE+1;These global variables could be used as follows in POST-FORMS-COMMIT trigger: MESSAGE (:GLOBAL.INSERT|| ‘records inserted’); MESSAGE (:GLOBAL.DELETE|| ‘records deleted’); MESSAGE (:GLOBAL.UPDATE|| ‘records updated’);Confidential © SQL Star International Ltd. 254
  • 258. Assign Sequence Numbers to RecordsDefault values can be assigned to items to provide unique keys for records. Oneof the methods of assigning unique keys to records is by using PRE-INSERTtrigger, just before their insertion in the base table, by which time, the user hascompleted the record and saved it.Obtaining Cursor Information in PL/SQLWhen DML is performed in commit triggers, the results are required to be tested.PL/SQL has provided certain attributes, to obtain the cursor information. Attribute Values SQL%ROWCOUNT Number indicates the number of rows that have been processed. SQL%FOUND True: Indicates multiple rows are Processed False: Indicates 0 rows are processed SQL%NOTFOUND True: Indicates 0 rows are processed False: Indicates multiple rows are Processed.Life of an UpdateTo explain how and where certain trigger actions can be performed, consider anexample:The address of a Branch is updated in a form. When the user queries the record,following are the events that occur: 37. The user updates the Branch address. 38. The user saves the change, initiating the transaction process. 39. The PRE-INSERT trigger is fired. At this stage the form item value and database column value both are different, as the base table has not been updated. 40. Form Builder applies the user changes to the database row. Now both the item and column are same. 41. Then the POST-UPDATE trigger is fired. 42. Form Builder issues the database commit, denying the rollback data and releases the locks, making the changes permanent. Then the following message is displayed: “ Transaction is completed…”Delete ValidationThe non-isolated deletion rule is linked to the Master-detail blocks by a relation,which automatically avoids deletion of master records in the form only if thematching detail rows exist.Confidential © SQL Star International Ltd. 255
  • 259. Finally, to make sure that since the master record was marked for deletion in theform, no dependent detail rows have been inserted by another user. NOTE If you select the “Enforce data integrity” check box in the Data Block Wizard, then Forms Builder automatically creates the related triggers to implement constraints.Commit Sequence of EventsFollowing are the events that occur during the commit sequence: Validation of the form Processing of the savepoint Firing of the PRE-COMMIT trigger Validating the blockFor all deleted records of the block, The PRE-DELETE trigger fires The ON-DELETE trigger fires The POST-DELETE trigger firesFor all inserted or updated records of the block,If it is an inserted record: The PRE-INSERT trigger fires Check the record uniqueness The ON-INSERT trigger fires The POST-INSERT trigger firesIf it is an updated record: The PRE-UPDATE trigger fires Check the record uniqueness The ON-UPDATE trigger fires The POST-UPDATE trigger firesFiring of the POST-FORM-COMMIT trigger. If the current operation is committhen, Issue an SQL statement Fire the POST-DATABASE-COMMIT triggerThere are 5 rules that are used for issuing DML statements at commit time foreach database record. The DML statement fires the associated database triggers.Confidential © SQL Star International Ltd. 256
  • 260. Form Builder uses the ROWID construct only when the Key Node Block property is set to ‘Automatic’ (default). If Form Builder inserts a row in the database, it retrieves the ROWID for that row. If the Updated Changed Columns Only block property is set to ‘Yes’ then only the base columns with changed values are included in the update statement. If the Enforce Column Security block property is set to ‘Yes’ then Oracle Forms enforces the update privileges that are defined in the database for the current end user. Keeping an Audit TrailTo record audit information of any changes applied to base tables, we use Post-event transactional triggers. Sometimes, this involves replication inserts orupdates in backup history tables or record statistics every time a DML operationoccurs.If the base table changes are made commit at the end of the transaction, theaudit information will also be committed.ExampleThis Post-Update trigger writes the current record ID to the UPDATE_AUDIT table,along with a time stamp and the user who performed the update. INSERT INTO update_audit (id, timestamp, who_did_it) VALUES (:ORDERS.order_id, SYSDATE, USER);ExampleThis Post-Insert trigger adds to a running total of Inserts for the transaction,which is recorded in the INSERT_TOT global variable. :GLOBAL.insert_tot:= TO_CHAR(TO_NUMBER(:GLOBAL.insert_tot)+1);Running against a non-oracle databaseTwo Ways to Run Against Data Sources Other than Oracle Use Oracle Transparent Gateway products. Write the appropriate set of transactional triggers.Connecting with Open GatewayWhen you connect to a data source other than Oracle with an Open Gatewayproduct, you should be aware of these transactional properties: Cursor mode form module property Savepoint mode form module property Key mode block property Locking mode block propertyThe specific settings depend on the capabilities of the data sourceConfidential © SQL Star International Ltd. 257
  • 261. Transactional TriggersTransactional triggers are related to accessing a data source. Commit triggers area subset of these triggers. They fire in response to a wide variety of events.Following are the six transactional triggers used during Commit Processing:12) ON-CHECK-UNIQUE trigger: This trigger is fired when Form Builder checks that values are unique for primary key. It fires once for each record that has been inserted or updated. This trigger can be defined at block or form level.13) ON-COLUMN-SECURITY trigger: This trigger is fired when Form Builder enforces the column-level security for each block that has the Enforce Column Security block property set ‘On’. It can be defined at block or form level.14) ON-COMMIT trigger: This trigger is fired when Form Builder issues a commit statement to finalize a transaction. It can be defined at form level.15) ON-ROLLBACK trigger: This trigger is fired when Form Builder issues a rollback statement, to roll back a transaction to the last savepoint that was issued. It can be defined at form level.16) ON-SAVEPOINT trigger: This trigger is fired when Form Builder issues a savepoint statement. It can be defined at form level. ON-SEQUENCE-NUMBER trigger: This trigger is fired when Form Builder performs the default processing for generating sequence numbers for default item values. This trigger can be defined at item, block or form level.Following are the six transactional triggers for logging on and logging off: 1. ON-LOGON trigger: This trigger is fired once when Form Builder starts the logon sequence. It is defined at form level. 2. ON-LOGOUT trigger: This trigger is fired when Form Builder starts a logout procedure. It is defined at form level. 3. PRE-LOGON trigger: This trigger is fired just before Form Builder starts a logon procedure to the data source. It is defined at form level. 4. PRE-LOGOUT trigger: This trigger is fired once before Form Builder starts a logout procedure. It is fired at the form level. 5. POST-LOGON Trigger: This trigger fired at the form level. It fires only after any of the following events has occurred: The successful completion of Form Builder default logon processing. The successful execution of the ON-LOGON trigger. 6. POST-LOGOUT trigger: This trigger is defined at the form level. It is fired after any of the following events has occurred: Form Builder successfully logs out of Oracle. The successful execution of the ON-LOGOUT trigger.Array DMLConfidential © SQL Star International Ltd. 258
  • 262. The default forms behavior is to process one record at a time. To alter theprocess of records we have an option in forms builder called Array Processing.You can process bulk of records at a time by enabling array processing. This ismostly used in web applications. This leads to reduction in traffic and increase inperformance. Here, an array containing groups of records are sent to or returnedfrom the server.Forms Builder supports both array fetch processing and array DML processing.For both DML operations and querying, you can specify the array size to optimizeperformance for your needs.Array processing is not supported for blocks based on transactional triggers.The following are the steps to implement Array DML:1) To set preferences: -Select Edit > Preferences. -Click the Runtime tab. -Select the Array Processing check box.2) To set properties: In the Object Navigator, select the Data Blocks node. Double-click the Data Blocks icon to display the Property Palette. Under the Advanced Database category, set the DML Array Size property to a number that represents the number of records in the array for array processing. You can also set this property programmatically.Getting and Setting the Commit StatusIf a record is to be processed in a form, then it is always useful to ensure whetherthat record exists in the database or not, and if it exists then make sure about itsstatus. For this purpose, system variables and built-ins are used.Using System VariablesThe commit status of a record identifies how the record will be processed at thetime of the next commit process.Following are the three system variables that are used to get and set the commitstatus:1. SYSTEM.RECORD_STATUS system variable specifies the status of the current record. The four values of SYSTEM.RECORD_STATUS system variable are: New: Indicates that none of the item in the record has been changed. Insert: Indicates that one or more of the items in the record have been changed. Changed: Indicates that one or more base table items in a database record have been changed. Query: Indicates that the record corresponds to a row in the database.2. SYSTEM.BLOCK_STATUS system variable specifies the status of the current data block. The three values of SYSTEM.BLOCK_STATUS system variable are: New: Indicates that the block contains only new records.Confidential © SQL Star International Ltd. 259
  • 263. Changed: Indicates that the block contains at least one changed record. Query: Indicates that the block contains only those records that have been retrieved from the database.3. SYSTEM.FORM_STATUS system variable specifies the status of the current form. The three values of SYSTEM.FORM_STATUS system variable are: New: Indicates that the form contains only new records. Changed: Indicates that the form contains at least one block with a changed record. Query: Indicates that the query is open.Using Built-ins SubprogramsThere are certain built-ins that can also be used to obtain the status of the otherblocks and records. GET_BLOCK_PROPERTY built-in specifies information about a specified block. The syntax is: GET_BLOCK_PROPERTY (block_id Block, property NUMBER); GET_BLOCK_PROPERTY (block_name VARCHAR2, property NUMBER); Where, block_id: is the ID assigned to the block when the Form Builder creates it. block_name: is the name of the block. GET_RECORD_PROPERTY built-in specifies the value of the given property for a given record number in the given block. The syntax is: GET_RECORD_PROPERTY (record_number NUMBER, block_name VARCHAR2, property NUMBER); Where, record_number: is the record in a block for which you want property information. block_name: is the name of the block containing the target record. SET_RECORD_PROPERTY built-in sets the specified record property to the specified value. The syntax is: SET_RECORD_PROPERTY (record_number NUMBER, block_name VARCHAR2,Confidential © SQL Star International Ltd. 260
  • 264. property NUMBER, value NUMBER); Where, record_number: specifies the number of the record whose status you want to set. block_name: specifies the name of the block in which the target record exists. property: specifies to change the record status. value: Use one of the following values: CHANGED_STATUS specifies the record to be marked for update INSERT_STATUS specifies the record to be marked as an insert. NEW_STATUS specifies the record to be treated as a new record.Confidential © SQL Star International Ltd. 261
  • 265. SummaryIn this chapter, you have learnt: • PRE-COMMIT, PRE-INSERT, PRE-UPDATE, POST-DELETE, POST-INSERT, POST-UPDATE, POST-FORM-COMMIT and POST-DATABASE-COMMIT trigger are the types of commit triggers that are fired during the normal flow of commit processing. • During the commit sequence, some of the events that occur are like validation of the form, processing of the savepoint and firing of the PRE- COMMIT trigger etc. • There are two ways to run against data sources other than Oracle. You can use Oracle transparent gateway products or write the appropriate set of transactional triggers. • Transactional triggers are related to accessing a data source and commit triggers are a subset of these triggers. • Array Processing in forms builder is used to alter the process of records and is not supported for blocks based on transactional triggers. • The commit status of a record identifies how the record will be processed at the time of the next commit process. • The three system variables that are used to get and set the commit status are SYSTEM.RECORD_STATUS, SYSTEM.BLOCK_STATUS and SYSTEM.FORM_STATUS. • GET_BLOCK_PROPERTY built-in specifies information about a specified block. • GET_RECORD_PROPERTY built-in specifies the value of the given property for a given record number in the given block. • SET_RECORD_PROPERTY built-in sets the specified record property to the specified value.Confidential © SQL Star International Ltd. 262
  • 266. Lab Exercise 14 1. Write a trigger in BRANCHXX such that if the time is between 10 and 19 hours, the transactions done after these business hours should not be allowed. 2. Write a trigger in BRANCHXX module such that an exception should be raised if a duplicate value is entered into the cmemberid column. 3. Set property such that if master record is deleted an exception should be raised that a detail record exists and master record cannot be dropped. 4. Write a trigger on MEMBER block such that when a duplicate record is getting inserted, this trigger fires.Confidential © SQL Star International Ltd. 263
  • 267. Chapter 15 Flexible Code System Variables for Flexible Coding System Variables to Determine the Form Status Built-in Subprograms for Flexible Coding Using Objects Internal IDs for Flexible Coding Extending the scope of the Object IdsConfidential © SQL Star International Ltd. 264
  • 268. ObjectiveAt the end of this chapter, you will be able to: • Use System Variables for Flexible Coding • Work with System Variables to Determine the Form Status • Learn built-in subprograms for flexible coding • Use objects internal IDs for flexible coding • Know about extending the scope of the object IdsConfidential © SQL Star International Ltd. 265
  • 269. System Variables for Flexible CodingFlexible code is a reusable code. Instead of hard coding we use the systemvariables in the flexible coding. It is easier to maintain and it increases theproductivity.Using System Variables in Flexible CodingSystem variables can be used to provide the current status of the record, theblock and the form. They are also used to get the current input focus location ofthe cursor in the form.The following table shows the system variables for locating the current inputfocus: System variables Function SYSTEM.CURSOR_BLOCK It determines the block that has got the focus. SYSTEM.CURSOR_RECORD It determines the record that has got the focus. SYSTEM.CURSOR_ITEM It determines the item that has got the focus. SYSTEM.CURSOR_VALUE It determines the value of the item with the current input focus.You can use the above system variables in the following way: IF:SYSTEM.CURSOR_BLOCK= ‘Book’ THEN MESSAGE (‘You are in the Book Data Block’); END IF;The code mentioned above will give you the message when you enter the Bookdata block. Similarly you can use the other system variables as mentioned abovein the code to find the status of the form module. There are other systemvariables used for locating the trigger focus. They are: System Variable Function TRIGGER_BLOCK Gets the name of the block that the input focus was in when the trigger initially fired. TRIGGER_RECORD Gets the number of record that Form Builder is processing. TRIGGER_ITEM Gets the name of the item and block that the input focus was in when the trigger initially fired.Confidential © SQL Star International Ltd. 266
  • 270. System Variables to Determine the Form StatusThese variables are used to know the status of the form at run-time and performactions based on the form status. There are three system variables through whichyou can know the form status. SYSTEM.RECORD_STATUS SYSTEM.BLOCK_STATUS SYSTEM.FORM_STATUSThe table below shows you the list of the system variables and theircorresponding values that are used for determining the form status. SYSTEM.RECORD_STATUS Function CHANGED This determines that the record fetched from the database has been updated. INSERT This specifies that the user has entered a value into the base table item of the non-fetched record. NEW This determines that the user has not entered the value into the base table items of the record. QUERY This specifies that the record fetched from the database has not been updated. SYSTEM.BLOCK_STATUS Description CHANGED This determines the block that has at least one record with the status CHANGED and INSERT. NEW This determines the block that has only NEW records. QUERY This determines the block that has only QUERY records. SYSTEM.FORM_STATUS Description CHANGED This determines the form that has at least one record with the status CHANGED and INSERT. NEW This determines the form that has only NEW records. QUERY This determines the form that has only QUERY records.Let us use the frmLib form module to create WHEN-WINDOW-CLOSED trigger toknow whether the user has modified any records or not. If the user modifies, thenthe trigger needs to save the changes to the database. 43. Open the frmLib form module. 44. Create the KEY-EXIT trigger at form level and write the following code in it DECLARE alert_button NUMBER; BEGINConfidential © SQL Star International Ltd. 267
  • 271. IF :SYSTEM.FORM_STATUS = CHANGED THEN COMMIT_FORM; END IF; alert_button:=SHOW_ALERT(alExit); IF alert_button = ALERT_BUTTON1 THEN EXIT_FORM; END IF; END; 45. Before you run the form, create the alExit Alert. Open the Property Palette of the alExit and set the Message and Alert Style properties to ‘Do you want to exit?’ and ‘Caution’ respectively. 46. The screen grab below shows the Property Palette of alExit with the properties Message and Alert Style set. 47. Compile the KEY-EXIT trigger and run the form module. 48. When you try to close the window of the form, the trigger fires and saves the changes to the database if there are any modifications. 49. It also invokes the alExit Alert and prompts you with ‘Do you want to exit?’. If you choose ‘Yes’ button then the form will exit from the forms run time environment.Built-in Subprograms for Flexible CodingThe Form Builder built-in subprograms are used in flexible coding to makeprogramming more dynamic.Confidential © SQL Star International Ltd. 268
  • 272. Using the Built-in Subprograms for Flexible CodingThere are sets of built-ins used to reduce the hard coded values in programming.The most important among them are: • GET_ built-in functions • SET_ built-in proceduresThe GET_ built-in subprograms are used for getting the values from the specifieditem, block or a form at runtime. Following are some of the GET_ built-insubprograms.GET_APPLICATION_PROPERTY subprogram:The GET_APPLICATION_PROPERTY subprogram returns information about thecurrent Form Builder application. The GET_APPLICATION_PROPERTY subprogramis used in following ways: :GLOBAL.username := get_Application_Property(USERNAME); :GLOBAL.password := get_Application_Property(PASSWORD);The above code is used to capture the database username and password of thecurrent user. • GET_BLOCK_PROPERTY subprogram:The GET_BLOCK_PROPERTY subprogram returns information about the specifiedblock.The GET_BLOCK_PROPERTY subprogram can be used in following ways: Message(GET_BLOCK_PROPERTY(‘Book’,FIRST_ITEM));The above code is used to display the name of the first item in the data blockmentioned. Message(GET_BLOCK_PROPERTY(‘Book’,RECORDS_DISPLAYED));The above code is used to display the number of records displayed in the datablock mentioned. • GET_ITEM_PROPERTY built-in subprogram:The GET_ITEM_PROPERTY subprogram returns information about the specifieditem in a block.The GET_ITEM_PROPERTY subprogram can be used in following ways: MESSAGE (GET_ITEM_PROPERTY (: SYSTEM.CURSOR_ITEM, DATATYPE));The above code returns the data type of the item where the cursor is placed.The SET_ built-in subprograms are used to set the specified value to theproperties of specified Item, Block or a Form. The following are some of the SET_built-in subprograms: • SET_ITEM_INSTANCE_PROPERTY built-in subprogram:The SET_ITEM_INSTANCE_PROPERTY built-in subprogram modifies the specifieditem instance in the block by changing the specified item property. TheSET_ITEM_INSTANCE_PROPERTY built-in subprogram can be used in followingway:Confidential © SQL Star International Ltd. 269
  • 273. SET_ITEM_INSTANCE_PROPERTY (: SYSTEM.CURSOR_ITEM, VISUAL_ATTRIBUTE, CURRENT_RECORD, ‘vattFonts’);The above code is used to set the visual attribute vattFonts for the current recordof the current item. • SET_ALERT_PROPERTY built-in subprogram:The built-in is used for changing the properties of the alert at run time. Forexample to change the alert message at runtime write the following lines of codein the WHEN-WINDOW-CLOSED trigger written above: SET_ALERT_PROPERTY (‘alExit’, ALERT_MESSAGE_TEXT,’do you want to exit the form?’);Using Objects Internal IDs for Flexible CodingForm Builder assigns IDs to all the items you create in the form module, which isreferred as object ID. The object ID is an internal value that is never beendisplayed. Use the FIND_ subprogram to get the internal ID of the appropriateobject. The FIND_ subprogram needs the object name as a parameter. The returntypes of the FIND_ subprograms are of specific type for each object, i.e. there aredifferent types for each object.The table below lists some of the FIND_ subprograms along with the object typesthey are related to and the return types they produce.Using the Object IDsTo use the object ID, you have to assign them to variables. You need to declarethe variable of the same type as the object ID. Once an object ID is assigned tothe variable, it can be used to refer the object any time in the trigger with outreferring the object by name.The following example shows you how an object ID is assigned to a variable andcan be used effectively in the trigger.Confidential © SQL Star International Ltd. 270
  • 274. NOTE Use the FIND_ built-in subprogram only when the object is being referred frequently in the same trigger code or PL/SQL program unit. DECLARE al_id Alert; al_button NUMBER; BEGIN al_id := Find_Alert(alExit); IF Id_Null(al_id) THEN Message ( alExit alert does not exist); RAISE Form_Trigger_Failure; ELSE al_button := Show_Alert(al_id); . . . . . . . . . . . . . . . . . . . . . . . . . . . . END;You can also use object IDs to set the properties for specified objects. The codebelow shows you how to set the property of the Alert using its object ID. SET_ALERT_PROPERTY(al_id, ALERT_MESSAGE_TEXT, ’Do you want to exit the Form’);Extending the scope of the Object IdsThe object ID is referenced within the trigger or program unit by means ofPL/SQL variables. However, you can increase the scope of the object IDs byincreasing the scope of the PL/SQL variable. To refer an object ID outside theinitial PL/SQL block, you need to convert the ID to a numeric format using an .idextension for your declared PL/SQL variable, and then assign it to a globalvariable.The following example shows the trigger code assigning the object ID to the localPL/SQL variables initially and then to a global variable. DECLARE al_var Alert; BEGIN al_var:=FIND_ALERT(‘alExit’); :GLOBAL.ALERT:= al_var.id;Confidential © SQL Star International Ltd. 271
  • 275. END;The following example shows the conversion of the global variable back to itsoriginal PL/SQL data type: DECLARE al_var Alert; BEGIN al_var :=TO_NUMBER(:GLOBAL.ALERT); SHOW_ALERT(‘al_var’); END;Using NAME_IN SubprogramUse variables for indirect referencing of items to build more generic and reusablecode. The diagram below shows the direct and indirect referencing of variables. ITEM A Direct Reference VALUE A ITEM B Indirect Reference VALUE A ITEM A VALUE AUsing the NAME_IN Built-in FunctionThe NAME_IN function returns the contents of the indicated variable. Thefollowing statements show the direct and indirect reference of the variables.The code below uses a direct reference to book name. IF :Book.cBookName = ’The Comedy of Errors’ . . . . . . . . . . . . . . . . . . . .The code below uses an indirect reference to Book name. IF NAME_IN(‘Book.cBookName’)= ’The Comedy of Errors’ . . . . . . . . . . . . . . . . . . ..Using the COPY Built-in ProcedureThe COPY built-in procedure copies a value from one item or variable to anotheritem or global variable. The COPY built-in procedure is similar to PL/SQLConfidential © SQL Star International Ltd. 272
  • 276. assignment statement, the only difference is that it is used to copy a value to thevariable or item using indirect referencing.The syntax below shows the direct referring: COPY (‘value’,’Book.cBookName’);The syntax below shows the indirect referring: COPY (‘value1’,:GLOBAL.Book_name);We can use COPY built-in with the NAME_IN built-in to assign the values. Thesyntax below shows you how to assign the value to an item whose name is storedin the global variable: COPY(‘value’, NAME_IN(‘GLOBAL.Book_name’);Confidential © SQL Star International Ltd. 273
  • 277. SummaryIn this chapter, you have learnt that: Flexible code is a reusable code where we use the system variables in the flexible coding which on the other hand increases the productivity. SYSTEM.RECORD_STATUS, SYSTEM.BLOCK_STATUS and SYSTEM.FORM_STATUS are the three system variables through which you can know the form status. GET_ built-in functions and SET_ built-in procedures are the sets of built- ins used to reduce the hard coded values in programming. To use the object ID, you need to declare the variable of the same type as the object ID. To refer an object ID outside the initial PL/SQL block, you need to convert the ID to a numeric format using a .id extension for your declared PL/SQL variable, and then assign it to a global variable. The NAME_IN function returns the contents of the indicated variable. The COPY built-in procedure copies a value from one item or variable to another item or global variable. It is used to copy a value to the variable or item using indirect referencing.Confidential © SQL Star International Ltd. 274
  • 278. Lab Exercise 1. Determine in which record the cursor is currently placed in? 2. Create an alert, which specifies grade should not be other than the specified range of age. 3. Display the name of the user you are currently working in. 4. Write a trigger for Branch block such that when the cursor is placed in an item, the font should zoom and when the cursor is navigated to other item then that item font should zoom, the item which lost focus should get back to its original font size. 5. Write a procedure named p_close_window to capture which window is getting closed. Call this procedure to check which window is closed.Confidential © SQL Star International Ltd. 275
  • 279. Chapter 16 Sharing Objects and Code Property Class Using Object Groups Object Libraries Smart Class PL/SQL LibraryConfidential © SQL Star International Ltd. 276
  • 280. ObjectiveAt the end of this chapter, you will be able to: • Describe the property class • Learn about the object group • Create an object library • Use Smartclass. • Create the PL/SQL LibraryConfidential © SQL Star International Ltd. 277
  • 281. Property ClassWhile developing an application, there is the need for reusing objects and code toimprove: Productivity: Plays a major role in developing a product. By sharing and reusing the frequently used objects and code, you can cut down the development time of the application and increase the productivity. Maintenance: After you develop the application, maintenance is an important factor that needs to be taken care of. Modifications in the shared code can be done easily as it is done in a single place. Modularity: Sharing the code increases the modularity of your applications. Standards: You can create standard reusable code and objects. Once created you can use them in several places. You can create standard code and objects as a starting point for all of your application modules. You can start writing code with little or no modifications. Application Performance: When Forms Services communicates the user interface to the forms Client, it sends meta-data about the items on the form. This meta-data includes values of properties that differ from the default. Once an item is defined, the meta-data about the next item includes only those properties that differ from the previous item. This is referred to as message diffing. Promoting similarities among items by using the methods of object reuse presented in this lesson improves the efficiency of message diffing, thereby decreasing network traffic and increasing performance.Using Property ClassProperty Class is a named object that contains a list of properties. All commonand most frequently used form builder object properties are put into the PropertyClass. It enables you to set the standard properties for several items at a time.This increases the productivity because it eliminates the time spent on setting theidentical properties of each of the objects.Creating a Property ClassWhen you create a Property Class all the properties from every Form module areavailable. The Property Class created can be used in any of the object in thatform module.The Property Class can be created in 2 ways: Using the Create icon in the Object Navigator. 1. Select the Property Class node and click the Create icon. 2. The property class entry will be displayed in the Object Navigator. 3. Double click the Property Class to open the Property Palette. 4. Add the required properties and their values using the Property icon in the Property Palette Using the Create Property Class button in the Property Palette. 1. In the Object Navigator, click the object whose Properties you need to copy into a Property Class.Confidential © SQL Star International Ltd. 278
  • 282. 2. Hold the [Shift] key on the keyboard and select the properties you want to copy. 3. Click the Create Property Class button in the Property palette toolbar. An information alert is displayed with the property class name. The screen grab of which is shown below: 4. Click OK to create the Property Class. Use the Object Navigator to locate the Property Class and change its name.You can use the property class icons to add and delete the properties from theProperty Class property list. The diagram below shows the property class icons: Property Class Add Delete Property Inherit Property Property Class PropertyInheriting a Property ClassOnce the Property Class is created, you can apply properties from the PropertyClass to an object. To apply properties from the Property Class to an object, setthe Subclass Information property of the object.The property that takes the value from the Property Class property list that isassociated with the object is known as an inherited property. An inheritedproperty is displayed with an arrow to the left of the property name. The screengrab below, shows the inherited property and the non-inherited property.Confidential © SQL Star International Ltd. 279
  • 283. The inherited property can be overridden by changing the value associated withit. Such a property is known as a variant property. A variant property is displayedwith a red cross over an arrow. The diagram below shows the variant propertythat is obtained by overriding the inherited property:You can convert a variant property to an inherited property by clicking the inheritproperty icon in the Property Palette. The steps to inherit the properties from a Property Class are:50. In the Object Navigator, double click the object you want to apply the properties from the Property Class. This opens the Property Palette of the object.51. Click the Subclass Information property to invoke the Subclass Information dialog box.52. The diagram below shows you the Subclass Information dialog box:53. Select the Property Class whose properties you want to use from the Subclass Information dialog box. Click OK to inherit the properties of the Property Class to the current object.Using Object GroupsThe Object Group is the logical container for holding the set of Form Builderobjects. Create an Object Group to copy or subclass all related objects to anothermodule. The Object Group is used to bundle the various objects into higher-levelbuilding blocks that can be used again with another application.Creating an Object GroupThe creation of the Object Group includes the following steps: 1. In Object Navigator, click the Object Group node.Confidential © SQL Star International Ltd. 280
  • 284. 2. Click the Create icon. A new Object Group entry is displayed. 3. Rename the new Object Group entry say objgrLib. 4. Click the form module and expand all the nodes. 5. Select the objects you want to include in objgrLib. 6. Drag and drop the selected objects into the Object Group entry. The objects are displayed as the Object Group children. 7. Repeat the steps 5 and 6 for different object types.The objects copied into the object group are not the duplicated, but they arepointers to the source objects.The screen grab below shows the Object Navigator with Object Group objgrLib,which has WHEN-NEW-FORM-INSTANCE trigger in the Object Group-Childrennode.You need to consider the following when working with object groups: When you copy a block into an object group, all the item level triggers, block level triggers, and relations that come under it are also copied. You cannot include one object group in another. Deleting an object from the form module deletes it from the object group.Copying and Subclassing in Object GroupWhen you try to drag and drop objects between modules in the Object Navigatorthe Subclass or Copy alert is displayed.This mechanism is used to reuse the objects in more than one form module.The screen below shows the Subclass or Copy alert:Confidential © SQL Star International Ltd. 281
  • 285. Copying Objects Subclassing ObjectsIf you click the Subclass button of the alert box then all the characteristics areinherited to the target module. Similarly if you click the Copy button of the alertbox, then the exact copy of the objects in the object group are made in the targetmodule.The diagrams below show the difference between the copying and subclassing ofobjects: Add to object Makes exact Makes exact copy of object copy of object Added partConfidential © SQL Star International Ltd. 282
  • 286. Subclassing of ObjectsOnce an object is subclassed you can: Add elements to the object: You can create an exact copy of the object, as with referencing the parent class, and add additional items to the subclassed object. Alter the properties of the object: Subclassing the object creates an exact copy of the parent class. If you change the parent class properties, the changes are reflected in the subclassed object. However the properties that are overridden in the subclassed object will remain overridden. Override the changes made in the parent class: When you change the properties of a parent object, all the objects inherit these properties if they are not already overridden.Object LibrariesObject Library is a collection of common Oracle objects that can be used in anyform where appropriate. Object Libraries store objects like property classes,visual attributes and triggers.The advantages of using the Object Libraries are: They are used to store and distribute standard, reusable objects. They are used to rapidly create applications by dragging and dropping predefined objects onto a form. They are automatically opened when the form referencing the object library is opened in Form Builder so that the reusable objects can be accessible immediately. NOTE An Object Library does not allow creation or modification of its objects.The valid Oracle forms objects that can be placed inside an object library are: Alerts Blocks Canvases Property classes Visual attributes WindowsConfidential © SQL Star International Ltd. 283
  • 287. Creating Object LibraryThe objects included in the Object Library must first be created in the formmodule. Once they are created they can be moved into an Object Library. Tocreate an Object Library for the Library database: 1. Open the form module frmLib. 2. Create a Visual Attribute object named vaErrors. Set their properties as shown below: 3. Select the Object Library node in the Object Navigator, Click the Create icon. A new Object Library with the default name is created, as shown in the following diagram:Confidential © SQL Star International Ltd. 284
  • 288. 4. Expand the Object Library node. A collection of one or more Library Tabs is displayed. The objects of different types can be organized and placed in different Library Tabs. 5. Double click the Library Tabs node to create a new Library Tab in the Object Library. A new tab with the default name is created as shown in the diagram below: 6. Set the Name property and the Label property to of the Tab Page to vattrLib and vattr respectively. The Property Palette for the Library Tab is shown in the diagram below:Confidential © SQL Star International Ltd. 285
  • 289. 1. Open the tab to place an object in it by selecting Tools Object Library menu option to open the Library Tab. The opened Library Tab is shown in diagram the following diagram: 2. Select the Visual Attribute object in the form module and drag and drop it in the vattr tab. The vattr tab with the added object is shown in the following diagram:Confidential © SQL Star International Ltd. 286
  • 290. 3. Save the object library to hard disk with .olb (Object Library Binary) extension.Smart ClassA smart class is a member of the Object Library. Smart class is used to subclassexisting objects in a form using the SmartClass option from the pop up menu,which gets invoked when you right click the object. If you have certain frequentlyused objects in your forms such as buttons, data items, and alerts, then you canmake them as smart classes. Once the object is made a smart class, you canreuse the object. For example, if a button B1 in form module FM1 is made into asmart class, then when button B2 of form module FM2 is assigned to the smartclass B1 gets all the properties including the label of button B1.To create a smart class you need to: 1. Expand the Object Library node in the Object Navigator. 2. Open the Library tab by double clicking it. 3. Select the object from the list of objects in the library tab. 4. Choose the Object SmartClass form the menu to make the object a smart class.How to Invoke a Smart Class?A smart class can be invoked by: 1. Selecting the object in the Layout Editor or Object Navigator. 2. Invoking the pop-up menu and selecting SmartClasses option. A list of all SmartClasses that are there in the current Object Library will be displayed. When you select a class for the object, it becomes the parent class of the object. You can see its details in the Subclass Information dialog box, just like any other subclassed object.Confidential © SQL Star International Ltd. 287
  • 291. Reusing PL/SQL code Reuse PL/SQL code in your trigger by: Copying and pasting it using the Edit menu options. Moving the trigger to Object Library node. Using the Copy and Paste options in the popup menu of the right mouse button. PL/SQL Library A PL/SQL Library is a collection of program units including user-defined procedures, functions and packages. PL/SQL Library provides you the convenient means of storing client-side program units and sharing them among multiple applications. The PL/SQL Library has the following features: It is created and stored either in a file or the database. It provides a convenient means for sharing a single copy of a program unit in many forms, menus, reports, or graphic modules. It also provides dynamic loading of program units. That means the program units are loaded into memory only when the application needs it. The bind variables in forms, menus and reports are outside the scope of the library as it is compiled independently of the Oracle Forms Developer modules. This means you cannot refer directly to the variables that are local to another module, because the compiler does not know them when you compile the library program units. There are two ways to refer to the bind variables indirectly: Refer to global variables and system variables in forms indirectly by using built-in subprograms. Write the program units with IN and OUT parameters, which are used to pass the names of the bind variables as parameters while calling the library program units from your Oracle Forms Developer applications. For example:FUNCTION fnTotalFine( bind_value IN VARCHAR2) RETURN NUMBER IS totFine NUMBER; BEGIN SELECT nFine INTO totFine FROM Transaction WHERE cMemberID= bind_value; RETURN totFine; END; Confidential © SQL Star International Ltd. 288
  • 292. Creating a LibraryYou must first create a library in the forms builder before you add any programunits to it. To do this: 1. In the Object Navigator, select File New PL/SQL Library from the main menu. A new entry for the PL/SQL Library appears under PL/SQL Library node. Select the PL/SQL Libraries node in the Object Navigator, and click the Create icon. • The PL/SQL Library created is shown as follows: 2. To create the program unit, expand the library node, select the Program Units node and then click Create icon. The Program Units dialog appears. The Program Units dialog box is shown the following figure: 3. Specify the name of the program unit and select its type from the given radio button options and click OK.Confidential © SQL Star International Ltd. 289
  • 293. 4. In the PL/SQL Editor, define the appropriate program units and then click the Compile button to compile and apply the modifications. Click the Close button to close the editor.The PL/SQL Library can be saved as follows: 1. Select File Save 2. Choose the destination folder and name by which the library is to be saved with .pll extension.Attaching the LibraryAfter saving library module to the file system or database, the library module canbe attached to a form, menu or library module as follows: 1. In the Object Navigator, open the desired form, menu or library module by clicking File Open and then specifying the module type to be opened. 2. Expand the module and select the Attached Libraries node. Click the Create icon to attach a library. The Attach Library dialog box appears as shown in the following diagram:3. Specify the name of the library to be attached as shown in the screen above.4. Click the Attach button to attach the PL/SQL Library to the current form module. Save the module to complete the process.Referencing Attached Library Program UnitsThe PL/SQL Library program units are referred in the same way as they aredefined locally, or stored in the database. The program units declared in apackage need to be prefixed with the name of the package for reference, whetherthey belong to the Object Library or they are attached to the calling module toAttached Libraries.For example:The procedure with name prMemberDetails can be referred as follows: prMemberDetails (:cMemberID, :cFirstName, :cLastName, :vAddress);The function with name fnFineCal can be referred as follows: Fine: = fnFineCal (:MemberID);Similarly the package with name pkMemberInfo can be referred as follows:Confidential © SQL Star International Ltd. 290
  • 294. PkMemberInfo. prMemberDetails(:cMemberID, :cFirstName, :cLastName, :vAddress);When several libraries are attached to the same form module, references areresolved by searching through the libraries in the order in which they occur in theattachment list. If two program units of the same name and type occur indifferent libraries in the attachment list, the program unit which is higher in thelibrary will be executed, since it is located first.SummaryIn this chapter, you have learnt that: • Whenever you want to develop an application, there is the need for reusing objects and code to improve productivity, maintenance, modularity, standards and application performance etc. • Property classes can be used in cases such as creation of Property Class, adding properties, deleting properties and inheriting property. • Object Library is a collection of common Oracle objects that store objects like property classes, visual attributes and triggers. • The valid Oracle forms objects that can be placed inside an object library are alerts and blocks etc. • Smart class is used to subclass existing objects in a form using the SmartClass option from the pop up menu, which gets invoked when you right click the object. • A smart class can be invoked by invoking the pop-up menu and selecting SmartClasses option. • A PL/SQL Library is a collection of program units including user-defined procedures, functions and packages. It is created and stored either in a file or the database.Confidential © SQL Star International Ltd. 291
  • 295. Lab Exercise: 1. Create a Property Class based on the nage column. 2. In the new form module, create a property class called ClassA. Include the following properties and settings: Font Name: Arial Format Mask: 99,999 Font Size: 8 Justification: Right Delete Allowed: No Background Color: blue Foreground Color: Gray 3. In the BRANCHXX Create an object group and name as objgroup consisting of Transaction block, cv_Transaction, win_Transaction window. o Copy the form level trigger to the object group. o Now create a new form module Demo and copy this form level trigger into the new module. 4. Create an Object Library, name it as OBJLIB. o Create five tab pages in it, name and label them as Text, Triggers, Canvas, Window and Buttons. o Keep the following items in the respective tabs. Cbranchname in Text. When-Button-Pressed trigger of EXIT_FORM button in Triggers. CV_BRANCH in Canvas. WIN_BRANCH in Window COLOR_BUTTON in Buttons. o Inherit only properties of the button into the form DEMO. 5. Create a smart class object for COLOR_BUTTON. Check how smart class is used. 6. Create a PL/SQL library, in that library create a procedure ‘Disp’ just to display ‘Hello from the Display’ and attach this library. o Call this Procedure in CONTROL.EXIT_FORM button.Confidential © SQL Star International Ltd. 292
  • 296. Chapter 17 WebUtil for Client Interaction Introduction to WebUtil Advantages of WebUtil Integrating WebUtil into a form Configuring Webutil When to Use the WebUtil Functionality Communicating with the client Using WebUtil in Various Context- ExamplesConfidential © SQL Star International Ltd. 293
  • 297. ObjectiveAt the end of this chapter, you will be able to: • Know about WebUtil • Describe the advantages of WebUtil Utility • Learn how to integrate WebUtil into a form • Get the idea of how to Configure Webutil • Know how to Communicate with client machine using WebUtil • Use WebUtil in Various Context with examplesConfidential © SQL Star International Ltd. 294
  • 298. Introduction to WebUtilThe middle-tier application server calls Forms built-in subprograms.Sometimes if you want to communicate with the client you can do with JavaBeansand PJCs, but with the utility called WebUtil, which has much prewrittenfunctionality for client interaction. This chapter deals with how to use WebUtil tointerface with the client machine.Overview of WebUtil • WebUtil enables you to have functionality on Win32 clients. • WebUtil comprises Java Classes, Forms objects and PL/SQL Library.Generally, Forms built-ins are executed on the application server machine. SomeForms built-ins communicate with the machine to read an image file, create orread a file, or execute operating system commands. Sometimes, it is desirable toexecute such built-ins on the application server machine. So to perform suchfunctionality on the client, you can very well use a JavaBean or PJC. For this,either you have to write or locate prewritten components and integrate each intoForms applications.WebUtil consists of a set of Java classes, Forms objects, and a PL/SQL API thatenables you to execute many Java functions of WebUtil without knowing Java. NOTE The middle-tier architecture can be of any platform on which WebUtil is installed with supported Forms Services but the client machine must be Windows 32-bit platform.Advantages of WebUtil• No java knowledge is necessary, the developer can code only in PL/SQL.• We can easily integrate WebUtil into forms application.• WebUtil provides Parity APIs, public functions, utility functions, internal functions, and client-server added value functions.• To perform complex tasks any Forms developer can use WebUtil on client browser machines by simply coding PL/SQL.• Using its Object group and PL/SQL Library, it is very easy to integrate WebUtil into your Forms applications, and you can easily extend it by adding your own custom functionality while leveraging its basic structure.• WebUtil enables you to perform a multitude of tasks, like: Reading and writing text files on the client machine Reading client-side variables Transferring files between the client, application server, and databaseConfidential © SQL Star International Ltd. 295
  • 299. Client-side files manipulation File selection dialog box use on the client Integrating with C code on the client Obtaining information about the clientThere is rich functionality available in the utility that includes the following: • Client/server parity APIs: This enables you to retrieve a file name from the client, read or write an image to or from the client, get information about the client machine, or perform HOST, TEXT_IO commands and OLE automation on the client (These built-ins execute on the application server machine without the WebUtil functions). • Client/server added value functions, which is ported from d2kwutil (a client/server package): CREATE_REGISTRY_KEY and DELETE_REGISTRY_KEY GET_COMPUTER_NAME GET_NET_CONNECTION GET_TEMP_DIRECTORY, GET_WINDOWS_DIRECTORY, and GET_WORKING_DIRECTORY GET_WINDOWS_USERNAME READ_INI_FILE and WRITE_INI_FILE READ_REGISTRY, WRITE_REGISTRY, and WRITE_REGISTRYEX NOTE There are some of these functions may duplicate other WebUtil functions, but if you use d2kwutil, then it is easy to migrate code. • Public functions: WebUtil is a set of packages. Each of these packages is provided with an API to implement certain functionality. WebUtil_ClientInfo package: This contains functions to obtain information about the client machine which are as follows: Function Returns: GET_DATE_TIME Date and time on client machine GET_FILE_SEPARATOR Character used on client as file separator (“” on Windows) GET_HOST_NAME Name of client machine GET_IP_ADDRESS IP address of client (string) GET_JAVA_VERSION JVM version that is running the Forms applet GET_LANGUAGE Language code of the client machine, such as de for German GET_OPERATING_SYST Name of OS running the browser EMConfidential © SQL Star International Ltd. 296
  • 300. WebUtil_C_API package: This contains functions to call into C libraries on the client which are as follows: Function Purpose: IsSupported Returns True if the client is a valid platform RegisterFunction Returns a handle to a specified C library function DeregisterFunction Deregisters function and frees client resources Create_Parameter_List Creates a parameter list to pass to C function Destroy_Parameter_List Deletes a parameter list and frees its resources Add_Parameter Adds a parameter to the parameter list Get_Parameter_Number Typed functions to return parameter Get_Parameter_Ptr values Get_Parameter_String Rebind_Parameter Changes parameter values of the existing parameter list to reuse it WebUtil_File package: This contains a PL/SQL table used to pass back multiple file names, which is a new type, called FILE_LIST. It also contains the APIs to manipulate files and directories on the client and to display file selection dialog boxes as shown in the following table:Confidential © SQL Star International Ltd. 297
  • 301. Function Purpose COPY_FILE Copy, rename, or delete a file and return RENAME_FILE a Boolean value to indicate success DELETE_FILE CREATE_DIRECTORY Creates the named directory if it does not exist; returns a Boolean value to indicate success DIRECTORY_ROOT_LIST Returns a FILE_LIST containing the directory roots on the client system (the drives on Windows) DIRECTORY_FILTERED_LIS Returns a list of files in a directory that T you filter using wildcard characters (* and ?) FILE_SELECTION_DIALOG Enables definition of File Save or File Open dialog box with configurable file filter and returns the selected file FILE_MULTI_SELECTION Enables definition of File Save or File _DIALOG Open dialog box with configurable file filter and returns the selected files in a FILE_LIST GET_FILE_SEPARATOR Returns character used on the client machine as a file separator (“” on Windows) GET_PATH_SEPARATOR Returns character used on client machine to separate directory locations on paths (“;” on Windows) Function Returns: GET_PATH_SEPARATOR Character used on client to separate directory locations on paths (“;” on Windows) GET_SYSTEM_PROPERT Any Java system propery Y GET_TIME_ZONE Time zone of client machine GET_USER_NAME Name of user logged in to the client WebUtil_File_Transfer package: The WebUtil_File_Transfer package contains APIs to transfer files to and from the client browser machine and to display a progress bar as the transfer occurs. The following APIs are included in the WebUtil_File_Transfer package:Function Purpose:URL_TO_CLIENT Transfers a file from a URL to the clientURL_TO_CLIENT_WITH machine (and displays a progress bar) _PROGRESSCLIENT_TO_DB Uploads a file from the client to aCLIENT_TO_DB_WITH database BLOB column (and displays a _PROGRESS progress bar)DB_TO_CLIENT Downloads file from a BLOB column inDB_TO_CLIENT_WITH the database to the client machine (and _PROGRESS displays a progress bar)CLIENT_TO_AS Uploads a file from the client to theCLIENT_TO_AS_WITH application server (with a progress bar) _PROGRESSAS_TO_CLIENT Transfers a file from the applicationAS_TO_CLIENT_WITH server to the client (with a progress bar) _PROGRESS Confidential © SQL Star International Ltd. 298
  • 302. WebUtil_Session package: This provides a way to respond to an interruption of the Forms session. If the session ends or crashes then this package finds a way by defining an URL to which the user is redirected. It contains the following: Function Purpose ENABLE_REDIRECT_ON Enables the time-out monitor and the _TIMEOUT specification of a redirection URL DISABLE_REDIRECT_ON Switches off the monitor; if you do not _TIMEOUT call this function before EXIT_FORM, the redirection occurs even if the exit is normal WebUtil_Host package: This contains routines to execute commands on the client machine. Thus it includes two types of routines: 1. PROCESS_ID :It holds a reference to a client-side process, and 2. OUTPUT_ARRAY: It is a PL/SQL table, which holds the VARCHAR2 output from a client-side command. The WebUtil_Host package also contains the following functions: Function Purpose HOST Runs the specified command in a BLOCKING mode on the client and optionally returns the return code BLOCKING Runs the specified command in a BLOCKING mode on the client and optionally returns the process ID NONBLOCKING Runs the specified command in a NON- BLOCKING mode on the client and optionally returns the process ID TERMINATE_PROCESS Kills the specified process on the client GET_RETURN_CODE Returns the return code of a specified process as an integer GET_STANDARD_OUTPUT Returns an OUTPUT_ARRAY containing output that was sent to standard output by the specified client process GET_STANDARD_ERROR Returns an OUTPUT_ARRAY containing output that was sent to standard error by the specified client processConfidential © SQL Star International Ltd. 299
  • 303. WebUtil_Core package: Contains mostly private functions, but you can call the following functions: Function Purpose IsError Checks whether the last WebUtil call succeeded ErrorCode Returns the last WebUtil error code ErrorText Returns the text of the last WebUtil error • Utility functions: There are some useful functions that are not related to client integration, as shown in the following table: Function Purpose: DelimStr Provides interaction with delimited strings Show_WebUtil_Information Calls the hidden WebUtil window to show the version of all WebUtil components WebUtil_Util Provides the BoolToStr() function for converting Boolean to text • There are some internal APIs that you should never call directly.Integrating WebUtil into a formStep 1: Attaching the WebUtil LibraryFirst attach the Webutil.pll library to the module that is going to use the WebUtilPL/SQL API to use the functions of WebUtil in a Forms application. NOTE Rename the webutil.pll library to avoid problems due to Bug 671456, if there are any other files or subdirectories named webutil in the FORMS_PATH. Else, you will receive an FRM-40039 error called – “cannot attach library at runtime”.Confidential © SQL Star International Ltd. 300
  • 304. Step 1: Attach the WEBUTIL library. Lib Step 2: Subclass the WEBUTIL object group. Error! Bookmark not defined.Alert Step 3: Move the WEBUTIL block after all other blocks. Object library Object groupWindow Confidential © SQL Star International Ltd. 301
  • 305. Step 2: Subclassing WebUtil Forms ObjectsA set of Forms objects contained in webutil.olb is a part of the WebUtil utility. Anobject group called WebUtil is contained in the object library that you cansubclass into your form.Step 3: Ensuring in the Object Navigator that WEBUTIL is thelast block.When you try to subclass the WebUtil object group into an empty form, you willfind that it contains some of the following objects: A generic alert for displaying WebUtil error messages. A generic alert for displaying WebUtil error messages. A canvas to contain the items A data block with items, including a button and several bean area items to implement the JavaBeans (the bean area items are hidden because there is no visual component). A window to display the canvas NOTE If you receive an FRM-92101 error while running the form, be sure that you have followed exactly the above steps.Configuring WEBUTIL 1. Download and unzip webutil_106.zip to c:Devsuitehomeforms 2. Download and Unzip jacob_18.zip to C:Devsuitehomeformsjava 3. Add the following in C:Devsuitehomeformsserverdefault.env WEBUTIL_CONFIG= C:DEvsuitehomeformsserverwebutil.cfg Append to existing CLASSPATH CLASSPATH= C:DevsuiteHomeformsjavafrmwebutil.jar; 4. Append the configuration of C:DevSuiteHomeformsserverformsweb.cfg archive_jini=f90all_jinit.jar, frmwebutil.jar, jacob.jar WebUtilArchive=frmwebutil.jar, jacob.jar 5. Add C:DevSuiteHomejdkbin to Environment variable PATH 6. Copy Jacob.jar to C:DevSuiteHomeformswebutil Open a Command window and change to the ORACLE_HOMEformswebutil directory. With it write the below signature in command prompt 7. sign_webutil.bat C:Devsuitehomeformswebutiljacob.jar-- press enter.Confidential © SQL Star International Ltd. 302
  • 306. Similarly sign frmwebutil.jar also. 8. sign_webutil.bat C:Devsuitehomeformsjavafrmwebutil.jar 9. Run create_webutil_db.sql Script 10. Open webutil.pll Compile it. To open it do the following: frmcmp module=D:DevSuiteHome_1formswebutil.pll userid=scott/tiger@orcl module_type=library compile_all=yes 11. Open the file WU_TEST.fmb and attach the library file.When to Use the WebUtil FunctionalityAs soon as you find the WebUtil library attached to your form, you can start toadd calls to the various PL/SQL APIs defined by the utility. But, you have arestriction here that is very important while using WebUtil functions- it is onlyafter the Form has instantiated the WebUtil JavaBeans that a WebUtil is allowedto communicate with the client.Thus, it is quite obvious that you cannot call WebUtil functions before the userinterface is rendered. For this reason you should not use the WebUtil functionalityin triggers such as When-New-Form-Instance, When-New-Block-Instance andPre-Form for the first block in the form. However, it is possible in the case of theWhen-New-Form-Instance trigger to call WebUtil functions after a call to theSYNCHRONIZE built-in has been issued. This is because this proves that the userinterface is rendered.However, after the destruction of the user interface, you cannot call WebUtilfunctions. Thus you should not use a WebUtil call in a Post-Form trigger.Communicating with the clientForms Built-ins/Packages WebUtil Equivalents HOST CLIENT_HOST GET_FILE_NAME CLIENT_GET_FILE_NAME READ_IMAGE_FILE CLIENT_IMAGE.READ WRITE_IMAGE_FILE (WRITE)_IMAGE_FILE OLE2 CLIENT_OLE2 TEXT_IO CLIENT_TEXT_IO CLIENT TOOL ENV TOOL ENVIn some applications these client/server parity APIs make it easy to providesimilar functionality that written for client/server deployment. Those built-inswere preceded with “CLIENT_” or “CLIENT_IMAGE”. There is no doubt that it iseasy to upgrade such applications but there are other WebUtil commands thatmay provide you the same but better, functionality. The client/server parity APIsincludes the following: CLIENT_HOST CLIENT_GET_FILE_NAMEConfidential © SQL Star International Ltd. 303
  • 307. READ_IMAGE_FILE: You can use this on the client by calling the WebUtilequivalent contained in a package known as CLIENT_IMAGE.READ_IMAGE_FILE.In addition to this, there are certain Forms packages that you can use on theclient with WebUtil:1 CLIENT_OLE2 CLIENT_TEXT_IO CLIENT_TOOL_ENVUsing WebUtil in Various Context- Examples1. Opening a File Dialog Box on the ClientTo open a file dialog box on the client for selecting a file, you can use: CLIENT_GET_FILE_NAME (DIRECTORY_NAME IN VARCHAR2, FILE_NAME IN VARCHAR2, FILE_FILTER IN VARCHAR2, MESSAGE IN VARCHAR2, DIALOG_TYPE IN NUMBER, SELECT_FILE IN BOOLEAN) RETURN VARCHAR2;The arguments for this WebUtil function are: • DIRECTORY_NAME: This specifies the name of the directory that contains the file you want to open. If DIRECTORY_NAME is NULL, subsequent invocations of the dialog box may open the last directory visited. • FILE_FILTER: This specifies that only particular files be shown. On Windows, the default is “All Files (*.*)|*.*|” if NULL. • FILE_NAME: This specifies the name of the file you want to open. • DIALOG_TYPE: This specifies the intended dialog box to OPEN_FILE or SAVE_FILE. • MESSAGE: This specifies the title of the file upload dialog box • SELECT_FILE: This specifies whether the user is selecting files or directories. The default value is TRUE; the user must select a directory if set to FALSE. If DIALOG_TYPE is set to SAVE_FILE, SELECT_FILE is internally set to TRUE. DECLARE v_file VARCHAR2 (250):= CLIENT_GET_FILE_NAME (,, ‘Bmp Files‘|*.bmp|Gif Files|*.gif|JPEG Files|*.jpg|, Select a photo to upload, open_file, TRUE);Confidential © SQL Star International Ltd. 304
  • 308. 2. Reading an Image File into Forms from the Client When you want to read or write image files, you can use the CLIENT_IMAGE package. For example, the CLIENT_IMAGE.READ_IMAGE_FILE procedure reads an image from the client file system and displays it in the Forms image item: CLIENT_IMAGE.READ_IMAGE_FILE (FILE_NAME VARCHAR2, FILE_TYPE VARCHAR2,ITEM_ID ITEM or ITEM_NAME VARCHAR2);The arguments for this WebUtil procedure are: • FILE_NAME (Valid file name): The file name designation can include a full path statement appropriate to your operating system. • FILE_TYPE (The valid image file type): BMP, CALS, GIF, JFIF, JPG, PICT, RAS, TIFF, or TPIC. NOTE As Oracle Forms will attempt to deduce it from the source image file, File type is optional but you should specify the file type to optimize performance.Confidential © SQL Star International Ltd. 305
  • 309. • ITEM_ID: The unique ID that Oracle Forms assigns to the image item when it creates it. • ITEM_NAME: The name you gave the image item when you created it. DECLARE v_file VARCHAR2(250):= CLIENT_GET_FILE_NAME(,,’Bmp Files’| *.bmp|Gif Files|*.gif|JPEG Files|*.jpg|, Select a photo to upload,open_file,TRUE); it_image_id ITEM := FIND_ITEM (members_photos.photo); BEGIN CLIENT_IMAGE.READ_IMAGE_FILE(v_file, ,it_image_id); END;Confidential © SQL Star International Ltd. 306
  • 310. SummaryIn this chapter, you have learnt that: • The WebUtil provides Client-side functionality and components of WebUtil. • WebUtil has much prewritten functionality for client interaction that enables you to have functionality on Win32 clients and comprises Java Classes, Forms objects and PL/SQL Library. • WebUtil enables you to perform a multitude of tasks, like reading and writing text files on the client machine • WebUtil_File package contains a new type which is a PL/SQL table used to pass back multiple file names called FILE_LIST. • WebUtil_Session packages provide a way to respond to an interruption of the Forms session. • There are steps to integrate WebUtil functionality into a form and different triggers used to add webutil functionality. • There are some useful functions that are not related to client integration. • You can integrate WebUtil into a form by attaching the WebUtil Library, subclassing WebUtil forms objects and ensuring in the object navigator that webUtil is the last block. • You should not use the WebUtil functionality in triggers such as When- New-Form-Instance, When-New-Block-Instance and Pre-Form for the first block in the form. • The client/server parity APIs includes CLIENT_HOST and CLIENT_GET_FILE_NAME. • The arguments for this WebUtil function are DIRECTORY_NAME, FILE_FILTER, DIALOG_TYPE, MESSAGE and SELECT_FILE. • FILE_NAME can include a full path statement appropriate to your operating system. • ITEM_ID is the unique ID that Oracle Forms assigns to the image item when it creates it.Confidential © SQL Star International Ltd. 307
  • 311. Lab Exercise 17 1. Select the image of the member by invoking the file image dialog box.Confidential © SQL Star International Ltd. 308
  • 312. Chapter 18 Working with Multiple Form Applications Invoking Multiple Form Modules The OPEN_FORM Built-in Procedure The CALL_FORM Built-in Procedure The NEW_FORM Built-in Procedure Form Parameters Built-in Subprograms to create and manipulate parameter lists Creating Record GroupsConfidential © SQL Star International Ltd. 309
  • 313. ObjectiveAt the end of this chapter, you will be able to: Identify ways of invoking multiple form modules Learn about the OPEN_FORM built-in procedure Know about the CALL_FORM built-in procedure Discuss about the NEW_FORM built-in Procedure Describe the need for form parameters Prepare built-in subprograms to create and manipulate parameter lists Create record groupsConfidential © SQL Star International Ltd. 310
  • 314. Invoking Multiple Form ModulesIn an earlier session you have seen that Forms applications can consist of morethan one form module. Multiple form modules can be invoked using any of thefollowing built-in procedures: OPEN_FORM CALL_FORM Form NEW_FORM C Forms Runtime Open Form Open Form (Parameters) A B (Parameters) Open (Parameters) Form D Global variables Global record groups PL/SQL variablesThe OPEN_FORM Built-in ProcedureOPEN_FORM built-in procedure opens an additional form module in a modelesswindow. This implies the invoking form remains displayed allowing you to switchbetween opened forms. However, it may be difficult to keep multiple open formssynchronized. For instance, if frmLib module invokes frmLibTrans module thecurrent transaction in frmLibTrans module may not always belong to the currentmember in the frmLib module.The syntax of OPEN_FORM built-in procedure is:Confidential © SQL Star International Ltd. 311
  • 315. OPEN_FORM (‘form_name’, ACTIVATE_MODE, SESSION_MODE, DATA_MODE, PARAMLIST); Where, form_name specifies the name of the file containing the executable Version of the form to be invoked. ACTIVATE_MODE is a parameter with the following values: • ACTIVATE (default): It sets the focus on the opened form. • NO_ACTIVATE: It does not set the focus on the opened form. SESSION_MODE is a parameter with the following values: • NO_SESSION (default): It opens the form in the same database session as the current form. • SESSION: A separate database session is created for the opened form. DATA_MODE is a parameter with the following values: • NO_SHARE_LIBRARY_DATA (default): It specifies that forms having identical libraries attached at design time will not share their data at runtime • SHARE_LIBRARY_DATA: It specifies that forms having identical libraries attached at design time will share their data at runtime. PARAMLIST is either the name (in quotes) or internal ID of a parameter list to be passed to the opened form.NOTE To share PL/SQL variable data between forms, create a package containing the PL/SQL variables to be shared and place it in the library. Attach the library to the forms that need to share data. In the OPEN_FORM built-in procedure, set the DATA_MODE property as SHARE_LIBRARY_DATA. This makes changes made by one form visible to another. The characteristics of OPEN_FORM built-in procedure are as follows: It is a restricted procedure because it causes navigation, that is, moves the focus from one form module to another. It is not valid in the Enter Query mode. It opens the form in a modeless window. It can create a new database session. It does not issue a savepoint, that is, changes in the opened forms cannot be saved or rolled back without affecting changes in the opening forms. Trigger statements that follow the call to OPEN_FORM built-in are never executed when a form is opened with the parameter specified as ACTIVATE. However, trigger statements following the call to OPEN_FORM Confidential © SQL Star International Ltd. 312
  • 316. are executed when a form is opened with the parameter specified as NO_ACTIVATE.You can invoke frmLibTrans form module from frmLib form module by writingthe following code within WHEN-BUTTON-PRESSED trigger: OPEN_FORM (‘D:Form6iModulesfrmLibTrans’);The entire path need not be mentioned if forms are saved in the default path.You can navigate programmatically between forms that have been opened withthe OPEN_FORM built-in procedure using the following built-in subprograms: Built-in Subprogram Description NEXT_FORM Shifts the input focus to the open form with the next highest sequence number. In the absence of a form with a higher sequence number, the built-in navigates to the form with the lowest sequence number. PREVIOUS_FORM Shifts the input focus to the open form with the next lowest sequence number. In the absence of a form with a lower sequence number, the built-in navigates to the form with the highest sequence number. GO_FORM Navigates to the form module, specified either by name or its internal ID. NOTE Forms are sequenced in the order in which they were invoked at runtime.The following navigation and validation aspects need to be kept in mind whilenavigating between forms: While navigating between open forms, no validation occurs in the form that initiates the navigation. However, normal validation occurs when an attempt is made to navigate within the form that initiates navigation. While navigating between forms using the built-ins NEXT_FORM, PREVIOUS_FORM, or GO_FORM, no triggers fire except WHEN-WINDOW- DEACTIVATED trigger, which fires, initiates navigation for the form and WHEN-WINDOW-ACTIVATED trigger that fires for the form navigated to.Confidential © SQL Star International Ltd. 313
  • 317. When you click a non-current item of an open form, triggers that would fire at the time of navigating from a current item to a target item, get fired. In this case, validation occurs and navigational triggers fire.Transaction Processing for Opened FormsAt runtime, Form Builder establishes a single connection to the Oracle databaseautomatically. As such, one database session is created for this connection.However, multiple sessions can be established within a single connection with thehelp of the multiple session feature of the Oracle database.Read consistency and transaction management behavior for two forms in differentsessions is the same as it is for the two clients with separate connections. Forinstance, when two independent forms attempt to access the same table, one ofthe forms can obtain a lock, preventing the other form from accessing the recordsof the table.Same SessionThe following issues need to be considered when forms are opened within thesame session: Commit Processing: When you issue a COMMIT command, Form Builder performs validation and commit processing for all forms in the order in which they were opened within the same session. In case of an error during the commit process, Form Builder sets the input focus to the form that initiated the commit. Savepoint and rollback processing: When forms are opened within the same session, Form Builder does not issue a savepoint for the form. For instance, if frmLib opens frmLibTrans within the same session, then when frmLibTrans executes CLEAR_FORM built-in procedure, all changes made in frmLibTrans as well as frmLib are rolled back.Different SessionsIt is appropriate to open forms in different sessions, when they access differenttables and manage logically independent transactions. For example, frmLib formmodule invokes frmLibTrans form module. If frmLibTrans is opened in thesame session, you will have to commit changes made to both the formssimultaneously. However, if it is opened in a separate session, you can enter anew transaction detail in frmLibTrans and save it independently to the databasewithout having to commit frmLib. NOTE To execute OPEN_FORM with SESSION_MODE parameter set to SESSION, Forms Runtime must set the Session option to ‘On’. If set to ‘Off’, Form Builder issues an error and does not open the form. To set the Session option to ‘On’, the FORMS50_SESSION environment variable must be set to ‘True’.Confidential © SQL Star International Ltd. 314
  • 318. OPEN_FORM Form Form Open_Form Form To close a form, use CLOSE_FORM built-in procedure. Its syntax is: CLOSE_FORM (Form_Name| Form_ID); Where, Form_Name is the form module (not the .fmx filename) Form_ID is the internal form module ID. The datatype returned is FORM MODULE. The main characteristics of CLOSE_FORM procedure is: It is a restricted procedure, which is not valid in the Enter Query mode. It is similar to EXIT_FORM when the specified form module is the current form. It cannot be used to close a form that has opened another form with CALL_FORM built-in procedure.TIP It is recommended to close your Web-deployed applications using either CLOSE_FORM or EXIT_FORM built-ins. Otherwise, applications continue! until timed out by the Oracle Forms Server. Confidential © SQL Star International Ltd. 315
  • 319. The CALL_FORM Built-in ProcedureCALL_FORM built-in procedure calls another form module in a modal window.That is, you cannot work in the calling form unless you exit from the called form.This is appropriate if the called form is to be used to set data in the calling formas in the case of an LOV form. This keeps both the calling and the called formssynchronized.The syntax of CALL_FORM built-in procedure is: CALL_FORM (‘form_name’, DISPLAY, SWITCH_MENU, QUERY_MODE, DATA_MODE, PARAMLIST);Where,form_name is the name of the file containing the executable version of the formto be invoked.DISPLAY parameter has the following values: • HIDE (default): It specifies that the calling form be hidden while the called form is running. • NO_HIDE: It specifies that the called form should be displayed without hiding the calling form. SWITCH_MENU parameter has the following values: • NO_REPLACE (default): The default menu module of the calling form is kept active for the called form. • DO_REPLACE: The default menu module of the calling form is replaced with the default menu module of the called form. QUERY_MODE parameter has the following values: • NO_QUERY_ONLY (default): The specified form is invoked in the normal mode wherein the user can make inserts, updates, and deletes. • QUERY_ONLY: The specified form is invoked in the query-only mode wherein the user can query but not insert, update, or delete. DATA_MODE and PARAMLIST parameters have the same values as in OPEN_FORM built-in procedure.The characteristics of CALL_FORM built-in procedure is: It is an unrestricted procedure and therefore valid in the Enter Query mode. It issues savepoints, thereby, enabling changes in the called forms to be posted or rolled back without affecting changes in the calling form. These savepoints break database transactions into segments that correspond to specific form modules. It causes the called form to be modal with respect to calling form. It does not cause any validation or navigation in the starting form. Trigger statements following the call to CALL_FORM built-in procedure is executed after the control returns to the calling form, that is, when Forms exits the called form.Confidential © SQL Star International Ltd. 316
  • 320. You can invoke frmLibTrans form module from frmLib form module by writingthe following code within WHEN-BUTTON-PRESSED trigger: CALL_FORM (‘c:Form10gModulesTransaction’);Transaction Processing for Called FormsWhen forms are invoked using the CALL_FORM built-in, the following transactionprocessing aspects need to be kept in mind: Commit processing: When changes made in the calling form are not explicitly posted or committed, Form Builder invokes the called form in post-only mode. In post-only mode, DML statements can be submitted to the database, but cannot be committed or rolled back. This is to prevent losing locks in the calling form. Any form called from a form running in post-only mode will also be in post-only mode.The characteristics of post-only mode are:17) Changes in the called form are not committed, only posted (that is, changes are written to the database). Any attempt to commit changes returns the message: “A calling form has unapplied changes. Save not allowed.” When you exit the form, a prompt asking whether the changes that were made needs to be applied (posted) rather than saved (committed) is displayed as follows:The runtime screen of frmLibTrans shows the message displayed when attemptis made to save changes, while there are unsaved changes in frmLib: Rollback processing: Form Builder issues a savepoint when a form is called with CALL_FORM built-in procedure. When changes made in the called form are discarded, Form Builder issues a rollback to the savepoint set when the form was called. That is, changes are rolled back upon exiting the called form without affecting changes in the calling form. This is because of the default arguments in EXIT_FORM built-in, which are: EXIT_FORM (Ask_Commit, To_Savepoint);The commit and rollback behavior of called forms requires redefining of thedefault transaction processing. This can be done by: Redefining [Commit] by writing a KEY-COMMIT trigger at form level so as to post changes made when the form is called. BEGINConfidential © SQL Star International Ltd. 317
  • 321. IF GET_APPLICATION_PROPERTY (CALLING_FORM) IS NOT NULLTHENPOST; ELSECOMMIT_FORM; END IF; END; Redefining [Exit] by writing a KEY-EXIT trigger at form level so as to not rollback the changes made when the form is called. BEGIN IF GET_APPLICATION_PROPERTY (CALLING_FORM) IS NOT NULLTHENEXIT_FORM (ASK_COMMIT, NO_ROLLBACK); ELSEEXIT_FORM; END IF; END;Call Form StackWhen a form is invoked with CALL_FORM, it is loaded into memory while thecalling form is also loaded. However, the calling form is disabled and users cannotset focus to its items. The module hierarchy resulting when successive forms areinvoked using CALL_FORM is known as the call form stack.There are certain restrictions involved in using OPEN_FORM with CALL_FORM.They are: Navigating programmatically to a disabled form in a call form stack is not allowed. Only one call form stack is allowed per run form session. That is, an open form Form3 cannot execute CALL_FORM if a call form stack has been initiated by another open form. Form2.The following diagram depicts the restrictions involved in using OPEN_FORM withCALL_FORM: CALL_FORM OPEN_FORM OPEN_FORM Form1 Form2 Form3 Form4 CALL_FORM CALL_FORM Form6 Form5Confidential © SQL Star International Ltd. 318
  • 322. The NEW_FORM Built-in ProcedureNEW_FORM built-in procedure enters the specified form module and exits thecurrent one. The current form is completely replaced with the new form. Thismeans, Form Builder releases memory that was being used by the terminatedform module.Its syntax is: NEW_FORM (‘Form_Name’, ROLLBACK_MODE, QUERY_MODE, DATA_MODE, PARAMLIST);Where,Form_Name is the name of the file containing the executable version of the formto be invoked.ROLLBACK_MODE parameter has the following values: TO_SAVEPOINT (default): all uncommitted changes (including changes posted) are rolled back to the current form’s savepoint. NO_ROLLBACK: the current form is exited without rolling back to the savepoint. FULL_ROLLBACK: all uncommitted changes (including changes posted) made during the current run form session are rolled back.QUERY_MODE, DATA_MODE, and PARAMLIST parameters have the same values asin OPEN_FORM and CALL_FORM built-ins.You can invoke frmLibTrans module from frmLib using the NEW_FORM built-in inthe WHEN-BUTTON-PRESSED trigger.Form ParametersThe form variables defined at design time to supply values of inputs required by aform at startup are known as parameters. They are of type CHAR, NUMBER, orDATE.Creating Form ParametersThe steps to create a form parameter in the frmLibTrans form module is: In the Object Navigator, select the Parameters node and click the Create icon. Invoke the Property Palette of the parameter created and name it as paramMemberID. The following Object Navigator screen shows the parameter created:Confidential © SQL Star International Ltd. 319
  • 323. You can pass parameter values to a Form either: When you start a form from the command line using the standard command line syntax, the default values specified for the parameter at design time is overridden by the parameter value entered on the command line. In the following example, MODULE and USERID are predefined command line parameters, PARAMMEMBERID is the user defined parameter created in frmLibTrans module: Ifrun90.exe MODULE=frmLibTrans USERID=scott/tiger PARAMMEMBERID= ‘PP039601’ When a form is invoked from another form module, you can pass parameter values by assigning them to parameter lists in the call to OPEN_FORM, CALL_FORM, or NEW_FORM built-in subprograms. This is illustrated later in this session.Form parameters are referenced within codes in a way similar to how formvariables are referenced. That is: Parameter contents are referenced using the bind-variable syntax such as:PARAMETER.PARAMMEMBERID, where PARAMETER is the fixed reserved word.Confidential © SQL Star International Ltd. 320
  • 324. Parameter names are referenced by enclosing the name within a single quotation mark, such as ‘PARAMETER.PARAMMEMBERID’. Creating Parameter Lists When you use OPEN_FORM, CALL_FORM, or NEW_FORM procedures to invoke a form, you can pass values for form parameters from the invoking form to the invoked form. To do so, each parameter and its value must be contained in a parameter list. Parameter list is a three-column data structure that contains the key (parameter name), their type (TEXT_PARAMETER or DATA_PARAMETER), and the value of each parameter on the list. The two-parameter types are: TEXT_PARAMETER: A parameter with a scalar, non-composite CHAR value. DATA_PARAMETER: A parameter with the name of a record group defined in the current form as its value. Data parameters cannot be used to pass data to forms. They are used to pass data to products like Report Builder, Graphic Builder, etc invoked with RUN_PRODUCT built-in subprogram. NOTE A parameter list named DEFAULT or an already existing parameter list cannot be created. Check whether a parameter list exists by using GET_PARAMETER_LIST and ID_NULL built-in subprograms. The following diagram illustrates the data structure of a parameter list: Parameter List Key Type Value paramMemberID TEXT_PARAMETER ‘PP039601’ paramMemID DATA_PARAMETER ‘rgMemberID’ OPEN_FORMSpecify parameter list in the calls to CALL_FORM NEW_FORM Confidential © SQL Star International Ltd. 321
  • 325. NOTE Every form includes a built-in parameter list known as DEFAULT. All the form parameters defined at design time are contained within the DEFAULT parameter list. It can be specified in the call to the built-ins that invoke form modules.Built-in Subprograms to create and manipulateparameter listsThe built-in subprograms used to create and manipulate parameter lists are: CREATE_PARAMETER_LIST: It is an unrestricted function, which creates a parameter list with the given name and assigns it a unique ID of PARAMLIST type. The parameter list can be called either by name or ID in parameter list related built-in subprograms. Its syntax is: CREATE_PARAMETER_LIST (name VARCHAR2) DESTROY_PARAMETER_LIST: It is an unrestricted procedure, which deletes the programmatically created parameter list along with all its parameters. Its syntax is: DESTROY_PARAMETER_LIST (ParameterList_name| ID VARCHAR2); GET_PARAMETER_LIST: It is an unrestricted function, which searches the list of parameter lists to return the internal ID of a parameter list with the given name. It is similar to FIND_functions available for other form objects. The syntax is: GET_PARAMETER_LIST (ParameterList_name); ADD_PARAMETER: It is an unrestricted procedure, which adds a parameter to the programmatically created parameter list. The parameter added consists of a key (name), type (TEXT_PARAMETER or DATA_PARAMETER), and an associated value. Its syntax is: ADD_PARAMETER (ParameterList_name| ID VARCHAR2, key VARCHAR2, paramtype VARCHAR2, value VARCHAR2); Where, ParameterList_name| ID is the parameter list to which the parameter is to be added key is the name assigned to the parameterConfidential © SQL Star International Ltd. 322
  • 326. paramtype is either TEXT_PARAMETER or DATA_PARAMETER value is the value intended to pass to the invoked form module. DELETE_PARAMETER: It is an unrestricted procedure, which deletes the parameter with the specified key from the given parameter list. Its syntax is: DELETE_PARAMETER (ParameterList_name| ID, key); GET_PARAMETER_ATTR: It is an unrestricted procedure that returns two OUT parameters, namely the type and current value of a specified parameter in an indicated parameter list. Its syntax is: GET_PARAMETER_ATTR (ParameterList_name| ID VARCHAR2, key VARCHAR2, paramtype NUMBER, value VARCHAR2);Where, paramtype is an OUT parameter of type NUMBER. The parameter you specify must be a variable of NUMBER, and not an expression. The value it sets for the variable is either DATA_PARAMETER or TEXT_PARAMETER. Value is an OUT parameter of type VARCHAR2. The value is the name of a record group if the parameter is a data parameter and the value is an actual text if the parameter is a text parameter. SET_PARAMETER_ATTR: It is an unrestricted procedure, which sets the value and type of a specified parameter in an indicated parameter list. Its syntax is: SET_PARAMETER_ATTR (ParameterList_name| ID VARCHAR2, key VARCHAR2, paramtype NUMBER, value VARCHAR2);To pass parameter values of paramMemberID (created at design time infrmLibTrans module) when a form is invoked, you need to:Place the parameter within a parameter list. To create a parameter list, write thefollowing code within WHEN-BUTTON-PRESSED trigger in frmLib form module: DECLARE paramID PARAMLIST; BEGIN paramID:=GET_PARAMETER_LIST(paramlstLib); IF ID_NULL (paramID) THEN paramID:=CREATE_PARAMETER_LIST(paramlstLib);Confidential © SQL Star International Ltd. 323
  • 327. ADD_PARAMETER (paramID, PARAMMEMBERID, TEXT_PARAMETER,:cMemberID); ELSE DELETE_PARAMETER (paramID, PARAMMEMBERID); ADD_PARAMETER (paramID, PARAMMEMBERID, TEXT_PARAMETER, :cMemberID); END IF; OPEN_FORM (D:Form9iModulesfrmLibTrans, ACTIVATE, NO_SESSION, NO_SHARE_LIBRARY_DATA, paramID); END; The above code performs the following tasks: ♦ Destroys an existing parameter list ♦ Creates a new parameter list ♦ Adds a text parameter along with the value of an item to the parameter list created ♦ Invokes a form using this parameter list After creating the parameter list paramlstLib, write a WHEN-NEW- FORM-INSTANCE trigger in frmLibTrans to execute query at form startup:EXECUTE_QUERY; Next write a PRE-QUERY trigger at the Transaction block level as follows to pass the parameter value: : cMemberID:=:PARAMETER.PARAMMEMBERID; You can also pass data between forms using global variables. In such a case the above WHEN-BUTTON-PRESSED trigger would have the following code: : GLOBAL.MemberID: =: cMemberID; OPEN_FORM (‘c:Form10gModulesTransaction); The WHEN-NEW-FORM-INSTANCE trigger would be the same, however, Transaction block PRE-QUERY trigger code would be as follows: : cMemberID:=:GLOBAL.MemberID; The major points of distinction between form parameters and global variables are: Confidential © SQL Star International Ltd. 324
  • 328. Form Parameters Global Variables Used only as input parameters. This The invoked form can modify global means, the invoked form cannot variable values. modify parameter values. Can be of CHAR, NUMBER, or DATE Are only of CHAR datatype, which are 255 datatype. CHAR parameters can be characters long. 64K long Can be design time objects Are only programmatic constructs Not visible across multiple forms Visible across multiple forms and remain active unless deleted explicitly with the ERASE built-in procedure, or until the end of the session.Confidential © SQL Star International Ltd. 325
  • 329. Creating Record GroupsA record group is a data structure, which has a column-row framework that issimilar to a database table. It is an internal Form Builder object (exists in localForms memory) that belongs to the form module in which it is defined. It canhave unlimited number of columns of CHAR, NUMBER, or DATE datatype.Record groups are used to: Construct dynamic SELECT statements Store form configuration information Communicate within a form module Pass data to other forms Pass data to other Oracle products Populate list items.Types of Record GroupsThere are three types of record groups. They are: Query Record Group: It has an associated SELECT statement. The Query Record Group columns derive their names, datatypes, and lengths from the database columns specified in the SELECT statement. Their records are the rows retrieved by the SELECT statement. They can be created and modified at design time as well as runtime. Nonquery Record Group: has no associated SELECT statement. However, its structure and row values can be modified at runtime. Nonquery Record Group columns and rows are defined only at runtime. Static Record Group: has no associated SELECT statement. Its structure and row values are defined at design time and remain fixed at runtime. NOTE While creating a record group, you do not specify its type explicitly. The type is implied by when (design time or runtime) and how the record group is defined. A query record group is created implicitly when a LOV based on a query is created. SET_LOV_PROPERTY built-in function can be used to replace the default record group of a LOV. Use GROUP_NAME property in SET_LOV_PROPERTY to do so.Creating Record Groups at Design TimeThe record groups defined at design time are: Query record group Static record groupConfidential © SQL Star International Ltd. 326
  • 330. The steps to create a query record group is: In frmLib form module, select the Record Groups node in the Object Navigator and click the create icon. A New Record Group dialog box is displayed. Click Based on the Query below…radio button and enter a SELECT statement in the Query Text field as shown in the screen below: Click OK. The dialog box is closed after Forms validates the SELECT statement. Name the record group created as rgMemberID. The steps to create a static record group is: In frmLibTrans form module, select the Record Groups node in the Object Navigator and click the create icon. A New Record Group dialog box is displayed. Click Static Values radio button and click OK. The Column Specification dialog box is displayed. Enter column names in the Column Names list. Specify the Data Type, Length, and Column Values properties for each of the column names as shown in the screen below:Confidential © SQL Star International Ltd. 327
  • 331. Navigator and invoking its Property Palette Double clicking the Column Specifications property to display the Column Specification dialog box. The following Property Palette screen shows the Column Specifications Click OK. Name the record group as rgBooks.After creating the query record group, you can modify the column definition of arecord group by: The SELECT statement of a query record group by: Selecting the desired record group in the Object Navigator and invoking its Property Palette Opening the editor from the Record Group Query property and modifying the SELECT statement as desired. Clicking OK. The column definition of a record group by: Selecting the desired record group in the Object property:Confidential © SQL Star International Ltd. 328
  • 332. Select the column whose properties you desire to change and then click OK.Creating Record Groups programmaticallyThe record groups created programmatically at runtime are: Query record groups Nonquery record groups To define record groups at runtime, you need to use the following built-in functions: The built-in functions to create and delete record groups are:Confidential © SQL Star International Ltd. 329
  • 333. Name Description SyntaxCREATE_GROUP Creates a non-query CREATE_GROUP record group with the (Recordgroup_name name specified and VARCHAR2, returns the ID assigned to it. The scope NUMBER record group created array_fetch_size has no columns and NUMBER); rows until added explicitlyCREATE_GROUP_FROM_QUERY Creates a query CREATE_GROUP_FROM_ record group of the QUERY name specified based (Recordgroup_name on the given SELECT VARCHAR2, statement. It returns the ID assigned to the query VARCHAR2, record group. scope NUMBER, array_fetch_size NUMBER)DELETE_GROUP Deletes a DELETE_GROUP programmatically (Recordgroup_name|Rec created record group ordgroup_ID VRACHAR2| RECORDGROUP)Confidential © SQL Star International Ltd. 330
  • 334. The built-in functions to modify the structure of record groups are:Name Description SyntaxADD_GROUP_ Adds a column of the specified ADD_GROUP_ datatype to the given record groupCOLUMN COLUMN and returns the ID assigned to the column. (Recordgroup_name|Rec ordgroup_ID VARCHAR2| RECORDGROUP, Groupcolumn_name VARCHAR2, Column_type NUMBER, Column_width NUMBER);ADD_GROUP_ Adds a row with the given row ADD_GROUP_ number to the specified recordROW ROW group. (Recordgroup_name|Rec ordgroup_ID VARCHAR2| RECORDGROUP, row_number NUMBER)DELETE_GROUP_ Deletes the specified row or rows of DELETE_GROUP_ROW the given record group. TheROW (Recordgroup_name|Rec memory occupied by the rows ordgroup_ID VARCHAR2| deleted are freed. RECORDGROUP, row_number NUMBER)Confidential © SQL Star International Ltd. 331
  • 335. NOTE You can specify the column_type to be CHAR_COLUMN, NUMBER_COLUMN, or DATE_COLUMN. Column_width is specified only when column_type is CHAR_COLUMN If you want to delete all the rows, specify row_number value as ALL_ROWS. All the rows get deleted, but the group continues to exist. The built-I functions to populate record groups are: Name Description Syntax POPULATE_ Executes the query associated POPULATE_ with specified query record group GROUP GROUP and returns 0 upon successful query and upon unsuccessful (Recordgroup_name|Recordgro query an Oracle error number is up_ID VARCHAR2| returned. The rows retrieved upon RECORDGROUP); successful query replace rows that exist in the group POPULATE_ Executes the given query for the POPULATE_ specified record group and returns GROUP_WITH_ GROUP_WITH_Confidential © SQL Star International Ltd. 332
  • 336. Name Description Syntax QUERY 0 upon successful query and upon QUERY unsuccessful query an Oracle (Recordgroup_name|Recordgro error number is returned. up_ID VARCHAR2| RECORDGROUP, query VARCHAR2) SET_GROUP_ Set the record group cell value SET_GROUP_ based on the record group column CHAR_CELL, CHAR_CELL| SET_GROUP_ and row number specified. The SET_GROUP_ record group columns must be of NUMBER_CELL| SET_GROUP_ DATE_CELL, datatype VARCHAR2 (or LONG), DATE_CELL SET_GROUP_ NUMBER, or DATE. (groupcolumn_ID NUMBER_CELL GROUPCOLUMN, row_number NUMBER, cell_value VARCHAR2) NOTE A non-query record group can be converted into a query record by using POPULATE_GROUP_WITH_QUERY built-in function. The built-in functions used to obtain record group cell values are: Name Description Syntax GET_GROUP_ Return the record group cell GET_GROUP_ value based on the record group CHAR_CELL, CHAR_CELL| column and row number GET_GROUP_ GET_GROUP_ specified. The record group NUMBER_CELL, columns must be of datatype NUMBER_CELL| GET_GROUP_ VARCHAR2 (or LONG), NUMBER, GET_GROUP_ DATE_CELL or DATE. DATE_CELL (groupcolumn_ID GROUPCOLUMN, row_number NUMBER) The built-in functions used to process record group rows are:Confidential © SQL Star International Ltd. 333
  • 337. Name Description Syntax GET_GROUP_ Returns the number of rows GET_GROUP_ROW_COUNT existing in the record group ROW_COUNT (Recordgroup_name|Record specified group_ID VARCHAR2| RECORDGROUP) SET_GROUP_ Marks the indicated rows in the SET_GROUP_ given record group sequentially SELECTION SELECTION starting with 1. For example, if rows 2, 5, and 7 are selected, (Recordgroup_name|Record Form Builder considers those rows group_ID VARCHAR2| to be selections 1, 2, and 3. RECORDGROUP, row_number NUMBER) RESET_GROUP_ Deselects all record group rows RESET_GROUP_ that have been marked as selected SELECTION SELECTION by SET_GROUP_SELECTION. (Recordgroup_name|Record group_ID VARCHAR2| RECORDGROUP) UNSET_GROUP_ Deselects or unmarks the row with UNSET_GROUP_ the specified row number in the SELECTION SELECTION given record group (Recordgroup_name|Record group_ID VARCHAR2| RECORDGROUP, row_number NUMBER) GET_GROUP_ Returns the number of rows GET_GROUP_ marked as selected in the given SELECTION_ SELECTION_ record group. COUNT COUNT (Recordgroup_name|Record group_ID VARCHAR2| RECORDGROUP) GET_GROUP_ Returns the sequence number GET_GROUP_ assigned to the selected row for SELECTION SELECTION the specified record group. (Recordgroup_name|Record group_ID VARCHAR2| RECORDGROUP, selection_number NUMBER)Confidential © SQL Star International Ltd. 334
  • 338. The built-in functions used to find record group objects are: Name Description Syntax FIND_GROUP Returns the internal ID of the FIND_GROUP specified record group (of type (recordgroup_name RECORDGROUP). VARCHAR2) FIND_COLUMN Returns the internal ID of the FIND_COLUMN specified record group column (recordgroup_groupc (of type GROUPCOLUMN). olumn_name VARCHAR2) The following code illustrates how to create and populate a query record group programmatically: DECLARE vRgID RECORDGROUP; vSuccessCode NUMBER; BEGIN -- Ensure the record group does not exist vRgID:= FIND_GROUP (‘rgMember’); IF ID_NULL (vRgID) THEN -- Create a query record group vRgID:=CREATE_GROUP_FROM_QUERY (‘rgMember’,‘SELECT cMemberID, cFirstName, dMembershipDt FROM Member’); END IF; --populate the record group VSuccessCode: =POPULATE_GROUP (vRgID); END; The following code illustrates how to create and populate a non-query record group programmatically: DECLARE vRgID RECORDGROUP; vGc1ID GROUPCOLUMN; vGc2ID GROUPCOLUMN; BEGIN --Ensure the record group does not exist vRgID:=FIND_GROUP(‘rgMember’);Confidential © SQL Star International Ltd. 335
  • 339. IF ID_NULL (vRgID) THEN -- Create a non-query record group vRgID:=CREATE_GROUP(‘rgMember’); --Add CHAR group columns to the record group vGc1ID:=ADD_GROUP_COLUMN(vRgID, ‘ID’, CHAR_COLUMN, 13);VGc2ID: =ADD_GROUP_COLUMN (vRgID, ‘Name’, CHAR_COLUMN, 25); ELSE --Delete existing group rows DELETE_GROUP_ROW (vRgID, ALL_ROWS); -- Find group column Ids for later use vGc1ID:=FIND_COLUMN(‘rgMember.ID’); vGc2ID:=FIND_COLUMN(‘rgMember.Name’); END IF; -- Add one row to the record group ADD_GROUP_ROW (vRgID, 1); -- Fill the cells of the row with values SET_GROUP_CHAR_CELL (vGc1ID, 1, : MEMBER.cMemberID); SET_GROUP_CHAR_CELL (vGc2ID, 1, : MEMBER.cFirstName); END;Manipulating List ItemsWhen list items are defined at design time, you set its labels and values on theProperties window. These properties could also be set programmatically byusing the following built-in functions:Confidential © SQL Star International Ltd. 336
  • 340. Name Description Syntax ADD_LIST_ELEMENT Adds a single element (with ADD_LIST_ label and value) to the ELEMENT given list item at the specified position (index). (list_ID ITEM|list_name VARCHAR2, list_index VARCHAR2, list_label VARCHAR2, list_value NUMBER) CLEAR_LIST Clears all elements from the CLEAR_LIST given list item, after which (list_ID ITEM|list_name only one null element is VARCHAR2) contained in the list. DELETE_LIST_ Deletes an element at the DELETE_LIST_ specified position (index) ELEMENT ELEMENT from the given list item. (list_ID ITEM|list_name VARCHAR2, list_index NUMBER) GET_LIST_ELEMENT_C Returns the total number GET_LIST_ OUNT (in CHAR format) of ELEMENT_COUNT elements in a list item, including those with null (list_ID ITEM|list_name values. VARCHAR2) GET_LIST_ELEMENT_L Returns the label of the GET_LIST_ ABEL element in the given list ELEMENT_LABEL item at the specified position (index). (list_ID ITEM, list_name VARCHAR2, list_index NUMBER) or GET_LIST_ELEMENT_LABEL (list_name VARCHAR2, list_index NUMBER) GET_LIST_ELEMENT_V Returns the value of a GET_LIST_ ALUE specified element in the ELEMENT_VALUE given list item at the (list_ID ITEM|list_nameConfidential © SQL Star International Ltd. 337
  • 341. Name Description Syntax specified position. VARCHAR2, list_index NUMBER) POPULATE_LIST Removes the values of the POPULATE_LIST current list and populates it (list_ID ITEM|list_name with values from a record VARCHAR2, group created at runtime having the following two recordgroup_ID CHAR columns: RECORDGROUP|recordgroup _name VARCHAR2) Column1 :- list label Column2 :- list value RETRIEVE_LIST Retrieves and stores the RETRIEVE_LIST current list element (list_ID ITEM|list_name contents (label and value) VARCHAR2, into the specified record group (having the columns recordgroup_ID mentioned above). RECORDGROUP|recordgroup _name VARCHAR2) POPULATE_LIST and RETRIEVE_LIST built-in functions are used to transfer information between list items and record groups. However, the following conditions must be met to use record groups with list items:POPULATE_LIST and RETRIEVE_LIST built-in functions make use of record groups, which are covered, in a later sess The record group must have two CHAR columns. The first column to store list element labels. The second column to store list element values. Confidential © SQL Star International Ltd. 338
  • 342. SummaryIn this chapter you have learnt that: • You can use OPEN_FORM, CALL_FORM and NEW_FORM to invoke multiple form modules. • OPEN_FORM built-in procedure opens an additional form module in a modeless window and is not valid in the Enter Query mode. • Trigger statements that follow the call to OPEN_FORM built-in are never executed when a form is opened with the parameter specified as ACTIVATE. • While navigating between open forms, no validation occurs in the form that initiates the navigation. • While navigating between forms using the built-ins NEXT_FORM, PREVIOUS_FORM, or GO_FORM, no triggers fire except WHEN-WINDOW- DEACTIVATED trigger. • Read consistency and transaction management behavior for two forms in different sessions is the same as it is for the two clients with separate connections. • There are two issues that you need to consider when forms are opened within the same session. They are Commit Processing and Savepoint and rollback processing. • While using OPEN_FORM with CALL_FORM, navigating programmatically to a disabled form in a call form stack is not allowed. • The form variables defined at design time to supply values of inputs required by a form at startup are known as parameters. • When you use OPEN_FORM, CALL_FORM, or NEW_FORM procedures to invoke a form, you can pass values for form parameters from the invoking form to the invoked form. • Some of the built-in subprograms used to create and manipulate parameter lists are CREATE_PARAMETER_LIST, DESTROY_PARAMETER_LIST, ADD_PARAMETER, GET_PARAMETER_ATTR and SET_PARAMETER_ATTR etc. • Form Parameters can be used only as input parameters. This means the invoked form cannot modify parameter values. Global Variables are invoked form can modify global variable values. • A record group is a data structure, which has a column-row framework that is similar to a database table. • Query record, Non-query record and Static record group are the three types of record groups from which Query record and the Static record groups are groups defined at design time. • POPULATE_LIST and RETRIEVE_LIST built-in functions are used to transfer information between list items and record groups.Confidential © SQL Star International Ltd. 339
  • 343. Lab Exercise 1. What are the different ways of calling a form? 2. Create a PRE-FORM to ensure that a global variable exits. 3. Create one new form module called TRANSACTION where Transaction details are displayed. 4. Create a button called OPEN in the BOOKXX form module in Book tab. 5. Now call this Transaction form from BOOK form when the user clicks on the OPEN button. 6. Save, compile and run the form. 7. Achieve the same functionality above by passing parameters between the modules.Confidential © SQL Star International Ltd. 340
  • 344. Chapter 19 Managing Menus Introduction to Menu Modules The Menu Editor Creating Menu Modules Menu Module Properties Menu Item Properties Menu Item Types Magic Items Command Types Menu Toolbars Pop-up Menus Controlling Menus Programmatically Menu SecurityConfidential © SQL Star International Ltd. 341
  • 345. ObjectiveAt the end of this chapter, you will be able to: Identify the components of the Menu module List various tools and functionality of Menu editor Create Menu modules Set Menu module properties using the property palette List various Menu item properties Learn about the Menu item types Know what are Magic items Describe Command types Create Menu toolbars Create Pop-up Menus Use menu built-ins for controlling Menus programmatically Implement Menu securityConfidential © SQL Star International Ltd. 342
  • 346. Introduction to Menu ModulesMenu module is a component of a Forms application. It has a hierarchicalstructure and provides an easy method to operate a Forms application.Form Builder has features that enable you to create customized menus for yourapplication.Menu Module ComponentsThe various components of a menu module are: Menu Menu exhibits as a pull-down menu, which consists of various options horizontally displayed under the application window title. In Forms, you can create the following three types of menus: Main menu: It is displayed horizontally in the menu bar. It organizes options that are also known as individual menus. Individual menu: It is displayed vertically below the main menu and contains menu items (options). Submenu: It is displayed vertically and to the right of the menu item that invoked it. Menu Item A menu item is defined as an option that can be chosen from a menu. Menu items have associated code to enable users to perform particular actions. Menu Toolbar A menu toolbar contains buttons having icons, each corresponding to individual menu items from the menu. You can create both horizontal and vertical toolbars.The following diagram depicts how the menu module components arehierarchically structured:Confidential © SQL Star International Ltd. 343
  • 347. Main Menu Menu Menu Menu Menu Item Item Menu Menu Menu Item Item ItemIndividual Menu Menu Menu Menu Item Item Item Submenu Menu Item The hierarchical structure of a menu is the same whether you create your own customized menu or use the default menu. The default menu: Is not a separate menu module. That is, it is not a workable file. A ready- made menu module (menudef.mmb) having same menu items as the default form menu is shipped along with Oracle Forms Developer. You can modify menudef.mmb menu module without worrying about changing the default form menu permanently because default menu is an internal component and not a file. Is internal to Oracle Forms Developer. A form module automatically uses the default menu that is built into every form module. Includes most of the standard commands such as editing, querying, navigating, etc. Can be replaced with a custom menu. The custom menu is saved as a separate module and is suffixed with .mmb. The structure of the default menu can be examined by opening the file menudef.mmb. The objects of the file can be viewed in the Object Navigator, once it is opened. The default menu options and their items are as below: Confidential © SQL Star International Ltd. 344
  • 348. Individual Menus Menu Items Action Save, Clear All, Print, Print Setup, Exit Edit Cut, Copy, Paste, Edit, Display List Query Enter, Execute, Cancel, Last Criteria, Count Hits, Fetch Next Set Block Previous, Next, Clear Record Previous, Next, Scroll Up, Scroll Down, Insert, Remove, Lock, Duplicate, Clear Field Previous, Next, Clear, Duplicate Help Help, Keys, List, Display Error, DebugThe Menu EditorForm Builder provides a graphical design area known as a Menu Editor toenable developers to design, layout, modify, and view menu modules along withtheir objects.The Menu Editor contains: A design area, which is similar to the one provided in the Layout Editor A drop down list to choose the object to be viewed A toolbar of icons to provide quick access to frequently used functionsThe tools provided in the Menu Editor toolbar are as follows: Tools Functionality Display Menu Enables you to choose from all the menus in your menu module Create Down Creates a menu item below the current one Create Right Creates a menu item to the right of the current one Switch Orientation Display the highest level menu vertically or horizontallyThere are two ways to invoke the Menu Editor: Double click the menu module icon in the Object Navigator. Select the Menu Editor option in the Tools menu;Confidential © SQL Star International Ltd. 345
  • 349. Tools->Menu Editor NOTE Invoking the Menu Editor causes the View and Navigator Form Builder menus to be replaced with a single menu, Menu.In the Menu Editor as shown below, you can expand or collapse individualmenus by clicking the arrow, which is to the right of the menu names. You candrag the entire menu by using the menu handle, which is a gray tab to the left ofeach menu name.When an item is selected in the Menu Editor (Save) , it causes that item to beselected in the Object Navigator (mnitSave). Similarly, an item selected in theObject Navigator causes it to be selected in the Menu Editor.Creating Menu ModulesTo create a menu, the first step is to add a new menu module using the ObjectNavigator. To do this: Select the Menus node in the Object Navigator and click the create icon or select File->New->Menu option Change the name of the menu to a desired name, say mnLib.After creating the module mnLib, you need to create menus and menu itemswithin it. This is done in the Menu Editor.Confidential © SQL Star International Ltd. 346
  • 350. Creating a Main MenuTo create a main menu, you need to: 18) Invoke the Menu Editor by double clicking mnLib module in the Object Navigator. 19) The Editor displays a single menu item MENU1 with a label <New_Item>. 20) Rename the label as Action. 21) Click the Create Right icon to create an additional menu item to the right. 22) Name the option as Edit. 23) Repeat steps 4 and 5 to create two more menu items namely Query and Sort By. 24) Return to the Object Navigator and change the menu name from MENU1 to mnMainMenuLib. The main menu mnMainMenuLib has the following menu items: Action Edit Query Sort ByThe following Menu Editor screen shows the above-mentioned menu itemscreated within the main menu mnMainMenuLib.After creating the main menu, you need to create individual menus for each ofthe menus.Creating Individual MenusTo create individual menus, you need to do the following: In the Menu Editor select the parent item in the main menu.Confidential © SQL Star International Ltd. 347
  • 351. Click the Create Down icon. Doing this creates an individual menu with the name ACTION_MENU in the Object Navigator. Change the label name to Save. At runtime it would appear as Save, specifying a one key access to it. That is, you can access the menu by a combination of [Alt]+[S]. Click the Create Down icon to add three more menu items to the Action menu, namely Clear, Separator, and Exit. Similarly create menu items for Edit, Query, and Sort By repeating step 2 to step 5. Create menu items: Cut, Copy, Paste, Separator, Editor, and List Of Values for the EDIT_MENU Enter Query, Execute Query, Image for the QUERY_MENU Names, IDs for the SORT_BY_MENUThe following Menu Editor screen shows the individual menus created:You can also specify the menu access key in the following way:The following screen of the Object Navigator shows the mnLib created alongwith its main menu mnMainMenuLib and individual menus ACTION_MENU,EDIT_MENU, QUERY_MENU and SORT_BY_MENU.Confidential © SQL Star International Ltd. 348
  • 352. Creating SubmenusTo create a submenu, you need to: Select the menu item from an individual menu for which a submenu is required. For example, select mnitNames menu item from the SORT_BY_MENU. Click the Create Right icon and rename the default label as Member Names. Click the Create Right icon to create another item to the submenu, and rename the label as Book Names.The form module frmLib continues to use the default menu. In order to use thecustomized menu, you need to first save it and then attach it to the form module.Saving a Menu ModuleThe menu module definition can be saved as: A file with .mmb extension, which is a binary representation of the menu module definition. This binary file is portable between operating systems. A database table, which is a table representation of the menu module definition. This is portable between databases.To save the menu module mnLib as a binary file, click the Save icon in theObject Navigator or select Save option from the File menu.Confidential © SQL Star International Ltd. 349
  • 353. Either of these actions creates a file with .mmb extension. However, to usemnLib you need to create an executable version of the saved file. This is done byselecting the File menu->the Administration option->the Compile File option.This creates a file with extension .mmx. Then it is this file that you will attach tothe form module. This executable file is not portable between operating systems.Attaching a Menu ModuleIn order to use a created menu, you need to attach it to your form module.Attaching a menu module to a form module replaces the default menu.The steps to attach a menu module, say mnLib to a form module, frmLib are: 29. Select the form module frmLib to which the menu module mnLib is to be attached. 30.Invoke the form module Property Palette. 31. Change the Menu Module property to mnLib. Enter the entire file path along with the file name, if you have saved the menu module somewhere other than the default path. 32. Ensure that the Menu Source property value is either ‘File’ if menu module is saved in the file system or ‘Database’ if menu module is saved in the database.Setting Menu PropertiesThe menu module created does not serve any purpose because the functionalityof its menu items has not been set. The functionality is set in the PropertyPalette.Menu Module PropertiesOn invoking the Property Palette of the menu module mnLib, the followingproperties are displayed:Confidential © SQL Star International Ltd. 350
  • 354. The functionality of these properties is described below: Main Menu: Specifies the individual menu name in the menu module that is the main or starting menu. In case of a pull-down menu, the name of the first menu you create is specified automatically as the main menu. In the menu hierarchy, you cannot navigate above this menu. Menu Directory: Specifies the path, which Forms uses as an indicator to the directory for the .mmx file.This property is to be specified if the menu module is saved to the database. Menu Filename: Specifies the filename, which Forms uses as an indicator to the runtime .mmx file.This property is to be specified if the menu module is saved to the database. Startup Code: Specifies the PL/SQL code that gets executed when the menu module is loaded in memory. Share Library with Form: Specifies whether a single copy of a PL/SQL library is to be loaded in memory, if both the form module and the menu module use the same library.Confidential © SQL Star International Ltd. 351
  • 355. Use Security: Setting the property to ‘Yes’ cause security to be enforced at runtime. Module Roles: Displays the Menu Module Roles dialog box. You can list the roles assigned to the menu module. The roles listed must be assigned to individual menu items in the Menu Editor. Assigning of module roles is covered in a later section.On invoking the Property Palette of the individual menus created, such asACTION_MENU, the following properties are displayed:The only functional property of a menu is Tear-Off Menu property. This propertyis set to enable the menu to be repositioned (that is, change its positioning) onthe screen. However, this property is functional only if your window managersupports this feature.Menu Item PropertiesOn invoking the Property Palette of a menu item, such as the menu itemmnitSave of individual menu ACTION_MENU, the following properties aredisplayed:Confidential © SQL Star International Ltd. 352
  • 356. The uses of these properties are described below: Property Name Used to: Enabled Determine whether the menu item is available and can be manipulated by mouse or is it disabled.Confidential © SQL Star International Ltd. 353
  • 357. Property Name Used to: Label Specify the menu item text that appears on the screen. Menu Item Type Control how the menu item is to be displayed, i.e. whether it should be of type ‘Plain’, ‘Check’, ‘Radio’, ‘Separator’, or ‘Magic’. Magic Item Specify that the item should implement predefined properties for ‘Cut’, ‘Copy’, ‘Paste’, etc. Menu Item Radio Specify the radio group to which the menu item belongs Group Command Type Specify the type of command the menu item invokes, i.e. whether ‘Null’, ‘Menu’, ‘PL/SQL’, or ‘SQL*PLUS’. Menu Item Code Specify the code the menu item invokes Submenu Name Specify the submenu item invoked by the menu item Keyboard Specify which function key is associated with the menu Accelerator item Icon in Menu Specify whether an icon is to be displayed in the menu item Icon Filename Specify the filename of the icon to be displayedMenu Item TypesThe menu item type of all the menu items created is set to ‘Plain’ by default. Inaddition to that, Form Builder also supports four types of menu item types thatyou can specify to customize your menu items. They are: Menu Item Type Function Plain Standard text menu item (default item type) Check Boolean menu item having two states, i.e. the user can check the item ON or OFF. Its functionality is defined using PL/SQL Radio Boolean menu item that is one of the choice within a set of mutually exclusive choices. To assign an item as a radio item, specify the radio group name. Separator Creates a separating line to group menu items.Confidential © SQL Star International Ltd. 354
  • 358. Menu Item Type Function Magic Assigns predefined functionality to menu itemsThe menu item Property Palette displays the above mentioned item types asfollows:Magic ItemsMagic items provide the standard Graphical User Interface (GUI) actions. Most ofthe magic items include default functionality. Therefore, actions such as copy orpaste are already defined. Users need to only set the item type to ‘Magic’ andspecify the required action to be performed.Confidential © SQL Star International Ltd. 355
  • 359. The menu item Property Palette displays the following magic items:The default functionality and the associated command types of the various magicitems are as follows: Magic Items Command Type Default Functionality?Confidential © SQL Star International Ltd. 356
  • 360. Magic Items Command Type Default Functionality? Cut Null Yes. Items perform the default function indicated by their names Copy Paste Clear Undo Any except Menu No. Items perform the desired actions on being assigned commands to do the same About Help Menu No. Submenus must be created for HELP magic item and commands must be assigned to them. Quit Null Yes. This command, by default exits from the form after prompting the user to save any changes. Window Null or Menu Yes. This item by default invokes a submenu that contains all open windows. Selecting it from the submenu can activate a window.Command TypesMenu items perform actions based on the commands specified for them. Thecommand type of most of the menu items is PL/SQL, as they execute PL/SQLcommands. A valid command type must be associated with every menu item.The different command types available to choose from are as follows: Null: No command is to be associated with the item. Mostly used with separator menu items or magic items having default functionality. Menu: If a menu item invokes submenus, its command type must be defined as ‘Menu’. For example, the command type of all the items on a main menu must be defined as ‘Menu’. In such a case the Menu Item Code property is replaced by Submenu Name property as can be seen in the following property palette of Action menu of main menu:Confidential © SQL Star International Ltd. 357
  • 361. NOTE ‘Plus’, ‘Macro’, and ‘Form’ command types are available only for backward compatibility.Confidential © SQL Star International Ltd. 358
  • 362. 54. PL/SQL: Executes a PL/SQL block including the use of built-in or user- defined subprograms Plus: The code initializes an SQL*PLUS process.The command associated with a menu item can be viewed either by: Double-clicking the menu item icon in the Object Navigator. Clicking the Menu Item Code in the menu item Property Palette. Selecting PL/SQL Editor from the pop-up menu by right clicking the menu item in the Object Navigator or Menu Editor. Now that you are familiar with the various menu item types and command types, you can set these properties for the menu items created within mnLib menu module in the following way: Invoke the PL/SQL Editor for any menu item, say mnitSave Enter the code as follows:Confidential © SQL Star International Ltd. 359
  • 363. Similarly enter the code for all the remaining menu items. The PL/SQL code for the menu item mnitMember_Names is as follows:Confidential © SQL Star International Ltd. 360
  • 364. Menu Item PL/SQL Code Save do_key(‘Commit_Form’); Exit do_key(‘Exit_Form’); Clear do_key(‘Clear_Form’); do_key(‘Clear_Item’); do_key(‘Clear_Field’); do_key(‘Clear_Block’); Editor do_key(‘Edit’); Display List do_key(‘List_Values’); Enter Query do_key(‘Enter_Query’); Execute Query do_key(‘Execute_Query’); Insert do_key(‘Create_Record’); Remove do_key(‘Delete_Record’); Help do_key(‘Help’); do_key(‘Show_Keys’);Menu ToolbarsA set of buttons with icons representing menu items is known as a menu toolbar.Menu toolbars enable developers to create shortcuts to menu commands withoutduplicating code.You can decide the menu toolbar orientation, i.e. whether to assign menu itemsto a horizontal or vertical menu toolbar. A horizontal menu toolbar is locatedbeneath the main menu and a vertical menu toolbar is located to the left of aform.The following menu item properties need to be set in order to create a menutoolbar:Confidential © SQL Star International Ltd. 361
  • 365. Property Name FunctionVisible in Horizontal Specifies that the menu item represented by an iconMenu Toolbar must appear on the horizontal menu toolbar.Visible in Vertical Menu Specifies that the menu item represented by an iconToolbar must appear on the vertical menu toolbar.Icon Filename Specifies the filename of the icon that is to be used to represent menu items (ICO file). In case of a Web-deployed form, specify a GIF file. For example, to set the above properties for the following menu items perform the following steps: • Invoke the menu item mnitSave Property Palette. • Set the Visible in Horizontal Menu Toolbar and Icon Filename properties in the menu item Property Palette. • Similarly, set the above properties for the remaining menu items. When the form is run, the menu toolbar is displayed as follows: In addition to creating menu modules, you can also create pop-up menus. Confidential © SQL Star International Ltd. 362
  • 366. Pop-up MenusPop-up menus also known as context-sensitive menus belong to a form module,unlike form menus that belong to a separate menu module. Pop-up menus (likealerts, blocks, canvases, etc) are also top-level objects in the Object Navigator.Pop-up menus enable users to access commonly used functions and commands.Pop-up menus appear at the location on the screen where they were invoked andcan be accessed by: Attaching them to an item or a canvas Right clicking that item or canvasCreating Pop-up MenusThe steps involved in creating pop-up menus are: 1. Select the Pop-up Menu node in the Object Navigator and click the Create icon. A pop-up menu with a default name such as MENU1 gets created. Rename it to pmnLib. 2. Create a main pop-up menu with menu items and submenus (if needed) in the Object Navigator or Menu Editor. 3. Assign appropriate commands to the menu items, which could be of type PLAIN, CHECK, RADIO, SEPARATOR, or MAGIC. Attach the pop-up menu to any of the data block items or canvas by specifying the pop-up menu name in the Pop-up Menu Property. NOTE In order to show the pop-up menu for the canvas; the mouse must be on the canvas. You can use PRE-POPUP-MENU trigger to provide dynamic control of pop-up menus prior to their display.The following screen displays the frmLib form module runtime environment withthe pop-up menu:Confidential © SQL Star International Ltd. 363
  • 367. Confidential © SQL Star International Ltd. 364
  • 368. Controlling Menus ProgrammaticallyMenu modules created can be modified and controlled dynamically by usingPL/SQL codes and built-in subprograms.PL/SQL Code in Menu Item CommandsPL/SQL code in menu item commands is structured similar to form triggers. Theycan be used to perform any action, in addition to database interaction, validation,and navigation.The three ways to share code between form modules and menu modules are: Set up libraries and attach them to the modules. Create user-defined triggers and call them from a standard form module trigger or from a menu item in a menu module. Fire the user-defined trigger using EXECUTE_TRIGGER. Use DO_KEY built-in to fire the corresponding trigger from a menu item.Since menu modules are built independently of form modules, there are certainrestrictions involved in using PL/SQL codes in menu item commands. They are: Do not directly reference form module object values. Instead, use NAME_IN built-in function to obtain the current value of an object. For instance, IF: MEMBER.cGrade= ‘B’ THEN…invalid IF NAME_IN (‘MEMBER.cGrade’)= ‘B’ THEN……valid Do not set form module object values using direct assignment. Instead, use the COPY built-in procedure. For instance, : MEMBER.cFirstName: = ‘Ann’…invalid COPY (‘Ann’, ‘MEMBER.cFirstName’)…validBuilt-in Menu SubprogramsYou can use built-in menu subprograms in the PL/SQL codes written for eachmenu item to perform the following tasks: Modify certain menu characteristics dynamically at run time Obtain and change menu item properties Hide, display and replace the current menuThe built-in subprograms used to obtain and change menu item properties are:Confidential © SQL Star International Ltd. 365
  • 369. Built-in Subprograms DescriptionFIND_MENU_ITEM This function returns the internal ID of a menu item to a variable declared of type menu itemGET_MENU_ITEM_PROPERTY This function returns the state or current value of the specified menu item propertySET_MENU_ITEM_PROPERTY This procedure changes the value of the specified menu item propertyITEM_ENABLED This function returns ‘True’ if the menu item is enabled and ‘False’ if the menu item is disabledMENU_SHOW_KEYS This procedure shows the Keys screen for the menu module at runtime Using the above mentioned built-in subprograms, you can write the following PL/SQL code to find the ID of mnitImage of the mnQuery menu and check if it’s CHECKED property is ‘True’. If so, then set it as ‘False’ and vice versa. DECLARE idMenuItem MenuItem; BEGIN idMenuItem:=FIND_MENU_ITEM(‘mnQuery.mnitImage’); IF GET_MENU_ITEM_PROPERTY (idMenuItem, CHECKED)= ‘TRUE’ THEN SET_MENU_ITEM_PROPERTY (idMenuItem, CHECKED, PROPERTY_FALSE); ELSE SET_MENU_ITEM_PROPERTY (idMenuItem, CHECKED, PROPERTY_TRUE); END IF; END; The built-in subprograms used to replace, hide, and show the current menu are as follows: Confidential © SQL Star International Ltd. 366
  • 370. Built-in Subprograms Description REPLACE_MENU This procedure replaces the current menu with the menu specified, without activating it. The menu for all the windows in the application is replaced. HIDE_MENU This procedure hides the current menu. SHOW_MENU This procedure shows the current menu, without making it active MENU_REDISPLAY Redisplays the current menu on the screenMenu SecurityWhen you build a form module, it is automatically limited by the security enforcedby you on the Oracle server. However, you can also enforce client applicationsecurity. Therefore, Menu security implies setting up access rights on menuitems. There are two security policies to choose from: Granting users access to all the menu items in a module Granting users access to only specific menu items in a moduleThe above security policies are based on database roles. Once roles are defined inthe database, you can determine which roles are to access which menu items.Implementation of menu security occurs entirely within the menu module. Inorder to implement menu security, you need to perform the following three steps: 1. Set up the security function for the whole menu module. 2. Determine which roles have access to the whole menu module. 3. Determine which roles have access to each menu item.Security RolesThe menu module property Use Security helps determine whether menu securityis implemented or not. This property enables menu security to be disabledtemporarily without altering menu setting for each item.Setting this property ‘On’ is the first step in implementing menu security.To set this property: Invoke the Property Palette of the menu module, say mnLib in the Object Navigator. In the Menu Security node, locate the Use Security property and set its value to ‘Yes’.If this property is set as ‘No’, No security is enforced All menu items can be accessed by users Application can be tested without being a member of all rolesConfidential © SQL Star International Ltd. 367
  • 371. NOTE You must recompile the menu module in case Use Security property is modified.After having enabled the menu module security function, you need to definesecurity roles.For example, create roles to insert, delete and select, update and select, andselect as follows: CREATE ROLE Ins; CREATE ROLE DelSel; CREATE ROLE UpdSel; CREATE ROLE Sel;Grant privileges to the roles created and grant the roles to users such as: Grant Ins, DelSel, UpdSel, and Sel roles to user Member Grant Ins to user LibClerk Grant DelSel to user DeskOfficer1 Grant UpdSel to user DeskOfficer2 Grant Sel to user Librarian NOTE A database administrator can only create these roles. Developers do not have the required privileges to create the above-mentioned roles.Assigning Roles to Menu ModulesAfter defining different roles, you need to associate specific roles with differentmenu items. But, before you do this you need to inform the menu module as towhich of these roles will have access rights to its items. To do so, you need toperform the following steps: 11. Select the menu module mnLib in the Object Navigator. • Invoke its Property Palette • Double click the Module Roles property. It opens a dialog box. • Enter the names of the roles that should be able to access this menu • When finished, click OK.Confidential © SQL Star International Ltd. 368
  • 372. The Menu Module Roles property is as follows:Assigning Roles to Menu ItemsThe last step in implementing menu security is to determine which roles mayaccess each menu item. To assign roles to menu items: • Select the menu item in the Object Navigator or Menu Editor Invoke its Property Palette Select the Items Role property and double click it You will be presented with the list of roles you had assigned in the menu Module Roles property. Select the desired role from the list to access the menu item In order to specify how the item is to be displayed if the current user does not have access to it, set the Display without Privilege property to ‘Yes’, if the item is to be displayed and ‘No’, if the item is to be hidden.Confidential © SQL Star International Ltd. 369
  • 373. The Items Role dialog box is as follows:Confidential © SQL Star International Ltd. 370
  • 374. SummaryIn this chapter, you have learnt that: A menu item is defined as an option that can be chosen from a menu with Menu items having associated code to enable users to perform particular actions. Menu Filename specifies the filename, which Forms uses as an indicator to the runtime .mmx file. Startup Code, Share Library with Form, Use Security and Module Roles are to be specified if the menu module is saved to the database. Startup Code specifies the PL/SQL code that gets executed when the menu module is loaded in memory. The only functional property of a menu is Tear-Off Menu property, which is set to enable the menu to be repositioned on the screen. Menu modules created can be modified and controlled dynamically by using PL/SQL codes and built-in subprograms. Magic items provide the standard Graphical User Interface (GUI) actions out of which most of them include default functionality. The command type of most of the menu items is PL/SQL, as they execute PL/SQL commands. Null, Menu etc. are different command types available to choose from. Menu toolbar is a set of buttons with icons representing menu items and it enables developers to create shortcuts to menu commands without duplicating the code. Pop-up menus also known as context-sensitive menus belong to a form module, unlike form menus that belong to a separate menu module. Example- alerts, blocks, etc. Menu modules created can be modified and controlled dynamically by using PL/SQL codes and built-in subprograms. PL/SQL code in menu item commands is structured similar to form triggers, which can be used to perform any action, in addition to database interaction, validation, and navigation. You can also hide, display and replace the current menu by using built-in menu subprograms in the PL/SQL codes written for each menu item. Menu security implies setting up access rights on menu items. The two security policies, you have to choose are granting users access to all the menu items in a module and granting users access to only specific menu items in a module.Confidential © SQL Star International Ltd. 371
  • 375. Lab Exercise 1. Create a menu module with Action, Edit, Query, Block, Record, Field and About as the menu items. 2. Under the FILE_MENU, create two items namely Save and Exit. 3. Under the EDIT_MENU, create three items namely Cut, Copy and Paste. 4. Under the QUERY_MENU, create three items namely Enter, Execute and Cancel. 5. Under the BLOCK_MENU, create three items namely Previous, Next and Clear. 6. Under the RECORD_MENU, create five items namely Previous, Next, Insert, Remove, Clear. 7. Under the FIELD_MENU, create four items namely Previous, Next, Clear, Duplicate. 8. Under the ABOUT_MENU, create only one item namely forms10g. 9. Now after creating the menu write functionality to each and every item. 10. Now compile the menu and attach this menu module to the form module. Save, compile and run the form.Confidential © SQL Star International Ltd. 372