You are on page 1of 117

Oracle Forms Recipes

By Vinish Kapoor
Developing Oracle Applications since 2001
Contents
Map Columns From Different Tables and Create Insert and Update Statements in Oracle Forms ............. 3
Checking For User Permissions Before Updating or Inserting The Records in Oracle Forms ....................... 5
An Example of Pre-Query and Post-Query Triggers in Oracle Forms With Using Display_Item to Highlight
Dynamically ................................................................................................................................................... 7
Displaying Modal Window Messages in Oracle Forms Using Alerts ............................................................. 9
Get_File_Name Usage in Oracle Forms 6i .................................................................................................. 11
Creating, Stopping, Re-Starting and Deleting a Timer in Oracle Forms ...................................................... 13
Writing Text File From A Tabular Block In Oracle Forms ............................................................................ 16
Populating Tabular Data Block Manually Using Cursor in Oracle Forms .................................................... 18
If Value Exists Then Query Else Allow Create New in Oracle Forms An Example ....................................... 21
Trigger Execution Sequence Of Oracle Forms ............................................................................................ 23
Why And When To Use Pre-Update and Pre-Insert Triggers In Oracle Forms ........................................... 25
Some Useful Property Settings Explained Of Oracle Forms ....................................................................... 27
FRM-10001, FRM-10002, FRM-10003 Oracle Form Builder Error Solution ................................................ 30
Example of Get_File_Name Function in Oracle Forms ............................................................................... 31
Create Timer Example To Show Image Presentation in Oracle Forms ....................................................... 33
See also: Create timer to display clock in Oracle Forms ........................ Error! Bookmark not defined.
Moving From Top To Bottom in Detailed Block in Oracle Forms ............................................................... 35
Date Picker Calendar For Oracle Forms 6i .................................................................................................. 36
Download Form and required PLL ...................................................................................................... 36
How To Use ............................................................................................................................................. 36
Determining Current Block and Current Item in Oracle Forms .................................................................. 38
SYSTEM.CURSOR_BLOCK ........................................................................................................................ 38
SYSTEM.CURSOR_ITEM ........................................................................................................................... 38
View Oracle Developer Handbook at Amazon.com ............................................................................ 39
Adding Value To Combo List at Runtime in Oracle Forms .......................................................................... 40
Using GET_GROUP_SELECTION For Record Groups in Oracle Forms ......................................................... 42
Oracle Form Data Entry Sample .................................................................................................................. 44
Using User-Named Triggers in Oracle Forms .............................................................................................. 52
Giving Data Backup Option in Oracle Forms 6i ........................................................................................... 53
An Example of On-Error Trigger in Oracle Forms........................................................................................ 55
Shifting List Item Values From One List To Another In Oracle Forms ......................................................... 58
Using SYSTEM.MOUSE_ITEM In Oracle Forms............................................................................................ 60
Using Post_Query Trigger in Oracle Forms ................................................................................................. 62

1
Pre-Update and Pre-Insert Trigger Examples For Oracle Forms ................................................................. 64
Pre-Insert trigger ................................................................................................................................. 65
Handling Tab Pages in Oracle Forms........................................................................................................... 66
How To PLAY_SOUND in Oracle Forms ....................................................................................................... 68
Using Find_Alert and Show_Alert in Oracle Forms ..................................................................................... 69
How To Use RUN_PRODUCT In Oracle Forms............................................................................................. 71
How To Use FETCH_RECORDS In Oracle Forms .......................................................................................... 73
Writing On-Error Trigger In Oracle Forms................................................................................................... 76
How To Use DBLink In Oracle Forms 6i ....................................................................................................... 78
Solution - 1 .......................................................................................................................................... 78
Solution - 2 .......................................................................................................................................... 78
Highlighting Text Item On Entry In Oracle Forms ....................................................................................... 79
Steps to highlight current item ........................................................................................................... 79
Changing Icon File Of Push Button At Runtime In Oracle Forms 6i ............................................................ 81
Set Icon_File property in When-Mouse-Enter trigger ............................................................................ 81
Displaying Window In Center In Oracle Forms 6i ....................................................................................... 83
Populating Tree Item With Record Group In Oracle Forms ........................................................................ 84
Formatting Excel File Using Ole2 In Oracle Forms ...................................................................................... 86
Adding List Item Element At Runtime In Oracle Forms .............................................................................. 88
Populating Display Item Value On Query In Oracle .................................................................................... 89
Creating Custom Login Screen In Oracle Forms 10g ................................................................................... 90
Writing Text Files On The Client in Oracle Forms 10g ................................................................................ 92
Reading An Image File Into Forms From Client In Oracle Forms 10g ......................................................... 94
Number To Indian Rupee Words in Oracle Forms / Reports ...................................................................... 95
Creating Object Library OLB in Oracle D2k Form ........................................................................................ 98
Creating Excel File in Oracle Forms ........................................................................................................... 101
How To Tune or Test PLSQL Code Performance in Oracle D2k Forms...................................................... 105
Creating Dynamic LOV in Oracle D2k Forms ............................................................................................. 107
Using GET_APPLICATION_PROPERTY in Oracle D2k Forms ...................................................................... 112
Upload Files To FTP in Oracle Forms D2k.................................................................................................. 114

2
Map Columns From Different Tables and Create Insert and Update
Statements in Oracle Forms

This is one of my most needed tool to create Insert and Update statements using select
or alias from different tables where column mapping is difficult.

What this utility actually does is, suppose you have two table with too many columns
and you want to update or insert in one table from another, you know column names
but you want some visual interface so that your task can be easier. This tool provide
the same facility to create insert or update statement by visually mapping fields from
two tables.

The utility is created using Oracle Forms and can be used easily. Free download it
from Tablemap.fmx

Below is the screen shots of this tool:

3
4
Checking For User Permissions Before Updating or Inserting The
Records in Oracle Forms
Suppose you want to check the user permissions on inserting or updating the records in Oracle
Forms, then you can use Pre-Insert and Pre-Update triggers for that particular data block to check
whether user is having proper permission or not.

The example is given for HR schema and the following demo table is created for this:

Create Table User_Permissions (User_Name varchar2(50) Primary Key,


Can_Insert Varchar2(1) default 'N',
Can_Update Varchar2(1) default 'N')

Insert into User_Permissions values ('FORMUSER1', 'Y', 'N');

Commit;

Below is the screen shot for the examle:

5
You can download this form from the following link: Pre-Update-Insert.fmb

The following is the code written in Pre-Update trigger to check the permissions from the
database:

Declare
n_allow number;
begin
Select 1 into n_allow
from hr.user_permissions
where user_name = 'FORMUSER1'
and can_update = 'Y';
--- all is well if no exception raised else stop in exception area

exception
when others then
message('You have no permission to update the record.');
message('You have no permission to update the record.');
raise form_trigger_failure;
end;

The following is the code written in Pre-Insert trigger to check the permissions from
the database on Insert:

Declare
n_allow number;
begin
Select 1 into n_allow
from hr.user_permissions
where user_name = 'FORMUSER1'
and can_insert = 'Y';
--- all is well if no exception raised else stop in exception area

exception
when others then
message('You have no permission to insert the record.');
message('You have no permission to insert the record.');
raise form_trigger_failure;

end;

The code is written for Save button:

Commit_form;
6
An Example of Pre-Query and Post-Query Triggers in Oracle Forms With
Using Display_Item to Highlight Dynamically

Example is given for Pre-Query and Post-Query triggers in Oracle Forms, with
using Display_Item built-in in Post-Query triggers to highlight fields dynamically.

This is the screen shot below for this example:

You can also download this form from the following link: Query.fmb

The example is based on HR schema departments table. In this example Department


No. and Execute Query push button is in upper block named "Ctrl" block and below
block is the departments block. User will be asked to enter department no. in above

7
block and then to click on Execute Query button to filter the records below. The
filtration is handled in Pre-Query trigger and after execution of query the Manager
Name and Salary will be populated in Post-Query trigger by dynamically highlighting
the Manager Name using Display_Item built-in.

The following code written in Pre-Query trigger of Departments block to filter the
records:

if :ctrl.deptno is not null then


-- set default_where property of the block to the ctrl block item to filter the records
before query
set_block_property('departments', default_where, 'department_id = :ctrl.deptno');
end if;

The following code written in Post-Query trigger of Departments block to populate


non-database item fields and dynamically highlighting the Manager Name field:

begin
select first_name, salary into :departments.empname, :departments.sal
from hr.employees where employee_id = :departments.manager_id;
-- highlight as per your criteria
if :sal >= 10000 then
-- create highlight visual attribute with color of your choice to highlight
display_item('departments.empname', 'highlight');
else
-- create default1 visual attribute to restore to normal view
display_item('departments.empname', 'default1');
end if;
exception
when others then
null;
end;

The following code written in When-Button-Pressed trigger of Execute Query push


button in Ctrl block to execute query in Departments block:

go_block('departments');
set_block_property('departments', default_where, '');
execute_query;

8
Displaying Modal Window Messages in Oracle Forms Using Alerts

You can display modal windows in Oracle Forms to display normal messages, error message or
asking for confirmation eg. on deleting a record or saving a record etc.

These modal window messages can be shown using Alert option in Oracle forms.

This is the screen shot below for this example:

You can download this form from the following link: Modal_Msgt.fmb

For this example I have created three alerts with the following names:

1. Good_Msg

9
2. Error_Msg
3. Ask_Alert

The following code is written for "Show Good Message" button to display a normal message,
you can use this code in any PLSQL block:

Declare
-- create a numeric variable to hold show_alert return value
nalertbutton number;
Begin
-- set the message for alert
set_alert_property('good_msg', alert_message_text, 'Records saved successfully.');
-- after below statement the execution will hold till you click on ok.. becuase it is an modal
window
nalertbutton := show_alert('good_msg');
:alertblock.result := 'That was a good message.';
-- after this you can perform any task...
End;

The following code is written for "Show Error Message" button to display an Error message:

Declare
-- create a numeric variable to hold show_alert return value
nalertbutton number;
Begin
-- set the message for alert
set_alert_property('error_msg', alert_message_text, 'An error occurred.');
-- after below statement the execution will hold till you click on ok.. becuase it is an modal
window
nalertbutton := show_alert('error_msg');
:alertblock.result := 'That was an ERROR message.';
-- after this you can perform any task...
End;

The following code is written for "Ask Confirmation" button to ask for a
confirmation:

Declare
-- create a numeric variable to hold show_alert return value
nalertbutton number;
Begin
-- set the message for alert
set_alert_property('ask_alert', alert_message_text, 'Confirm Yes or No?');
-- after below statement the execution will hold till you click on ok.. becuase it is an
modal window

10
nalertbutton := show_alert('ask_alert');
-- now check which button or answer have been choosen
if nalertbutton = alert_button1 then
:alertblock.result := 'You choose Yes.';
else
:alertblock.result := 'You choose No.';
end if;
-- after this you can perform any task...
End;

Get_File_Name Usage in Oracle Forms 6i


Get_File_Name is built-in function of Oracle Forms 6i, used to get the file name with address by
browsing the file. You can browse a specific extension name file or with multiple extensions
using wild cards.

In this example I am showing three different usage of Get_File_Name function, one is given for
to get any Csv file name into a display field, second is given to read image files into an image
item and third is for sound item.

Below is the screen shot for this example:

11
You can also download this form from the following link: GetFileName.fmb

Write the following code on When-Button-Pressed trigger for Browse CSV Files button:

declare
filename varchar2(500);
begin
filename := GET_FILE_NAME(File_Filter=> 'CSV Files
(*.Csv)|*.Csv|');

:block2.txtfile := filename;

end;

Write the following code on When-Button-Pressed trigger for Upload Image button:

declare
filename varchar2(500);
begin
filename := GET_FILE_NAME(File_Filter=> 'Jpg Files
(*.jpg)|*.jpg|Gif Files (*.gif)|*.gif|All Files (*.*)|*.*|');

READ_IMAGE_FILE(filename, 'JPEG', 'block2.image9');

12
end;

Write the following code on When-Button-Pressed trigger for Browse Wave button:

declare
filename varchar2(500);
begin
filename := GET_FILE_NAME(File_Filter=> 'Wav Files
(*.wav)|*.wav|All Files (*.*)|*.*|');

READ_sound_FILE(filename, 'wave', 'block2.sound_item11');


play_sound('block2.sound_item11');
end;

Creating, Stopping, Re-Starting and Deleting a Timer in Oracle Forms


I have written many posts previously on Timers in Oracle Forms like how to change images
randomly with timers and how to display a clock using timer, but in this post I am simply
describing to how to create a timer, stop a timer, re-start a timer and deleting a timer.

The following is the screen shot for this example showing a progress bar based on a display item:

13
You can also download this form from the following link Timer.fmb

Create a display item with the following properties:

Name: Prgbar
Width: 5
Bevel: Plain
Background Color: blue

Write the following code for the "Create Timer" button:

When-Button-Pressed trigger
Declare
v_timer timer;
Begin
-- find timer first if already exists.
v_timer := find_timer('PrgBarTmr');
if id_null(v_timer) then
-- Creating timer for one second... one second = 1000 millisecond
v_timer := Create_Timer('PrgBarTmr', 1000, Repeat);
else
message('already exists.');
end if;

-- will handle this timer in form level when-timer-expired trigger


End;

Write the following code for the "Stop Timer" buton:

When-Button-Pressed trigger
Declare
v_timer timer;
Begin
-- find the timer first
v_timer := find_timer('PrgBarTmr');
if not id_null(v_timer) then
-- this will stop the timer after one millisecond
Set_Timer(v_timer, 1, No_Repeat);
14
end if;
-- will handle this timer in form level when-timer-expired trigger
End;

Write the following code for the "Re-Start Timer" buton:

When-Button-Pressed trigger
Declare
v_timer timer;
Begin
-- find the timer first
v_timer := find_timer('prgbartmr');
if not id_null(v_timer) then
-- this will re-start the timer after one second
Set_Timer(v_timer, 1000, Repeat);
else
v_timer := create_timer('prgbartmr',1000, Repeat);
end if;
-- will handle this timer in form level when-timer-expired trigger
End;

Write the following code for the "Delete Timer" buton:

When-Button-Pressed trigger
Declare
v_timer timer;
Begin
-- find the timer first
v_timer := find_timer('PrgBarTmr');
if not id_null(v_timer) then
-- this will delete the timer
Delete_Timer(v_timer);
end if;
End;

Then finally write the code for When-Timer-Expired trigger at form level to handle the timer and
to do specific task:

When-Timer-Expired trigger
Declare
v_timer_name varchar2(30);
v_width number;
Begin
-- get the timer name first.. to know which timer has expired.. if multiple timer are
running
v_timer_name := get_application_property(timer_name);
15
-- check if the same timer with capital letters
if v_timer_name = 'PRGBARTMR' then
v_width := get_item_property('blKtmr.prgbar', width);
if v_width < 100 then
v_width := v_width + 5;
else
v_width := 0;
end if;
set_item_property('blktmr.prgbar', width, v_width);
end if;

-- will handle this timer in form level when-timer-expired trigger


End;

Writing Text File From A Tabular Block In Oracle Forms

The example given below for writing text file or CSV using Text_IO package from a
tabular block in Oracle Forms.

16
Suppose there is a tabular grid data block "Job_History" in your forms and you want
to write a CSV on click of a button by reading whole block from top to bottom. The
following is the demo screen shot:

You can also download this form from this link Job_History_Csv.fmb.

Write the following When-Button-Pressed trigger code for the "Export To CSV"
button:

Declare
out_file text_io.file_type;
v_line varchar2(1000);
begin
out_file := text_io.fopen('C:\job_history.csv', 'w');
go_block('job_history');
-- move control to first record;
first_record;
loop
v_line := :job_history.employee_id||','|| :job_history.start_date||','||
:job_history.end_date ||','||
:job_history.job_id||','|| :job_history.department_id;
text_io.put_line(out_file, v_line);
-- move control to next record;
if :system.last_record = 'TRUE' then
exit;
end if;
next_record;
17
end loop;
text_io.fclose(out_file);
-- again after completion move control to first record
first_record;
end;

Populating Tabular Data Block Manually Using Cursor in Oracle Forms

18
Suppose you want to populate a non-database data block with records manually in Oracle forms.
This task can be done using a cursor.

Below is the example given for hr.job_history table, where user input the employee id in upper
block and click on the fetch button to populate the records from hr.job_history table into the
lower tabular data block.

The following is the screen shot for this example: (you can also download the form from this
link Job_History.fmb)

For the employee id field of upper block write the When-Validate-Item trigger code as below:

Begin
Select first_name||' '||last_name into :ctrl.ename from hr.employees
where employee_id = :ctrl.empid;
exception
when no_data_found then
message('Employee id does not exists');
raise form_trigger_failure;
End;

For the Fetch button write the When-Button-Pressed trigger code as below:

Declare
Cursor C_jobs
is
Select employee_id, start_date, end_date,
job_id, department_id
from hr.job_history
where employee_id = :ctrl.empid;
Begin

19
go_block('job_history');
-- first clear the block if it contains any records
clear_block(no_validate);
-- move control to first record;
first_record;
-- open the cursor and populate the block
for cur in C_jobs loop
:job_history.employee_id := cur.employee_id;
:job_history.start_date := cur.start_date;
:job_history.end_date := cur.end_date;
:job_history.job_id := cur.job_id;
:job_history.department_id := cur.department_id;
-- move control to next record;
next_record;
end loop;
-- again after completion move control to first record
first_record;

End;

20
If Value Exists Then Query Else Allow Create New in Oracle Forms An
Example

An example given below for Oracle Forms, when a value exists then execute
query for that value to display the correspondent record else allow user to create a
new record for that value.

The following is the example given for HR schema employee table, in this example
user will enter an empoyee id and if the employee id exists it will query the record
else allow user to create a new record, the trigger written on key-next-item trigger,
you can download the employees.fmb form also from the following
link employees.fmb

KEY-NEXT-ITEM trigger code


declare
v_empid employees.employee_id%type;
Begin
Select employee_id into v_empid
from hr.employees
where employee_id = :employees.employee_id;
-- value exists
-- set block property and execute query
clear_block(no_validate);

set_block_property('employees', default_where, 'employee_id = '||v_empid);


execute_query;
set_block_property('employees', default_where, '');
next_item;
exception
when no_data_found then
-- when not then clear block and allow to add new
v_empid := :employees.employee_id;
clear_block(no_validate);
:employees.employee_id := v_empid;
next_item;
End;

21
22
Trigger Execution Sequence Of Oracle Forms

Sequence of triggers fires on Commit.

1. KEY Commit
2. Pre Commit
3. Pre/On/Post Delete
4. Pre/On/Post Update
5. Pre/On/Post Insert
6. On commit
7. Post Database Commit

Sequence of triggers fires when Form is opened and closed.

On Open
1. Pre-Logon
2. On-Logon
3. Post-Logon
4. Pre-Form
5. When-Create-Record
6. Pre-Block
7. Pre-Record
8. Pre-Text-Item
9. When-New-Form-Instance
10. When-New-Block-Instance
11. When-New-Record-Instance
12. When-New-Item-Instance
On Close
1. Post-Text-Item
2. Post-Record
3. Post-Block
4. Post-Form
5. On-Rollback
6. Pre-Logout
7. On-Logout
8. Post-Logout

Sequence of triggers fires when Navigating from one item to another.

23
1. Key-next
2. Post Change
3. When validate
4. Post text
5. Pre text
6. When new item instance

24
Why And When To Use Pre-Update and Pre-Insert Triggers In Oracle
Forms
Whenever we commit after entering data in Oracle Forms, many triggers fires during this event
and also Pre-Update and Pre-Insert triggers fires just before inserting or updating the record into
table. We can write Pre-Update and Pre-Insert triggers on particular block to just allow the
process or to stop the process by using "Raise Form_Trigger_Failure" command, the following
are the some examples:

Suppose you have a data block and there is a field which need to be validate just before inserting
the record, then you must write the Pre-Insert trigger for this purpose, below is an example:

Declare
v_avl_qty number;
Begin
Select avl_qty into v_avl_qty
From stock_inhand
Where Item_Code = :Block1.item_code;
if v_avl_qty < :Block1.qty_issued then
Raise Form_Trigger_Failure;
--- Execution stopped...
end if;
--- Else insertion will take place...
End;

And now I am giving you another example, suppose there is a field which need to be
assigned from database just before the updation of the record, then you must write a
Pre-Update trigger for this purpose, below is an example:

Declare
v_value varchar2(10);
Begin
Select a_value into v_value
From a_table
Where b_value = :Block1.b_value;
--- Assign this value to block item
:Block1.a_value := v_value;
--- you can assign any others value to any field just before updation or insertion like:
:Block1.create_date := Sysdate;

25
Exception
when others then
--- After any error or no data found you still want to continue then you can use
only Null; statement
Null;
--- and any other value to any field you can still assign
:Block1.create_date := Sysdate;
End;

26
Some Useful Property Settings Explained Of Oracle Forms

In Oracle forms when we have two or more blocks and there is a requirement to join
them or make a relation between blocks then there are certain types of relation
properties available. You will find below the explanation of Master-Detail relation
properties and the triggers and procedures names which Oracle forms creates
automatically:

1. Master-Detail Relation (Triggers/Procedures/Properties)

(i) Isolated: - Masters Can be deleted when Child is existing


Triggers
On Populate details (created at block level)
On Clear Details (created at form level)
Procedures
Check Package Failure
Clear all master Detail
Query Master Detail
(ii) Non- Isolated: - Masters Cannot be deleted when Child is existing.
Triggers
On Populate details (created at block level)
On Check Delete master (created at block level)
On Clear Details (created at form level)
Procedures
Check Package Failure
Clear all master Detail
Query Master Detail
(iii) Cascading: - Child Record Automatically Deleted when Masters is deleted.
Triggers
On Populate details (created at block level)
Pre Delete (created at block level)
On Clear Details (created at form level)
Procedures
Check Package Failure
Clear all master Detail
Query Master Detail
---

27
There is also a property settings in relation to set the query behavior of relation
blocks. The following is the property settings and their meanings:

2.Various Block Co-ordination Properties

The various Block Coordination Properties are


a) Immediate
Default Setting. The Detail records are shown when the Master Record are shown.
b) Deffered with Auto Query
Oracle Forms defer fetching the detail records until the operator navigates to the
detail block.
c) Deferred with No Auto Query
The operator must navigate to the detail block and explicitly execute a query
---

A single canvas in Oracle forms can be converted into four types and each type has is
its different purpose. The following types of Canvases available in Oracle Forms:

3. Types of Canvases (Stacked/Content Difference)

(i) Content Canvas (Default Canvas) [A content canvas is the required on each
window you create]
(ii) Stack Canvas [you can display more then one stack canvas in a window at the
same time]
(iii) Tab Type Window [In Tab canvas that have tab pages and have one or more then
tab page]
(iv) Toolbar Canvas [A toolbar canvas often is used to create Toolbar Windows.
There are two type of Toolbar window.
a. Horizontal Toolbar Canvas: - Horizontal Toolbar canvases are displayed at the top
of the window, Just Under the Main Menu Bar.
b. Vertical Toolbar Canvas: - While vertical Toolbar are displayed along the Left
Edge of the window.

28
29
FRM-10001, FRM-10002, FRM-10003 Oracle Form Builder Error Solution

These errors occurred usually due to forms connection problem or some internal
problem, the solution is, close the form, re-connect to the database and then re-open
the form.

FRM-10001: Internal Error: TOS.


Cause: Internal system error.
Action: If the problem persists, contact Oracle Support Services.

FRM-10002: Unable to save the current module.


Cause: Internal system error.
Action: If the problem persists, contact Oracle Support Services.

FRM-10003: Unable to retrieve the module from the file.


Cause: Internal system error.
Action: If the problem persists, contact Oracle Support Services.

30
Example of Get_File_Name Function in Oracle Forms

Displays the standard open file dialog box where the user can select an existing file or
specify a new file.
Syntax
FUNCTION GET_FILE_NAME
(directory_name VARCHAR2,
file_name VARCHAR2,
file_filter VARCHAR2,
message VARCHAR2,
dialog_type NUMBER,
select_file BOOLEAN;

Returns VARCHAR2

Parameters
directory_name Specifies the name of the directory containing the file you want to
open. The default value is NULL. If directory_name is NULL, subsequent invocations
of the dialog may open the last directory visited.

file_name Specifies the name of the file you want to open. The default value is
NULL.

file_filter Specifies that only particular files be shown. The default value is NULL.
File filters take on different forms, and currently are ignored on the motif and
character mode platforms. On Windows, they take the form of Write Files
(*.WRI)|*.WRI| defaulting to All Files (*.*)|*.*| if NULL. On the Macintosh the
attribute currently accepts a string such as Text.

message Specifies the type of file that is being selected. The default value is NULL.

dialog_type Specifies the intended dialog to OPEN_FILE or SAVE_FILE. The


default value is OPEN_FILE.

select_file Specifies whether the user is selecting files or directories. The default
value is TRUE. If dialog_type is set to SAVE_FILE, select_file is internally set to
TRUE.
GET_FILE_NAME examples
/*
** Built-in: GET_FILE_NAME
** Example: Can get an image of type TIFF.

31
*/
DECLARE
filename VARCHAR2(256)
BEGIN
filename := GET_FILE_NAME(File_Filter=> ’TIFF Files
(*.tif)|*.tif|’);
READ_IMAGE_FILE(filename, ’TIFF’, ’block1.imagefld);
END;

32
Create Timer Example To Show Image Presentation in Oracle Forms

Suppose you want to change multiple images after a specified time in home screen of
your oracle forms application. Follow these simple steps to create image presentation
with create_timer:

(1) Place an image item on canvas and set the appropriate size and other properties for
image item.
(2) Create a parameter in object navigator with any name and the data type of the
parameter should be number type and specify the default value 1.
(3) You must have multiple images with name like image1.jpg, image2.jpg,
image3.jpg and so on.
(4) Then create when-new-form-instance trigger at form level and place the following
code:

Declare
tm timer;
begin
---- 3000 milliseconds = 3 seconds
create_timer('foxtimer', 3000, repeat);
end;

(5) Then create when-timer-expired trigger in form level and place the following
code:

begin
-- this will change the images in image item in every 3 seconds
read_image_file('C:\Documents and Settings\yourpc\My Documents\My
Pictures\image'||
:parameter.nprm||'.jpg', 'JPEG', 'block3.IMAGE7');
:parameter.nprm := :parameter.nprm + 1;
if :parameter.nprm > 10 then
:parameter.nprm := 1;
end if;
end;

33
34
Moving From Top To Bottom in Detailed Block in Oracle Forms

Suppose you want to scan a tabular grid block (detail block) from top to bottom in
Oracle forms. You can do this task by using :system.last_record system variable to
determine whether it is last record in a block and then exit.

Example:

Begin
go_block('yourblock');
--- then move to first record
first_record;
Loop
--- do some processing
null;
if :system.last_record = 'TRUE' then
exit;
End if;
next_record;
End Loop;
--- after exiting move to top
first_record;
End;

35
Date Picker Calendar For Oracle Forms 6i
Giving date picker calendar option to user for date type fields in Oracle Forms. I am providing
you the form (FoxCal.Fmx) and two libraries (General.plx and Calendar.pll). You can download
these files by clicking below link:
Download Form and required PLL

How To Use
It is very simple to use, no need to attache any library to your form, just copy all three files to
your current working directory of your application. Suppose you have a form and there is one or
many date date type fields in the form. You have to create key-listval trigger for those date type
fields or create a push button adjacent to those fields and paste the below code in when-button-
pressed trigger:

DECLARE
pl_id paramList;
begin
:GLOBAL.G_LOV_DATE := TRUNC(SYSDATE);
pl_id := Get_Parameter_List('foxcal');
IF NOT Id_Null(pl_id) THEN
destroy_parameter_list(pl_id);
end if;
pl_id := create_parameter_list('foxcal');
add_parameter(pl_id, 'XPOS', text_parameter, to_char(50));
add_parameter(pl_id, 'YPOS', text_parameter, to_char(100));
add_parameter(pl_id, 'CURRDATE', text_parameter, to_char(Sysdate));
add_parameter(pl_id, 'Label', text_parameter, 'Date Picker');
CALL_FORM('foxcal', no_hide, do_replace, query_only, no_share_library_data, pl_id);
:yourdateitem := :Global.G_LOV_Date;
erase('Global.G_LOV_DATE');
END;

Note: Your current working directory for form designer and


runtime should be the directory where you copied the above
mentioned three files.

36
37
Determining Current Block and Current Item in Oracle Forms

SYSTEM.CURSOR_BLOCK
Determining current block in Oracle Forms Using SYSTEM.CURSOR_BLOCK
system variable. The value that the SYSTEM.CURSOR_BLOCK system variable
represents depends on the current
navigation unit:
If the current navigation unit is the block, record, or item (as in the Pre- and Post-
Item, Record, and Block triggers), the value of SYSTEM.CURSOR_BLOCK is the
name of the block where the cursor is located. The value is always a character string.
If the current navigation unit is the form (as in the Pre- and Post-Form triggers), the
value of SYSTEM.CURSOR_BLOCK is NULL.

SYSTEM.CURSOR_BLOCK examples

Assume that you want to create a Key-NXTBLK trigger at the form level that
navigates depending on what the current block is. The following trigger performs this
function, using :SYSTEM.CURSOR_BLOCK stored in a local variable.

DECLARE
curblk VARCHAR2(30);
BEGIN
curblk := :System.Cursor_Block;
IF curblk = ’ORDERS’
THEN Go_Block(’ITEMS’);
ELSIF curblk = ’ITEMS’
THEN Go_Block(’CUSTOMERS’);
ELSIF curblk = ’CUSTOMERS’
THEN Go_Block(’ORDERS’);
END IF;
END;

SYSTEM.CURSOR_ITEM
Determining current item using System.Cursor_Item in Oracle Forms.
SYSTEM.CURSOR_ITEM represents the name of the block and item, block.item,
where the input focus (cursor) is located.The value is always a character string.

Usage Notes

38
Within a given trigger, the value of SYSTEM.CURSOR_ITEM changes when
navigation takes place. This differs from SYSTEM.TRIGGER_ITEM, which remains
the same from the beginning to the end of single trigger.

SYSTEM.CURSOR_ITEM examples
Assume that you want to create a user-defined procedure that takes the value of the
item where the cursor is located (represented by SYSTEM.CURSOR_VALUE), then
multiplies the value by a constant, and then reads the modified value into the same
item. The following user-defined procedure uses the COPY built-in to perform this
function.

PROCEDURE CALC_VALUE IS
new_value NUMBER;
BEGIN
new_value := TO_NUMBER(:System.Cursor_Value) * .06;
Copy(TO_CHAR(new_value), :System.Cursor_Item);
END;
View Oracle Developer Handbook at Amazon.com

39
Adding Value To Combo List at Runtime in Oracle Forms

You want to add a value in Combo List item in Oracle Forms, by typing it in combo
list box text area. Here is the example is given for the same, you can write following
block in When-Validate-Item trigger for the combo box item:

Write the following code in When-Validate-Trigger of combo box:

DECLARE
total_list_count Number (10);
loop_index_var Number (10) := 1;
list_element Varchar2 (50);
list_element_value Varchar2 (50);
list_element_to_add Varchar2 (50);
list_value_to_add Varchar2 (50);
element_match Varchar2 (5) := 'FALSE';
value_match Varchar2 (5) := 'TRUE';
list_id item := Find_item ('YOURBLOCK.COMBOLIST1');
BEGIN
total_list_count := Get_list_element_count (list_id);
List_element_to_add := :YOURBLOCK.COMBOLIST1;

For I In 1 .. TOTAL_LIST_COUNT
LOOP
list_element := Get_list_element_value (list_id, loop_index_var);
loop_index_var := loop_index_var + 1;

IF list_element_to_add = list_element
Then
element_match := 'TRUE';
END IF;

EXIT When list_element = list_element_to_add;


END LOOP;

list_value_to_add := list_element_to_add;

IF element_match = 'FALSE'
Then
Add_list_element (list_id, total_list_count + 1, list_element_to_add,
list_value_to_add);

40
END IF;

--- element added...

EXCEPTION
When form_trigger_failure
Then
RAISE;
When Others
Then
Message (SQLERRM);
END;

41
Using GET_GROUP_SELECTION For Record Groups in Oracle Forms

Retrieves the sequence number of the selected row for the given group. Suppose you
want to get a particular column value from a record group for the all rows or for
particular rows, then you can use get_group_selection built-in to perform the task.

Example:

/*
Built-in: GET_GROUP_SELECTION Example: Return a comma-separated list
(string) of the selected part numbers from the presumed existent PARTNUMS record
group.
*/
FUNCTION Comma_Separated_Partnumbers
RETURN VARCHAR2 IS
tmp_str VARCHAR2(2000);
rg_id RecordGroup;
gc_id GroupColumn;
the_Rowcount NUMBER;
sel_row NUMBER;
the_val VARCHAR2(20);
BEGIN
rg_id := Find_Group(’PARTNUMS’);
gc_id := Find_Column(’PARTNUMS.PARTNO’);
/*
Get a count of how many rows in the record group have been marked as "selected"
*/
the_Rowcount := Get_Group_Selection_Count( rg_id );
FOR j IN 1..the_Rowcount LOOP
/*
Get the Row number of the J-th selected row.
*/
sel_row := Get_Group_Selection( rg_id, j );
/*
Get the (VARCHAR2) value of the J-th row.
*/
the_val := Get_Group_CHAR_Cell( gc_id, sel_row );
IF j = 1 THEN
tmp_str := the_val;
ELSE
tmp_str := tmp_str||’,’||the_val;

42
END IF;
END LOOP;
RETURN tmp_str;
END;

43
Oracle Form Data Entry Sample

I shared a data entry example form here in this post for Oracle Forms beginner
developers, so that they may take an idea to how to develop a simple data entry form
in Oracle Forms. The form can be fully modified.

Example is given for an emp table and other related tables. You can download
Emp.fmb form from Google drive by clicking here Emp.Fmb Form

To run this form you would require some tables in Payroll schema, so create a
user/schema with name Payroll and run the following script:

-- start
CREATE TABLE DESIG
(
DNAME VARCHAR2(60 BYTE)
);

CREATE TABLE DEPT


(
DNAME VARCHAR2(60 BYTE)
)
;

CREATE TABLE EMP


(
ECODE VARCHAR2(10 BYTE),
ENAME VARCHAR2(60 BYTE),
DESIG VARCHAR2(60 BYTE),
DEPT VARCHAR2(60 BYTE),
ADDR1 VARCHAR2(60 BYTE),
ADDR2 VARCHAR2(60 BYTE),
CITY VARCHAR2(30 BYTE),
STATE VARCHAR2(30 BYTE),
PINCODE VARCHAR2(6 BYTE),
PHONE VARCHAR2(30 BYTE),
DOJ DATE,
DOR DATE,
DOP DATE,

44
PFNO VARCHAR2(30 BYTE),
ESINO VARCHAR2(60 BYTE),
BASIC NUMBER(10) DEFAULT 0,
HRA NUMBER(10) DEFAULT 0,
CONV NUMBER(10) DEFAULT 0,
MEDC NUMBER(10) DEFAULT 0,
BONUS NUMBER(10) DEFAULT 0,
TEL NUMBER(10) DEFAULT 0,
OTHA NUMBER(10) DEFAULT 0,
CL NUMBER(3) DEFAULT 0,
EL NUMBER(5) DEFAULT 0,
SL NUMBER(3) DEFAULT 0,
PFA NUMBER(10) DEFAULT 0,
TDS NUMBER(10) DEFAULT 0,
TDSMB NUMBER(2) DEFAULT 0,
ADVTOTAL NUMBER(10) DEFAULT 0,
ADVDED NUMBER(10) DEFAULT 0,
BANKAC VARCHAR2(50 BYTE),
FY VARCHAR2(9 BYTE),
CP VARCHAR2(30 BYTE),
FYCP VARCHAR2(40 BYTE),
ESI NUMBER(10,2),
TDSDED NUMBER(10,2)
)
;

CREATE TABLE FYCPT


(
FY VARCHAR2(9 BYTE),
CP VARCHAR2(30 BYTE),
FYCP VARCHAR2(40 BYTE)
)
;

CREATE TABLE MNTRANS


(
TRANID NUMBER(10),
TRANDATE DATE,
ECODE VARCHAR2(10 BYTE),

45
ENAME VARCHAR2(60 BYTE),
NOOFABS NUMBER(3),
NOOFWD NUMBER(3),
NETBASIC NUMBER(10,2),
NETCONV NUMBER(10,2),
NETMED NUMBER(10,2),
NETBONUS NUMBER(10,2),
NETTEL NUMBER(10,2),
NETHRA NUMBER(10),
OT_HRS NUMBER(10),
OT_HRSAMT NUMBER(10,2),
OT_SAL NUMBER(10,2),
OTHER_A NUMBER(10),
GRS_SAL NUMBER(10,2),
PFA NUMBER(10),
ESIA NUMBER(10),
TDS NUMBER(10,2),
ADVI NUMBER(10),
OTH_DED NUMBER(10),
NETPAYABLE NUMBER(10,2),
CLT NUMBER(2),
ELT NUMBER(2),
SLT NUMBER(2),
TL NUMBER(2),
CAA VARCHAR2(1 BYTE),
FY VARCHAR2(9 BYTE),
CP VARCHAR2(30 BYTE),
FYCP VARCHAR2(40 BYTE),
FOR_MNTH VARCHAR2(20 BYTE),
FOR_YEAR NUMBER(4)
)
LOGGING
NOCOMPRESS
NOCACHE
NOPARALLEL
MONITORING;

SET DEFINE OFF;


Insert into DEPT

46
(DNAME)
Values
('COMMERCIAL');
Insert into DEPT
(DNAME)
Values
('MAINT & SUPPORT');
Insert into DEPT
(DNAME)
Values
('SYSTEMS');
Insert into DEPT
(DNAME)
Values
('OPERATIONS');
Insert into DEPT
(DNAME)
Values
('QUALITY CONTROL');
Insert into DEPT
(DNAME)
Values
('ACCOUNTS');
Insert into DEPT
(DNAME)
Values
('PACKING & DISPATCH');
Insert into DEPT
(DNAME)
Values
('ADMINISTRATION');
Insert into DEPT
(DNAME)
Values
('STORE');
Insert into DEPT
(DNAME)
Values
('MAINTENANCE');
Insert into DEPT
(DNAME)

47
Values
('DESIGNING');
Insert into DEPT
(DNAME)
Values
('PURCHASE & STORE');
COMMIT;

SET DEFINE OFF;


Insert into DESIG
(DNAME)
Values
('AGM');
Insert into DESIG
(DNAME)
Values
('CHIEF MANAGER');
Insert into DESIG
(DNAME)
Values
('SR. MANAGER');
Insert into DESIG
(DNAME)
Values
('MANAGER');
Insert into DESIG
(DNAME)
Values
('SCY. TO CMD & COMPLIANCE OFFICER');
Insert into DESIG
(DNAME)
Values
('DY. MANAGER');
Insert into DESIG
(DNAME)
Values
('ASST. MANAGER');
Insert into DESIG
(DNAME)
Values
('SR. EXECUTIVE');

48
Insert into DESIG
(DNAME)
Values
('EXECUTIVE');
Insert into DESIG
(DNAME)
Values
('OMR OPERATOR');
Insert into DESIG
(DNAME)
Values
('SR. ASSISTANT');
Insert into DESIG
(DNAME)
Values
('ASSISTANT');
Insert into DESIG
(DNAME)
Values
('MANAGER SYSTEMS');
COMMIT;

SET DEFINE OFF;


Insert into EMP
(ECODE, ENAME, DESIG, DEPT, ADDR1,
ADDR2, CITY, STATE, PINCODE, PHONE,
DOJ, DOR, DOP, PFNO, ESINO,
BASIC, HRA, CONV, MEDC, BONUS,
TEL, OTHA, CL, EL, SL,
PFA, TDS, TDSMB, ADVTOTAL, ADVDED,
BANKAC, FY, CP, FYCP, ESI,
TDSDED)
Values
('1000', 'ABC', 'xyz', 'abc', NULL,
NULL, 'NEW DELHI', 'DELHI', '110020', NULL,
TO_DATE('08/01/2010 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
'12345', '654123',
8000, 2500, 500, 1000, 5000,
500, 250, 7, 31, 8,
780, 1000, 5, 10000, 500,

49
'254252525632548', '2010-2011', 'LTD.', '2010-2011 INTERNATIONAL LTD.',
210,
NULL);
Insert into EMP
(ECODE, ENAME, DESIG, DEPT, ADDR1,
ADDR2, CITY, STATE, PINCODE, PHONE,
DOJ, DOR, DOP, PFNO, ESINO,
BASIC, HRA, CONV, MEDC, BONUS,
TEL, OTHA, CL, EL, SL,
PFA, TDS, TDSMB, ADVTOTAL, ADVDED,
BANKAC, FY, CP, FYCP, ESI,
TDSDED)
Values
('93', 'VINISH KAPOOR', 'MANAGER SYSTEMS', 'OPERATIONS', 'MARIYAM
NAGAR',
NULL, 'GHAZIABAD', 'UP', '110020', '9540377373',
TO_DATE('01/10/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
NULL, NULL,
10000, 4000, 1000, 1000, 5000,
1000, 2000, 7, 31, 8,
780, 2000, 2, 50000, 1000,
NULL, '2010-2011', 'INTERNATIONAL LTD.', '2010-2011 INTERNATIONAL
LTD.', 0,
NULL);
Insert into EMP
(ECODE, ENAME, DESIG, DEPT, ADDR1,
ADDR2, CITY, STATE, PINCODE, PHONE,
DOJ, DOR, DOP, PFNO, ESINO,
BASIC, HRA, CONV, MEDC, BONUS,
TEL, OTHA, CL, EL, SL,
PFA, TDS, TDSMB, ADVTOTAL, ADVDED,
BANKAC, FY, CP, FYCP, ESI,
TDSDED)
Values
('93993', 'VIN', 'AGM', 'ACCOUNTS', NULL,
NULL, 'NEW DELHI', 'DELHI', '110020', NULL,
TO_DATE('01/01/2000 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
NULL, NULL,
33333, 0, 0, 0, 0,
0, 0, 7, 31, 8,
780, NULL, 1, NULL, NULL,

50
NULL, 'FY', 'FY', 'FY', 0,
NULL);
COMMIT;

SET DEFINE OFF;


Insert into FYCPT
(FY, CP, FYCP)
Values
('2010-2011', 'INTERNATIONAL LTD.', '2010-2011 INTERNATIONAL LTD.');
COMMIT;

-- end

51
Using User-Named Triggers in Oracle Forms

A user-named trigger is a trigger defined in a form by the developer. User-Named


triggers do not automatically fire in response to a Form Builder event, and must be
called explicitly from other triggers or user-named subprograms. Each user-named
trigger defined at the same definition level must have a unique name.
To execute a user-named trigger, you must call the EXECUTE_TRIGGER built-in
procedure, as shown here:

Execute_trigger(’my_user_named_trigger’);

Usage Notes:
User-named PL/SQL subprograms can be written to perform almost any task for
which one might use a user-named trigger.
As with all triggers, the scope of a user-named trigger is the definition level and
below. When more than one user-named trigger has the same name, the trigger
defined at the lowest level has precedence.
It is most practical to define user-named triggers at the form level.
Create a user-named trigger to execute user-named subprograms defined in a form
document from menu PL/SQL commands and user-named subprograms. (User-named
subprograms defined in a form cannot be called directly from menu PL/SQL, which is
defined in a different document.) In the menu PL/SQL, call the
EXECUTE_TRIGGER built-in to execute a user-named trigger, which in turn calls
the usernamed subprogram defined in the current form.

52
Giving Data Backup Option in Oracle Forms 6i

Suppose you want to give the data backup option in Oracle Forms application to some
client users, where you have installed Oracle 11g client or direct from server.

The following procedure executes a batch file placed in current working directory of
the application and the batch file contains the following line:

exp.exe userid=%1 FULL=N FILE=%2

Means you have to pass two parameters to this batch file one is
username/password@connectstring and another is the filename with location. The
following procedure runs this batch file and passes the required parameters.

Example:

PROCEDURE DO_BACKUP IS
USERID VARCHAR2(50) := GET_APPLICATION_PROPERTY(USERNAME);
PSW VARCHAR2(50) := GET_APPLICATION_PROPERTY(PASSWORD);
CSTRING VARCHAR2(50) :=
GET_APPLICATION_PROPERTY(CONNECT_STRING);
fPathName varchar2(200);
BDIR VARCHAR2(1000);
DMPFILENAME VARCHAR2(100);
BEGIN
MESSAGE( 'Doing Backup...');
SYNCHRONIZE;
if bdir is null then
select BKPDIR into bdir
from URparam
where Pcode = 'BACKUP';
end if;
if Substr(bdir,length(bdir),1) != '\' then
bdir := rtrim(bdir) || '\';
end if;
bdir := ltrim(rtrim(bdir));
dmpfilename := to_char(sysdate, 'ddMONyy')||'_'||dbms_random.string('x', 5);
host('backup.bat '||USERID||'/'||PSW||'@'||cstRING||' '||bdir||dmpfilename);
exception
when others then
message('Please check parameters for the backup option.');

53
END;

Note: The connect string is used by oracle forms client should be the same as oracle
11g client or oracle servers connect string.

54
An Example of On-Error Trigger in Oracle Forms

I wrote this trigger around 4 years ago to handle errors in an application based on
Oracle Forms 6i. This trigger handles all errors with some custom messages for some
specific errors and not only this after giving an appropriate message to the user it logs
the error into a table named error_log, so that a DBA can view all the errors with their
execution time, user and program information. See the example below:

On-Error Trigger code:

declare
vabutton number;
verrtxt varchar2(80) := error_text;
verrno number := error_code;
vdbms number := dbms_error_code;
verrtype varchar2(20) := error_type;
begin
if vdbms = -3114 or vdbms = -1017 or vdbms = -3115 or vdbms = -1012 then
-- logon related errors
set_alert_property('errmes', title, 'App '||ltrim(to_char(vdbms)));
set_alert_property('errmes', alert_message_text, 'Logon denied.');
vabutton := show_alert('errmes');
raise form_trigger_failure;
end if;
if verrno = 41009 OR VERRNO = 41008 or verrno = 40100 OR VERRNO =
40105 then
--- ignoring all errors like at first record etc.
NULL;
elsif verrno = 40509 then
insert into error_log (sqno, username, error_msg, error_cd, error_tp, error_dt,
LOCATION) values
(error_seq.nextval, :MAIN.USERNAME, verrtxt, verrno, verrtype, sysdate,
:SYSTEM.CURSOR_BLOCK);
frmsave;
set_alert_property('errmes', title, 'Info.'||ltrim(to_char(verrno)));
set_alert_property('errmes', alert_message_text, 'You cannot update records.');
vabutton := show_alert('errmes');
:main.er := :main.er + 1;
else
insert into hms.error_log (sqno, username, error_msg, error_cd, error_tp,
error_dt, LOCATION) values

55
(hms.error_seq.nextval, :MAIN.USERNAME, verrtxt, verrno, verrtype, sysdate,
:SYSTEM.CURSOR_BLOCK);
--- frmsave is the database procedure to commit explicitly.
frmsave;
set_alert_property('errmes', title, 'Info.'||ltrim(to_char(verrno)));
set_alert_property('errmes', alert_message_text, verrtxt);
vabutton := show_alert('errmes');
:main.er := :main.er + 1;
end if;
exception
when form_trigger_failure then
null;
when others then
-- FOR DEBUG NEXT LINE TO KNOW ERROR NUMBER
-- set_alert_property('errmes', alert_message_text,
'['||TO_CHAR(ERROR_CODE)||'] '||error_text);
insert into error_log (sqno, username, error_msg, error_cd, error_tp, error_dt,
LOCATION)values
(error_seq.nextval, :MAIN.USERNAME, verrtxt, verrno, verrtype, sysdate,
:SYSTEM.CURSOR_BLOCK);
frmsave;
set_alert_property('errmes', alert_message_text, error_text);
vabutton := show_alert('errmes');
:main.er := :main.er + 1;
end;

Error_Log Table structure:


1 SQNO NUMBER(10)
2 USERNAME VARCHAR2(20 BYTE)
3 ERROR_MSG VARCHAR2(200 BYTE)
4 ERROR_CD NUMBER(10)
5 ERROR_TP VARCHAR2(10 BYTE)
6 ERROR_DT DATE
7 LOCATION VARCHAR2(20 BYTE)

56
57
Shifting List Item Values From One List To Another In Oracle Forms

Suppose you have two T-List items in form and you want to shift element values
from one list to another in Oracle Forms, here is the example given below for the
same. Create two buttons also between list items as shown in picture in the bottom of
this blog. Create one button with label ">" and another with label "<".

When-button-pressed trigger code for button with label ">":

declare
n number;
vval varchar2(100);
begin
--- replace rightsidelist with your list name placed on right side
--- replace leftsidelist with your list name placed at left side
n := get_list_element_count('rightsidelist');
add_list_element('rightsidelist', n + 1, :leftsidelist, :leftsidelist);
--- delete element
n := get_list_element_count('leftsidelist');
for i in 1..n loop
vval := get_list_element_value('leftsidelist',i);
if vval = :leftsidelist then
delete_list_element('leftsidelist',i);
end if;
end loop;
end;

When-button-pressed trigger for button with label "<":

declare
n number;
vval varchar2(100);
begin
n := get_list_element_count('leftsidelist');
add_list_element('leftsidelist', n + 1, :rightsidelist, :rightsidelist);

--- delete element


n := get_list_element_count('rightsidelist');
for i in 1..n loop
vval := get_list_element_value('rightsidelist',i);
if vval = :rigtsidelist then

58
delete_list_element('rightsidelist',i);
end if;
end loop;
end;

See also: Create List Item In Oracle Forms

59
Using SYSTEM.MOUSE_ITEM In Oracle Forms

If the mouse is in an item, SYSTEM.MOUSE_ITEM represents the name of that item


as a CHAR value.
For example, if the mouse is in Item1 in Block2, the value for
SYSTEM.MOUSE_ITEM is :BLOCK2.ITEM1.

SYSTEM.MOUSE_ITEM is NULL if:


· the mouse is not in an item
· the operator presses the left mouse button, then moves the mouse
· the platform is not a GUI platform

SYSTEM.MOUSE_ITEM examples
/*
Example: Dynamically repositions an item if:
1) the operator clicks mouse button 2 on an item and
2) the operator subsequently clicks mouse button 2 on an area of the canvas that is
not directly on top of another item.
*/
DECLARE
item_to_move VARCHAR(50);
the_button_pressed VARCHAR(50);
target_x_position NUMBER(3);
target_y_position NUMBER(3);
the_button_pressed VARCHAR(1);
BEGIN
/* Get the name of the item that was clicked.
*/
item_to_move := :System.Mouse_Item;
the_button_pressed := :System.Mouse_Button_Pressed;
/*
If the mouse was clicked on an area of a canvas that is not directly on top of another
item, move the item to the new mouse location.
*/
IF item_to_move IS NOT NULL AND the_button_pressed = ’2’
THEN
target_x_position := To_Number(:System.Mouse_X_Pos);
target_y_position := To_Number(:System.Mouse_Y_Pos);
Set_Item_Property(item_to_move,position,
target_x_position,target_y_position);
target_x_position := NULL;

60
target_y_position := NULL;
item_to_move := NULL;
END IF;
END;

61
Using Post_Query Trigger in Oracle Forms

When a query is open in the block, the Post-Query trigger fires each time Form
Builder fetches a record into a block. The trigger fires once for each record placed on
the block’s list of records.

Usage Notes
Use a Post-Query trigger to perform the following tasks:
· populate control items or items in other blocks
· calculate statistics about the records retrieved by a query
· calculate a running total
· When you use a Post-Query trigger to SELECT non-base table values into control
items, Form Builder marks each record as CHANGED, and so fires the When-
Validate-Item trigger by default. You can avoid the execution of the When-Validate-
Item trigger by explicitly setting the Status property of each record to QUERY in the
Post-Query trigger. To set record status programmatically, use
SET_RECORD_PROPERTY.

Example
This example retrieves descriptions for code fields, for display in non-database items
in the current block.
DECLARE
CURSOR lookup_payplan IS SELECT Payplan_Desc
FROM Payplan
WHERE Payplan_Id =
:Employee.Payplan_Id;
CURSOR lookup_area IS SELECT Area_Name
FROM Zip_Code
WHERE Zip = :Employee.Zip;
BEGIN
/*
Lookup the Payment Plan Description given the Payplan_Id in the Employee Record
just fetched. Use Explicit Cursor for highest efficiency.
*/
OPEN lookup_payplan;
FETCH lookup_payplan INTO :Employee.Payplan_Desc_Nondb;
CLOSE lookup_payplan;
/*
Lookup Area Descript given the Zipcode in the Employee Record just fetched. Use
Explicit Cursor for highest efficiency.
*/

62
OPEN lookup_area;
FETCH lookup_area INTO :Employee.Area_Desc_Nondb;
CLOSE lookup_area;
END;

63
Pre-Update and Pre-Insert Trigger Examples For Oracle Forms

Pre-Update Fires during the Post and Commit Transactions process, before a row is
updated in Oracle Forms. It fires once for each record that is marked for update.

The following example writes a row into an Audit Table showing old discount and
new discount for a
given customer, including timestamp and username making the change.
DECLARE
old_discount NUMBER;
new_discount NUMBER := :Customer.Discount_Pct;
oper_desc VARCHAR2(80);
CURSOR old_value IS SELECT discount_pct FROM customer
WHERE CustId = :Customer.CustId;
BEGIN
/*
Fetch the old value of discount percentage from the database by CustomerId. We need
to do this since the value of :Customer.Discount_Pct will be the new value we’re
getting ready to commit and we want to record for posterity the old and new values.
We could use SELECT...INTO but choose an explicit cursor for efficiency.
*/
OPEN old_value;
FETCH old_value INTO old_discount;
CLOSE old_value;
/* If the old and current values are different, then we need to write out an audit record
*/
IF old_discount <> new_discount THEN
/* Construct a string that shows the operation of Changing the old value to the new
value. e.g.’Changed Discount from 13.5% to 20%’
*/
oper_desc := ’Changed Discount from ’||
TO_CHAR(old_discount)||’% to ’||
TO_CHAR(new_discount)||’%’;
/*
Insert the audit record with timestamp and user
*/
INSERT INTO cust_audit( custid, operation, username, timestamp )
VALUES ( :Customer.CustId,oper_desc,USER,SYSDATE );
END IF;
END;

64
Pre-Insert trigger
Pre-Insert Fires during the Post and Commit Transactions process, before a row is
inserted. It fires once for each record that is marked for insert.

Example
This example assigns a primary key field based on a sequence number, and then
writes a row into an
auditing table, flagging creation of a new order.
DECLARE
CURSOR next_ord IS SELECT orderid_seq.NEXTVAL FROM dual;
BEGIN
/* Fetch the next sequence number from the explicit cursor directly into the item in
the Order record. Could use SELECT...INTO, but explicit cursor is more efficient. */
OPEN next_ord;
FETCH next_ord INTO :Order.OrderId;
CLOSE next_ord;
/*
Make sure we populated a new order id ok...
*/
IF :Order.OrderId IS NULL THEN
Message(’Error Generating Next Order Id’);
RAISE Form_trigger_Failure;
END IF;
/*
Insert a row into the audit table
*/
INSERT INTO ord_audit( orderid, operation, username, timestamp)
VALUES ( :Order.OrderId,’New Order’,USER, SYSDATE );
END;

65
Pre-insert and Pre-update in Oracle Forms
Reviewed by Rasa on

Mar 24
Rating:
5

Handling Tab Pages in Oracle Forms

Handle tab pages in Oracle forms at runtime with When-Tab-Page-Changed trigger at


Form Level. This trigger Fires whenever there is explicit item or mouse navigation
from one tab page to another in a tab canvas.

Usage Notes
· Use a When-Tab-Page-Changed trigger to perform actions when any tab page is
changed during
item or mouse navigation.

66
· When-Tab-Page-Changed fires only when tab page navigation is explicit; it does
not respond to
implicit navigation. For example, the trigger will fire when the mouse or keyboard is
used to
navigate between tab pages, but the trigger will not fire if an end user presses [Next
Item] (Tab) to
navigate from one field to another field in the same block, but on different tab pages.
· When-Tab-Page-Changed does not fire when the tab page is changed
programmatically.

When-Tab-Page-Changed examples
Use a When-Tab-Page-Changed trigger to dynamically change a tab page’s label from
lower- to upper-case (to indicate to end users if they already have navigated to the tab
page)

DECLARE
tp_nm VARCHAR2(30);
tp_id TAB_PAGE;
tp_lb VARCHAR2(30);
BEGIN
tp_nm := GET_CANVAS_PROPERTY(’emp_cvs’, topmost_tab_page);
tp_id := FIND_TAB_PAGE(tp_nm);
tp_lb := GET_TAB_PAGE_PROPERTY(tp_id, label);
IF tp_lb LIKE ’Sa%’ THEN
SET_TAB_PAGE_PROPERTY(tp_id, label, ’SALARY’);
ELSIF tp_lb LIKE ’Va%’ THEN
SET_TAB_PAGE_PROPERTY(tp_id, label, ’VACATION’);
ELSE null;
END IF;
END;

67
How To PLAY_SOUND in Oracle Forms

Play_sound is used to play audio files in Oracle Forms, Play_Sound plays the sound
object in the specified sound item.

PLAY_SOUND examples
The following plsql block you can write in when-button-pressed trigger for a push
button item, when button clicked read a sound object from the file system and play it.

68
Note: since an item must have focus in order to play a sound, the trigger code includes
a call to the built-in procedure GO_ITEM:

BEGIN
IF :clerks.last_name = ’BARNES’ THEN
GO_ITEM(’orders.filled_by’);
READ_SOUND_FILE(’t:\orders\clerk\barnes.wav’,’wave’,’orders.filled_by’);
PLAY_SOUND(’orders.filled_by’);
END IF;
END;

Using Find_Alert and Show_Alert in Oracle Forms

Show_alert is used to display model window messages in Oracle Forms and


Find_alert searches the list of valid alerts in Form Builder, when the given alert is
located, the subprogram returns an alert ID. You must return the ID to an
appropriately typed variable, define the variable with a type of Alert.

69
Example
Show a user-warning alert. If the user presses the OK button, then make REALLY
sure they want to continue with another alert.

DECLARE
al_id Alert;
al_button NUMBER;
BEGIN
al_id := Find_Alert(’User_Warning’);
IF Id_Null(al_id) THEN
Message(’User_Warning alert does not exist’);
RAISE Form_trigger_Failure;
ELSE
/*
** Show the warning alert
*/
al_button := Show_Alert(al_id);
/*
If user pressed OK (button 1) then bring up another alert to confirm -- button
mappings are specified in the alert design
*/
IF al_button = ALERT_BUTTON1 THEN
al_id := Find_Alert(’Are_You_Sure’);
IF Id_Null(al_id) THEN
Message(’The alert named: Are you sure? does not exist’);
RAISE Form_trigger_Failure;
ELSE
al_button := Show_Alert(al_id);
IF al_button = ALERT_BUTTON2 THEN
-- do some task
Erase_All_Employee_Records;
END IF;
END IF;
END IF;
END IF;
END;

70
How To Use RUN_PRODUCT In Oracle Forms

Run_Product is used to run Oracle Reports (RDF/REP files) in Oracle Forms. It


invokes one of the supported Oracle tools products and specifies the name of the
71
module or module to be run. If the called product is unavailable at the time of the call,
Form Builder returns a message to the end user.
If you create a parameter list and then reference it in the call to RUN_PRODUCT, the
form can pass text and data parameters to the called product that represent values for
command line parameters, bind or lexical references, and named queries. Parameters
of type DATA_PARAMETER are pointers to record groups in Form Builder. You
can pass DATA_PARAMETERs to Report Builder and Graphics Builder, but not to
Form Builder.

Example:
Call a Report Builder report, passing the data in record group ’EMP_RECS’ to
substitute for the report’s query named ’EMP_QUERY’. Presumes the Emp_Recs
record group already exists and has the same column/data type structure as the
report’s Emp_Query query.

PROCEDURE Run_Emp_Report IS
pl_id ParamList;
BEGIN
/*
** Check to see if the ’tmpdata’ parameter list exists.
*/
pl_id := Get_Parameter_List(’tmpdata’);
/*
** If it does, then delete it before we create it again in
** case it contains parameters that are not useful for our
** purposes here.
*/
IF NOT Id_Null(pl_id) THEN
Destroy_Parameter_List( pl_id );
END IF;
/*
** Create the ’tmpdata’ parameter list afresh.
*/
pl_id := Create_Parameter_List(’tmpdata’);
/*
** Add a data parameter to this parameter list that will
** establish the relationship between the named query
** ’EMP_QUERY’ in the report, and the record group named
** ’EMP_RECS’ in the form.
*/
Add_Parameter(pl_id,’EMP_QUERY’,DATA_PARAMETER,’EMP_RECS’);

72
/*
**Pass a Parameter into PARAMFORM so that a parameter dialog
will not appear
**for the parameters being passing in.
*/
Add_Parameter(pl_id, ’PARAMFORM’, TEXT_PARAMETER, ’NO’);
/*
** Run the report synchronously, passing the parameter list
*/
Run_Product(REPORTS, ’empreport’, SYNCHRONOUS, RUNTIME,
FILESYSTEM, pl_id, NULL);
END;

How To Use FETCH_RECORDS In Oracle Forms

73
When called from an On-Fetch trigger, initiates the default Form Builder processing
for fetching records
that have been identified by SELECT processing.

FETCH_RECORDS examples
/*
** Built-in: FETCH_RECORDS
** Example: Perform Form Builder record fetch processing
during
** query time. Decide whether to use this built-in
** or a user exit based on a global flag setup at
** startup by the form, perhaps based on a
** parameter. The block property RECORDS_TO_FETCH
** allows you to know how many records Form Builder
** is expecting.
** trigger: On-Fetch
*/
DECLARE
numrecs NUMBER;
BEGIN
/*
** Check the global flag we set during form startup
*/
IF :Global.Using_Transactional_Triggers = ’TRUE’ THEN
/*
** How many records is the form expecting us to
** fetch?
*/
numrecs := Get_Block_Property(’EMP’,RECORDS_TO_FETCH);
/*
** Call user exit to determine if there are any
** more records to fetch from its cursor. User Exit
** will return failure if there are no more
** records to fetch.
*/
User_Exit(’my_fetch block=EMP remaining_records’);
/*
** If there ARE more records, then loop thru
** and create/populate the proper number of queried
** records. If there are no more records, we drop through
** and do nothing. Form Builder takes this as a signal that

74
** we are done.
*/
IF Form_Success THEN
/* Create and Populate ’numrecs’ records */
FOR j IN 1..numrecs LOOP
Create_Queried_Record;
/*
** User exit returns false if there are no more
** records left to fetch. We break out of the
** if we’ve hit the last record.
*/
User_Exit(’my_fetch block=EMP get_next_record’);
IF NOT Form_Success THEN
EXIT;
END IF;
END LOOP;
END IF;
/*
** Otherwise, do the right thing.
*/
ELSE
Fetch_Records;
END IF;
END;

75
Writing On-Error Trigger In Oracle Forms

Suppose you want to handle an error in oracle forms and want to display custom error
message for that error, but also you want to customize more for a particular error. For
example there are many fields in form with required property is set to TRUE for Not
Null check.

The example below shows the error handling in oracle forms with a specific Frm-
40202 error.

On-Error Trigger
Trigger Level - Form

Declare
error_item varchar2(50);
curr_item_label varchar2(100);
Begin
error_item := :system.trigger_item;
if error_type = 'FRM' and error_code = 40202 then
curr_item_label := get_item_property(error_item, prompt_text);
--- you can use alert also to show the message
message(curr_item_label || ' cannot be left blank.');
else
message(error_text);
--- visual attribute a_errors must exists or create your own
set_item_property(error_item, current_record_attribute, 'A_errors');
end if;
end;

76
77
How To Use DBLink In Oracle Forms 6i

You want to connect multiple databases in oracle forms to perform certain tasks, for
example you need to execute ddl or dml statements against databases but when you
try to use dblink it gives you error or suddenly quits from the oracle forms.

Solution - 1

You can create Database Synonyms for the objects which you want to access through
dblink in oracle forms. Suppose you want to execute a procedure from another
database, create a synonym for that procedure in current database and access it in
oracle forms.

Solution - 2
Use Exec_Sql package in oracle forms to access multiple database and to execute any
ddl and dml statements. A simple example is given below:

declare
cid exec_sql.conntype;
cursorid exec_sql.curstype;
begin
cid := exec_sql.open_connection('scott/tiger@db3');
cursorid := exec_sql.open_cursor(cid);
exec_sql.parse(cid, cursorid, 'drop table emp2 ', exec_sql.v7);
exec_sql.close_cursor(cid, cursorid);
exec_sql.close_connection(cid);
end;

78
Highlighting Text Item On Entry In Oracle Forms

It is very necessary to highlight the current cursor text item in data entry forms so that
a user can easily notice the current item.

Steps to highlight current item


1. Create a visual attribute and set the background color (as per your choice)
property as shown below:

2. Then write a When-New-Item-Instance trigger to specify the current visual


attribute to an item, with the following code.

When-New-Item-Instance Trigger Code:


-- first get if item type is text item
Begin
IF GET_ITEM_PROPERTY(:SYSTEM.CURSOR_ITEM, ITEM_TYPE) = 'TEXT
ITEM' THEN
-- you can take current item into global variable, it will help you in next trigger
:GLOBAL.CRITEM := :SYSTEM.CURSOR_ITEM;

-- specify the attribute you just created


79
SET_ITEM_PROPERTY(:SYSTEM.CURSOR_ITEM,
CURRENT_RECORD_ATTRIBUTE, 'RECATB');
-- high light the current item
END IF;
End;
3. Then write Post-Text-Item trigger to restore the default color of a text item.

Post-Text-Item Trigger Code:

Begin
IF :GLOBAL.CRITEM IS NOT NULL THEN
-- you can specify your normal color attribute here
SET_ITEM_PROPERTY(:GLOBAL.CRITEM,
CURRENT_RECORD_ATTRIBUTE, 'Default');
END IF;
End;
Now you can check the result by running your form.

80
Changing Icon File Of Push Button At Runtime In Oracle Forms 6i

Set Icon_File property in When-Mouse-Enter trigger


Suppose you are creating icon based menu system in Oracle Forms 6i and you want to
change icon when mouse over on any push button.

You can accomplish this task by writing form level trigger when-mouse-
enter and when-mouse-leave, here is the example:

Create a block, design accordingly and place push buttons as per the requirement and
set iconic property to yes and specify default icon file.

Then write when-mouse-enter trigger Form Level, this trigger will fire when-ever
mouse enter over on any item.
Declare
vMousetime varchar2(100) := lower(:system.mouse_item);
Begin
-- check for your button and specify the new icon
if vMouseitem = 'yourblock.urbutton1' then
set_item_property(vmouseitem, icon_file, 'onhover1');
elsif vmouseitem = 'yourblock.urbutton2' then
set_item_property(vmouseitem, icon_file, 'onhover2');
-- and so on for your all buttons
end if;
End;

Write when-mouse-leave trigger Form Level, this trigger will fire when-ever mouse
leave any item.

Declare
vMousetime varchar2(100) := lower(:system.mouse_item);
Begin
-- check for your button and restore the default icon
if vMouseitem = 'yourblock.urbutton1' then
set_item_property(vmouseitem, icon_file, 'default1');
elsif vmouseitem = 'yourblock.urbutton2' then
set_item_property(vmouseitem, icon_file, 'default2');
-- and so on for your all buttons
end if;
End;

81
Now you can test your menu.

82
Displaying Window In Center In Oracle Forms 6i

Center window automatically in Oracle Forms 6i, use the following procedure by
passing window name as parameter:

Example

PROCEDURE auto_centre (pwn in varchar2) IS


vw number := get_window_property(forms_mdi_window, width);
vh number := get_window_property(forms_mdi_window, height);
BEGIN
set_window_property(pwn, x_pos, (vw - get_window_property(pwn, width)) / 2);
set_window_property(pwn, y_pos, (vh - get_window_property(pwn, height)) / 2);
END;

83
Populating Tree Item With Record Group In Oracle Forms

The below plsql program unit could be used in a WHEN-NEW-FORM-INSTANCE


trigger to initially populate the hierarchical tree with data in Oracle forms.

DECLARE
htree ITEM;
v_ignore NUMBER;
rg_emps RECORDGROUP;
BEGIN
-- Find the tree itself.
htree := Find_Item(’treeblock.htree1’);
-- Check for the existence of the record group.
rg_emps := Find_Group(’emps’);
IF NOT Id_Null(rg_emps) THEN
DELETE_GROUP(rg_emps);
END IF;
-- Create the record group.
rg_emps := Create_Group_From_Query(’rg_emps’,
’select 1, level, ename, NULL, to_char(empno) ’ ||
’from emp ’ ||
’connect by prior empno = mgr ’ ||
’start with job = ’’PRESIDENT’’’);
-- Populate the record group with data.
v_ignore := Populate_Group(rg_emps);
-- Transfer the data from the record group to the hierarchical
-- tree and cause it to display.
Ftree.Set_Tree_Property(htree, Ftree.RECORD_GROUP, rg_emps);
END;

84
85
Formatting Excel File Using Ole2 In Oracle Forms

Below is the some useful commands of Ole2 to format excel file in Oracle Forms.

-- Change font size and name in ole2


-- Declare as cfont ole2.obj_type;
CFONT := OLE2.GET_OBJ_PROPERTY(CELL, 'Font');
OLE2.SET_PROPERTY(CFONT, 'Name','Calibri');
OLE2.SET_PROPERTY(CFONT, 'Bold',1);
OLE2.SET_PROPERTY(CFONT, 'Size',11);
ole2.release_obj(CFONT);
--
-- Changing number format with ole2
OLE2.SET_PROPERTY(cell, 'NumberFormat', '00,0,0,000.00');
--
-- Changing background color in ole2
-- Declare colour ole2.obj_type;
colour:=ole2.get_obj_property(cell, 'Interior');
ole2.set_property(colour, 'ColorIndex', 33);
-- Border color
colour:=ole2.get_obj_property(cell, 'Borders');
ole2.set_property(colour, 'ColorIndex', 1);
--

-- Wrapping text in ole2


86
args:=OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG(args, 2);
OLE2.ADD_ARG(args, 1);
cell:=OLE2.GET_OBJ_PROPERTY(worksheet, 'Cells', args);
ole2.set_property(cell, 'WrapText', 'True');
OLE2.DESTROY_ARGLIST(args);
--
-- Autofit columns in ole2
range := OLE2.GET_OBJ_PROPERTY( worksheet,'UsedRange');
range_col := OLE2.GET_OBJ_PROPERTY( range,'Columns');
OLE2.INVOKE( range_col,'AutoFit' );
OLE2.RELEASE_OBJ( range );
OLE2.RELEASE_OBJ( range_col );
--
-- Saving a excel file in ole2
args := OLE2.Create_Arglist;
filen := 'c:\myfile.xls';
OLE2.ADD_ARG(args,filen);
OLE2.INVOKE(workbook, 'SaveAs', args);
OLE2.DESTROY_ARGLIST(args);
--
See also: Create Excel File in Oracle
Forms http://foxinfotech.blogspot.com/2013/02/creating-excel-file-in-oracle-d2k-
forms.html

87
Adding List Item Element At Runtime In Oracle Forms

Add combo list / drop down list item element at runtime in Oracle forms.

Syntax

PROCEDURE ADD_LIST_ELEMENT
(list_name VARCHAR2,
list_index, NUMBER
list_label VARCHAR2,
list_value NUMBER);

Example

Declare
nElmntCount Number;
Begin
-- First count the total list element currently in list item
nElmntCount := Get_list_element_count('yourlist');
-- Then add it by adding + 1 to total count element
Add_list_element('yourlist', nElmntCount + 1, 'A Value', 'A Value');
End;

88
Populating Display Item Value On Query In Oracle

Write Post-Query trigger for the block you want to fetch the field value for display
item.

Example

Begin
Select Ename into :datablock.dspname
from emp
where ecode = :datablock.ecode;
-- Field dspname in datablock will be populated with the value
exception
when others then
-- you can ignore error
null;
End;

You can write multiple plsql blocks in post-query trigger for different tables.

89
Creating Custom Login Screen In Oracle Forms 10g

Below is the example plsql unit to validate login credentials and after successful
validation open a new form by passing some parameters to it, in Oracle forms 10g.
Create a form for custom login. Create text items for username and password etc. and
a login button. When user click on that login button call this plsql routine.

declare
vPassword fox_user.password%type; -- get a password field type from your user
master table
plid paramlist;
begin
-- check if username is null
if :appstart.usn is null then
error_message('User name must be entered.');
go_item('appstart.usn');
raise Form_Trigger_Failure;
end if;

90
-- check if password is null
if :appstart.psw is null then
error_message('Password must be entered.');
go_item('appstart.psw');
raise Form_Trigger_Failure;
end if;
select password into vpassword
from fox_user
where rtrim(userid) = rtrim(:appstart.usn);
-- decrypt password using your own encrypt / decrypt method.
-- below mentioned decrypt is a program unit i used
if :appstart.psw != decrypt(vpassword) then
error_message('Invalid Password for the user. Logon Denied!');
go_item('appstart.psw');
raise form_trigger_Failure;
end if;
-- if valid username and password then create parameter list to pass the calling form
plid := get_parameter_list('formdata');
if Not id_null(plid) then
Destroy_parameter_list(plid);
end if;
plid := Create_Parameter_list('formdata');
Add_parameter(plid, 'userid', text_parameter, :appstart.usn);
new_form('main', full_rollback, no_query_only, plid);
exception
when no_data_found then
error_message('Invalid Userid. Please enter valid userid and password. Logon
Denied!');
go_item('appstart.usn');
when too_many_rows then
error_message('Internal error...');
when others then
null;
end;

91
Writing Text Files On The Client in Oracle Forms 10g

Below is the example to write file on client in Oracle Forms 10g with webutil library
package.

Note: Webutil library must be attached to the form.

DECLARE
v_dir VARCHAR2(250) := 'c:\temp';
ft_tempfile CLIENT_TEXT_IO.FILE_TYPE;
92
begin
ft_tempfile := CLIENT_TEXT_IO.FOPEN(v_dir ||'\tempfile.txt','w');
CLIENT_TEXT_IO.PUT_LINE(ft_tempfile,'First line....');
CLIENT_TEXT_IO.PUT_LINE(ft_tempfile,'Second line....');
CLIENT_TEXT_IO.PUT_LINE(ft_tempfile,'Third line....');
CLIENT_TEXT_IO.FCLOSE(ft_tempfile);
END;

Writing Text Files in Oracle Forms 10g


Reviewed by Nisha Vats on

Mar 01
Rating:
93
4.5

Reading An Image File Into Forms From Client In Oracle Forms 10g

Below is the example to read an image file from client in Oracle Forms 10g with the
help of webutil library.

Note: Webutil library must be attached to the form.

DECLARE
v_file VARCHAR2(250):= CLIENT_GET_FILE_NAME('','',
'Gif Files|*.gif|JPEG Files|*.jpg|',
'Select a photo to upload',open_file,TRUE);

it_image_id ITEM := FIND_ITEM


('emp.photo');
BEGIN
CLIENT_IMAGE.READ_IMAGE_FILE(v_file,'',it_image_id);
END;

94
Number To Indian Rupee Words in Oracle Forms / Reports

Convert numbers to Indian Rupees format in Oracle Forms / Reports.

Create the below mention function in Oracle Forms / Reports and call it with passing
a number parameter.

FUNCTION INR_words( p_number In number, vFrDec varchar2 Default 'Paisa


Only')
RETURN varchar2 As
TYPE myArray Is Table Of varchar2(255);
TYPE myArray2 Is Table Of varchar2(255);
l_str myArray := myArray( '',
' Thousand ', ' Lac ',
' Crore ', ' Arab ',
' Kharab ', ' quintillion ',

95
' Sextillion ', ' Septillion ',
' Octillion ', ' Nonillion ',
' Decillion ', ' Undecillion ',
' Duodecillion ' );
l_str2 myArray2 := myArray2('Rs Paisa', '$ Pany');
l_num varchar2(50) Default Trunc( p_number );
l_dec varchar2(50) Default Substr(To_Char(p_number - Trunc(p_number),
'.99'),2);
l_return varchar2(4000);
j number := 3;
BEGIN
For i In 1 .. l_str.Count
LOOP
EXIT When l_num Is Null;
IF ( Substr(l_num, Length(l_num)-(j-1), j) <> 0 ) Then
l_return := To_Char(To_Date(
Substr(l_num, Length(l_num)-(j-1), j),'J' ), 'Jsp' ) || l_str(i) || l_return;
END IF;
l_num := Substr( l_num, 1, Length(l_num)-j );
j:=2;
END LOOP;
IF l_dec > 0 Then
l_return := rtrim(l_return) || ' and ' || rtrim(inr_words(Substr(l_dec,2), Null)) || ' ' ||
rtrim(Initcap(vFrdec));
END IF;
RETURN Replace(l_return, '-', ' ');
END;

96
97
Creating Object Library OLB in Oracle D2k Form

With following steps you can create Object Library (OLB) in Oracle D2k Forms.

Step - 1
Create a form in form builder and create objects like Data Block, Canvases, Windows,
Program Units etc. as shown in below image.

Step - 2

98
Then Highlight Object Groups node in object navigator and click on add button and
give any name. Then add the objects you created by draggig them into object group
you just created. As shown below.

Step - 3
Then Highlight Object Libraries node in object navigator and click on add and then
click on Library Tabs node and click on add. After that double click on that library tab
you just created. It will open in a new window then drag Object Group (MainGroup in
my example) to that window and then save it. As shown below.

99
Your object library is now created. Now you can add it to any form.

100
Creating Excel File in Oracle Forms

Below is the example to create an excel file in Oracle Forms.

Pass the Sql query string to the below procedure to generate an Excel file using Ole2
package.

PROCEDURE Create_Excel_File (CSQL Varchar2)


Is
source_cursor Integer;
l_colCnt Number Default 0;
l_descTbl Dbms_sql.desc_tab;
newval1 Varchar2 (4000);
application OLE2.OBJ_TYPE;
workbooks OLE2.OBJ_TYPE;
workbook OLE2.OBJ_TYPE;
worksheets OLE2.OBJ_TYPE;
worksheet OLE2.OBJ_TYPE;
colour OLE2.OBJ_TYPE;

cell OLE2.OBJ_TYPE;
RANGE OLE2.OBJ_TYPE;
range_col OLE2.OBJ_TYPE;
range_row OLE2.OBJ_TYPE;
args OLE2.LIST_TYPE;
rows_processed Number;
row_n Number;
VAL Varchar2 (100);
x Number;
filename Varchar2 (200);
BEGIN
BEGIN
source_cursor := Dbms_Sql.open_Cursor;
Dbms_Sql.parse (source_cursor, cSql, 2);
Dbms_Sql.describe_Columns (c => source_cursor, col_cnt => l_colCnt, desc_t =>
l_descTbl);
EXCEPTION
When Others
Then
Error_Message (SQLERRM);

101
RETURN;
END;

application := OLE2.CREATE_OBJ ('Excel.Application');


OLE2.SET_PROPERTY (application, 'Visible', 'False');
workbooks := OLE2.GET_OBJ_PROPERTY (application, 'Workbooks');
workbook := OLE2.GET_OBJ_PROPERTY (workbooks, 'Add');
worksheets := OLE2.GET_OBJ_PROPERTY (workbook, 'Worksheets');
args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG (args, 1);
worksheet := OLE2.GET_OBJ_PROPERTY (worksheets, 'Item', args);
OLE2.DESTROY_ARGLIST (args);

For T In 1 .. l_colCnt
LOOP
BEGIN
Dbms_Sql.define_Column (source_cursor, T, newval1, 4000);
args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG (args, 1);
OLE2.ADD_ARG (args, T); --Next column
cell := OLE2.GET_OBJ_PROPERTY (worksheet, 'Cells', args);
OLE2.DESTROY_ARGLIST (args);
colour := ole2.get_obj_property (cell, 'Borders');
ole2.set_property (colour, 'ColorIndex', 1);
ole2.Release_obj (colour);
colour := ole2.get_obj_property (cell, 'Interior');
ole2.set_property (colour, 'ColorIndex', 15);
ole2.Release_obj (colour);
OLE2.SET_PROPERTY (cell, 'Value', l_descTbl (T).col_name);
OLE2.Release_obj (cell);
EXCEPTION
When Others
Then
Null;
END;
END LOOP;

Rows_processed := Dbms_Sql.EXECUTE (source_cursor);


row_n := 1;

LOOP

102
IF Dbms_Sql.fetch_Rows (source_cursor) > 0
Then
For T In 1 .. l_colCnt
LOOP
BEGIN
Dbms_Sql.column_Value (source_cursor, T, newval1);
args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG (args, row_n + 1);
OLE2.ADD_ARG (args, T); --Next column
cell := OLE2.GET_OBJ_PROPERTY (worksheet, 'Cells', args);
OLE2.DESTROY_ARGLIST (args);
colour := ole2.get_obj_property (cell, 'Borders');
ole2.set_property (colour, 'ColorIndex', 1);
ole2.Release_obj (colour);
OLE2.SET_PROPERTY (cell, 'Value', newval1);
OLE2.Release_obj (cell);
EXCEPTION
When Others
Then
EXIT;
END;

newval1 := Null;
END LOOP;
Else
EXIT;
END IF;

row_n := row_n + 1;
END LOOP;

Dbms_Sql.close_Cursor (source_cursor);
-- Autofit columns
RANGE := OLE2.GET_OBJ_PROPERTY (worksheet, 'UsedRange');
range_col := OLE2.GET_OBJ_PROPERTY (RANGE, 'Columns');
range_row := OLE2.GET_OBJ_PROPERTY (RANGE, 'Rows');
OLE2.INVOKE (range_col, 'AutoFit');
OLE2.INVOKE (range_row, 'AutoFit');
OLE2.Release_obj (RANGE);
OLE2.Release_obj (range_col);
OLE2.Release_obj (range_row);

103
-- Get filename and path
filename := 'Yourexcel.xls';

-- Save as worksheet
IF Nvl (filename, '0') <> '0'
Then
OLE2.SET_PROPERTY (application, 'Visible', 'True');
args := OLE2.CREATE_ARGLIST;
OLE2.ADD_ARG (args, filename);
OLE2.INVOKE (worksheet, 'SaveAs', args);
OLE2.DESTROY_ARGLIST (args);
END IF;

-- OLE2.INVOKE( workbook ,'Close');


OLE2.Release_obj (worksheet);
OLE2.Release_obj (worksheets);
OLE2.Release_obj (workbook);
OLE2.Release_obj (workbooks);
OLE2.Release_obj (application);
END;

104
How To Tune or Test PLSQL Code Performance in Oracle D2k Forms

You can test or tune your program unit performance in Oracle forms with Ora_Prof
package.

Suppose you have created to procedure to perform a single task with different logic
and you want to check exactly which procedure is performing well. See the below
example:

declare
i PLS_INTEGER;
BEGIN
--test 1
Ora_Prof.Create_Timer('test1');
Ora_Prof.Start_Timer('test1');

yourprogramunitwithsomelogic;

Ora_Prof.Stop_Timer('test1');
message('Test 1 Time taken '||Ora_Prof.Elapsed_Time('test1'), acknowledge);
Ora_Prof.Destroy_Timer('test1');
-- test 2
Ora_Prof.Create_Timer('test2');
Ora_Prof.Start_Timer('test2');

yourprogramunitwithanotherlogic;

Ora_Prof.Stop_Timer('test2');
message('Test 2 Time taken '||Ora_Prof.Elapsed_Time('test2'),acknowledge);
message('Test 2 Time taken '||Ora_Prof.Elapsed_Time('test2'),acknowledge);
Ora_Prof.Destroy_Timer('test2');
END;

It will give the result in milliseconds and now you can analyze that which program is
working good.

105
106
Creating Dynamic LOV in Oracle D2k Forms

Dynamic Lov is a good idea for the form where too many Lov requirement is there
with different record groups. In this blog you will learn create dynamic Lov step by
step.

Step-1 Create a Single Lov (you can give any name)


1. Click on form builder navigator Lovs node and then click on Add button. Select
create lov manually option from the window.
Step-2 Create Record Group (you can give any name)
2. Click on form builder navigator Record Groups and then click on Add button and
set the properties and query as displayed in below image.

Step-3 Create Parameters


3. Click on Parameter node and then click on Add button and create 4 Char type
Parameters as displayed below:

107
Step-4 Set Lov Properties
4. Set the lov properties as show below:

108
Step-5 Set Lov Column Mapping Properties
5. Set the Lov's Column Mapping Properties with the parameters as show below:

Step-6 Create a procedure to populate lov


109
PROCEDURE call_dynlov (IGroupName in Varchar2)
IS
blov boolean;
begin
:parameter.lovcol1 := null;
:parameter.lovcol2 := null;
:parameter.lovcol3 := Null;
:parameter.lovcol4 := Null;
set_lov_property('dynlov', group_name, IgroupName);
set_lov_property('dynlov', position, (get_application_property(display_width)-
600)/2,
(get_application_property(display_height)-250)/2-50);
blov := show_lov('dynlov');
if not blov then
message('Value not choosen.');
end if;
end;

Finally Call to this Lov with the following code:

DECLARE
rg_name VARCHAR2(40) := 'YrGroup';
rg_id RecordGroup;
errcode NUMBER;
BEGIN
rg_id := Find_Group( rg_name );
--- Create group with 4 column because we already set the lov property for 4 cols,
these 3 and 4 cols will --- be not mapped to any fields
if not id_null(rg_id) then
delete_group(rg_id);
end if;
rg_id :=
Create_Group_From_Query( rg_name, 'select main_menu_name col1,
sub_menu_name col2, ''3'' col3, ''4'' col4 from
fox_main_menu a, fox_sub_menu b
where a.main_menu_code = b.main_menu_code order by 1,2');
--- call the procedure
call_dynlov(rg_name);
if :parameter.lovcol1 is not null then

110
--- if lov selected and parameter 1 value is not null then map to field
:fox_user_prog.mmn := :parameter.lovcol1;
:Fox_user_prog.smn := :parameter.lovcol2;
end if;

END;

111
Using GET_APPLICATION_PROPERTY in Oracle D2k Forms

Description
Returns information about the current Form Builder application. You must call the
built-in once for each
value you want to retrieve.
Usage Notes
To request a complete login, including an appended connect string, use the Username,
Password, and
Connect_String properties. For instance, assume that the user has initiated an
Microsoft Windows
Runform session specifying the following connect string:

ifrun60 my_form scott/tiger@corpDB1


Form Builder returns the following string as the result of a call to
GET_APPLICATION_PROPERTY(USERNAME):
scott
Form Builder returns the following string as the result of a call to
GET_APPLICATION_PROPERTY(PASSWORD):
tiger
Form Builder returns the following string as the result of a call to
GET_APPLICATION_PROPERTY(CONNECT_STRING):
corpDB1

GET_APPLICATION_PROPERTY examples
Example 1
/*
** Built-in: GET_APPLICATION_PROPERTY
** Example: Determine the name of the timer that just
** expired, and based on the username perform a
** task.
** trigger: When-Timer-Expired
*/
DECLARE
tm_name VARCHAR2(40);
BEGIN
tm_name := Get_Application_Property(TIMER_NAME);

112
IF tm_name = ’MY_ONCE_EVERY_FIVE_MINUTES_TIMER’ THEN
:control.onscreen_clock := SYSDATE;
ELSIF tm_name = ’MY_ONCE_PER_HOUR_TIMER’ THEN
Go_Block(’connected_users’);
Execute_Query;
END IF;
END;
Example 2
/*
** Built-in: GET_APPLICATION_PROPERTY
** Example: Capture the username and password of the
** currently logged-on user, for use in calling
** another Tool.
*/
PROCEDURE Get_Connect_Info( the_username IN OUT VARCHAR2,
the_password IN OUT VARCHAR2,
the_connect IN OUT VARCHAR2) IS
BEGIN
the_username := Get_Application_Property(USERNAME);
the_password := Get_Application_Property(PASSWORD);
the_connect := Get_Application_Property(CONNECT_STRING);
END;
Example 3
Making window0 in center of screen
DECLARE
VWIDTH NUMBER := GET_APPLICATION_PROPERTY(DISPLAY_WIDTH);
VHEIGHT NUMBER :=
GET_APPLICATION_PROPERTY(DISPLAY_HEIGHT);
wwidth number := get_window_property('window0', width);
wheight number := get_window_property('window0', height);
BEGIN
SET_WINDOW_PROPERTY(FORMS_MDI_WINDOW, WINDOW_STATE,
MAXIMIZE);
SET_WINDOW_PROPERTY('WINDOW0', x_pos, (vwidth - wwidth) / 2);
SET_WINDOW_PROPERTY('WINDOW0', y_pos, (vheight - wheight-100) / 2 );
end;

113
Upload Files To FTP in Oracle Forms D2k

Use following procedure to upload files to Ftp.

PROCEDURE Ftp_Upload IS
outfile text_io.file_type;
BEGIN
-- write a ftp script
outfile := text_io.fopen('D:\ftpsendsource.ftp', 'w');
text_io.put_line(outfile, 'open yourftpurl');
text_io.put_line(outfile, 'youruser');
text_io.put_line(outfile, 'yourpassword');
text_io.put_line(outfile,'binary');
text_io.put_line(outfile,'send D:\Temp\Test1.txt');
text_io.put_line(outfile,'send D:\Temp\Test2.abc');
text_io.put_line(outfile,'disconnect');
text_io.put_line(outfile,'bye');
text_io.fclose(outfile);
host('cmd /c ftp -s:d:\ftpsendsource.ftp');
exception
when others then
if text_io.is_open(outfile) then
text_io.fclose(outfile);
end if;
message(sqlerrm);
END;

114
115
116

You might also like