Getting Started with Base

Getting Started with Base
Apache OpenOfficetm Database Component
Copyright
This document is Copyright © 2013 by its contributors as listed below. You may distribute it and/or
modify it under the terms of either the Apache Software License 2.0 or later
( http://www.apache.org/licenses/), or the Creative Commons Attribution License, version 3.0 or
later (http://creativecommons.org/licenses/by/3.0/).
Apache OpenOffice and OpenOffice.org are trademarks of The Apache Software Foundation. All
other trademarks mentioned in this guide belong to their respective owners.
Contributors
Drew Jensen ([email protected])
Feedback
Please direct any comments or suggestions about this document to:
Acknowledgments
This work includes material from
OpenOffice.org 3.3 Getting Started Guide, Chapter 8 - Getting Started with Base, Copyright 2010
Dan Lewis, Iain Roberts, Magnus Adielsson, Jean Hollis Weber, JiHui Choi
OpenOffice.org 3.2 BASIC Guide · March 2010, Copyright Oracle Corp.
Publication date and software version
Published 30 October 2013. Based on Apache OpenOffice 4.0.1
2
Getting Started with Base
Note for Mac users
Some keystrokes and menu items are different on a Mac from those used in Windows and Linux.
The table below gives some common substitutions for the instructions in this chapter. For a more
detailed list, see the application Help.
Windows/Linux
Tools > Options menu
selection
Right-click
Ctrl (Control)
F5
F11
Getting Started with Base
Mac equivalent
Effect
OpenOffice.org >
Preferences
Access setup options
Control+click
z (Command)
Shift+z+F5
z+T
Open context menu
Used with other keys
Open the Navigator
Open Styles & Formatting window
3
Contents
Copyright.......................................................................................................................................... 2
Note for Mac users........................................................................................................................... 3
Introduction...................................................................................................................................... 6
Planning a database......................................................................................................................... 8
Creating a new database.................................................................................................................. 9
Creating database tables................................................................................................................ 10
Using the Wizard to create a table.............................................................................................10
Creating a table by copying an existing table.............................................................................13
Creating tables in Design View..................................................................................................13
Creating tables for the list box...............................................................................................16
Defining relationships..................................................................................................................... 18
Creating a database form............................................................................................................... 20
Using the Wizard to create a form..............................................................................................20
Modifying a form........................................................................................................................ 23
Creating forms and subforms in Design View............................................................................34
Accessing other data sources........................................................................................................ 35
Accessing a spreadsheet as a data source................................................................................35
Registering *.odb databases......................................................................................................35
Using data sources in Apache OpenOffice.................................................................................36
Viewing data sources............................................................................................................ 36
Editing data sources.............................................................................................................. 36
Launching Base to work on data sources..............................................................................37
Using data sources in Writer and Calc.......................................................................................37
Writer documents.................................................................................................................. 37
Calc spreadsheets................................................................................................................ 39
Entering data in a form................................................................................................................... 41
Creating queries............................................................................................................................. 44
Using the Wizard to create a query............................................................................................44
Using the Design View to create a query...................................................................................46
Creating reports.............................................................................................................................. 52
Creating a static report............................................................................................................... 52
Creating a dynamic report.......................................................................................................... 55
Apendix 1 HSQL-SDBC internal query procedures........................................................................60
Overview.................................................................................................................................... 60
Numerical Functions.................................................................................................................. 60
String Functions......................................................................................................................... 63
Date and Time Functions........................................................................................................... 66
System Functions...................................................................................................................... 69
Aggregate Functions.................................................................................................................. 69
Statistical Functions................................................................................................................... 70
Modifiers.................................................................................................................................... 70
Limit...................................................................................................................................... 71
4
Getting Started with Base
Top........................................................................................................................................ 71
Distinct.................................................................................................................................. 72
Appendix 2 – OpenOffice Basic .....................................................................................................73
Database .................................................................................................................................. 73
SQL: a Query Language ......................................................................................................73
Types of Database Access ...................................................................................................73
Data Sources ............................................................................................................................ 74
Queries ................................................................................................................................ 75
Database Access ................................................................................................................. 76
Iteration of Tables ................................................................................................................. 77
Type-Specific Methods for Retrieving Values .......................................................................78
The ResultSet Variants .........................................................................................................79
Methods for Navigation in ResultSets ..................................................................................79
Modifying Data Records .......................................................................................................80
Dialogs ...................................................................................................................................... 80
Working With Dialogs ........................................................................................................... 81
Creating Dialogs ................................................................................................................... 81
Closing Dialogs .................................................................................................................... 81
Working With Dialogs ........................................................................................................... 82
Access to Individual Control Elements .................................................................................82
Working With the Model of Dialogs and Control Elements ...................................................82
Focus and Tabulator Sequence ............................................................................................83
Multi-Page Dialogs ............................................................................................................... 84
Dialogs supporting several languages ..................................................................................85
Events .................................................................................................................................. 85
The Apache OpenOffice Basic development environment ....................................................85
Mouse Events ...................................................................................................................... 86
Keyboard Events .................................................................................................................. 88
Focus Events ....................................................................................................................... 89
Control Element-Specific Events ..........................................................................................89
Dialog Control Elements .......................................................................................................90
Buttons ................................................................................................................................. 90
Text Fields ............................................................................................................................ 93
Forms ....................................................................................................................................... 96
Working With Forms ............................................................................................................. 97
Control Element Forms ......................................................................................................100
Database Forms ................................................................................................................. 106
Getting Started with Base
5
Introduction
A data source, or database, is a collection of pieces of information that can be accessed or
managed by OpenOffice.org (OOo). For example, a list of names and addresses is a data source
that could be used for producing a mail merge letter. A shop stock list could be a data source
managed through OOo.
Note
OpenOffice.org uses the terms “Data Source” and “Database” to refer to the same
thing, which could be a database such as MySQL or dBase or a spreadsheet or text
document holding data.
This chapter covers creating a database, showing what is contained in a database and how the
different parts are used by OOo. It also covers using the Base component of OOo to register other
data sources. A data source can be a database, spreadsheet, or text document.
Note
OOo Base uses the HSQL database engine. All of the files created by this engine
are kept in one zipped file. The database forms are included in this zipped file.
A database consists of a number of fields that contain the individual pieces of data. Each table of
the database is a group of fields. When creating a table, you also determine the characteristics of
each field in the table. Forms are for data entry into the fields of one or more tables associated with
the form. They can also be used for viewing fields from one or more tables associated with the
form. A query creates a new table from the existing tables based upon how you create the query. A
report organizes the information of the fields of a query in a document according to your
requirements.
Caution
The database in OOo requires Java Runtime Environment (JRE). If you do not
have it on your computer, you can download it from www.java.com and install it
following the instructions on the site. It should be Java 5.0 or higher. In OOo, use
Tools > Options > OpenOffice.org > Java to register Java.
Windows' version of JRE can not be used, while there are other versions that can.
Base creates relational databases. This makes it fairly easy to create a database in which the
fields of the database have relationships with each other.
For example: Consider a database for a library. It will contain a field for the names of the authors
and another field for the names of the books. There is an obvious relationship between the authors
and the books they have written. The library may contain more than one book by the same author.
This is what is known as a one-to-many relationship: one author and more than one book. Most if
not all the relationships in such a database are one-to-many relationships.
Consider an employment database for the same library. One of the fields contains the names of
the employees while others contain the social security numbers, and other personal data. The
relationship between the names and social security numbers is one-to-one: only one social security
number for each name.
If you are acquainted with mathematical sets, a relational database can easily be explained in
terms of sets: elements, subsets, unions, and intersections. The fields of a database are the
elements. The tables are subsets. Relationships are defined in terms of unions and intersections of
the subsets (tables).
To explain how to use a database, we will create one for automobile expenses. In the process, we
will be explaining how a database works.
6
Getting Started with Base
Planning a database
The first step in creating a database is to ask yourself many questions. Write them down, and
leave some space between the questions to later write the answers. At least some of the answers
should seem obvious after you take some time to think.
You may have to go through this process a few times before everything becomes clear in your
mind and on paper. Using a text document for these questions and answers makes it easier to
move the questions around, add additional questions, or change the answers.
Here are some of the questions and answers I developed before I created a database for
automobile expenses. I had an idea of what I wanted before I started, but as I began asking
questions and listing the answers, I discovered that I needed additional tables and fields.
What are the fields going to be? My expenses divided into three broad areas: fuel purchases,
maintenance, and vacations. The annual cost for the car’s license plate and driver’s license every
four years did not fit into any of these. It will be a table of its own: license fees.
What fields fit the fuel purchases area? Date purchased, odometer reading, fuel cost, fuel quantity,
and payment method fit. (Fuel economy can be calculated with a query.)
What fields fit the maintenance area? Date of service, odometer reading, type of service, cost of
service, and next scheduled service of this type (for example, for oil changes list when the next oil
change should be). But it would be nice if there was a way to write notes. So, a field for notes was
added to the list.
What fields fit the vacations area? Date, odometer reading, fuel (including all the fields of the fuel
table), food (including meals and snacks), motel, total tolls, and miscellaneous. Since these
purchases are made by one of two bank cards or with cash, I want a field to state which payment
type was used for each item.
What fields fit into the food category? Breakfast, lunch, supper, and snacks seem to fit. Do I list all
the snacks individually or list the total cost for snacks for the day? I chose to divide snacks into two
fields: number of snacks and total cost of snacks. I also need a payment type for each of these:
breakfast, lunch, supper, and total cost of snacks.
What are the fields that are common to more than one area? Date appears in all of the areas as
does odometer reading and payment type.
How will I use this information about these three fields? While on vacation, I want the expenses for
each day to be listed together. The date fields suggest a relationship between the vacation table
and the dates in each of these tables: fuel and food, This means that the date fields in these tables
will be linked as we create the database.
The type of payment includes two bank cards and cash. So, we will create a table with a field for
the type of payment and use it in list boxes in the forms.
Tip
While we have listed fields we will create in the tables of the database, there is one
more field that may be needed in a table: the field for the primary key. In some tables,
the field for the primary key has already been listed. In other tables such as the
payment type, an additional field for the primary key must be created.
Planning a database
7
Creating a new database
To create a new database, choose File > New > Database from the menu bar, or click the arrow
next to the New icon on the Standard toolbar and select Database from the dropdown menu. Both
methods open the Database Wizard.
On the first page of the Database Wizard, select Create a new database and then click Next.
The second page has two questions. Make sure the choice for the first question is Yes, register the
database for me and the choice for the second question is Open the database for editing. Click
Finish.
Note
If the database is not registered, it will not be accessible to the other OOo
components such as Writer and Calc. If the database is registered, other components
can access it.
Save the new database with the name Automobile. This opens the Automobile – OpenOffice.org
Base window. Figure 1 shows part of this window.
Figure 1: Creating database tables
Tip
8
Every time the Automobile database is opened, the Automobile – OpenOffice.org
Base window opens. Changes can then be made to the database. The title for this
window is always <database name> – OpenOffice.org Base.
Getting Started with Base
Creating database tables
In a database, a table stores information for a group of things we call fields. For example, a table
might hold an address book, a stock list, a phone book or a price list. A database can have from
one to several tables.
To work with tables, click the Tables icon in the Database list, or press Alt+a. The three tasks that
you can perform on a table are in the Tasks list (see Figure 1).
Using the Wizard to create a table
Wizards are designed to do the basic work. Sometimes this is not sufficient for what we want; in
those cases we can use a wizard as a starting point and then build upon what it produces.
The Table Wizard in Base contains two categories of suggested tables: business and personal.
Each category contains sample tables from which to choose. Each table has a list of available
fields. We can delete some of these fields and add other fields.
A field in a table is one bit of information. For example, a price list table might have one field for
item name, one for the description, and a third for the price.
Since none of the fields we need for our Automobile database are contained in any of the sample
wizard tables, we will create a simple table using the wizard that has nothing to do with our
database. This section is an exercise in explaining how the Wizard works.
The Wizard permits the fields of the table to come from more than one suggested table. We will
create a table with fields from three different suggested tables in the Wizard.
Caution
Every table requires a Primary key field. (What this field does will be explained
later.) We will use this field to number our entries and want that number to
automatically increase as we add each entry.
Click Use Wizard to Create Table. This opens the Table Wizard (Figure 2).
Step 1: Select fields.
We will use the CD-Collection Sample table in the Personal category to select the fields
we need.
Category: Select Personal. The Sample Tables dropdown list changes to a list of personal
sample tables.
Sample tables: Select CD-Collection. The Available fields box changes to a list of available
fields for this table.
Selected fields: Using the > button, move the following fields from the Available fields
window to the Selected fields window in this order: CollectionID, AlbumTitle, Artist,
DatePurchased, Format, Notes, and NumberofTracks.
Selected Fields from another sample table. Click Business as the Category. Select
Employees from the dropdown list of sample tables. Use the > button to move the Photo
field from the Available fields window to the Selected fields window. It will be at the bottom
of the list directly below the NumberofTracks field.
If you make a mistake in selecting fields, click on the field name in the Selected fields list
and use the < button to move it from the Selected fields list back to the Available fields list.
Creating database tables
9
If you make a mistake in the order of the selected fields, click on the field name that is in
the wrong order and use the Up or Down arrow on the right side of the Selected fields list to
move the field name to the correct position.
Click Next.
Figure 2: Selecting fields for the table
Step 2: Set field types and formats.
In this step you give the fields their properties. When you click a field, the information on the
right changes. (See Figure 3.) You can then make changes to meet your needs. Click each
field, one at a time, and make the changes listed below.
Figure 3: Changing field types
Note
If any of these fields requires an entry, set Entry required to Yes. An entry with that
field blank will then not be allowed. In general, only set Entry required to Yes if
something must always be put in that field. By default, Entry required is set to No.
CollectionID: Change AutoValue from No to Yes.
AlbumTitle:
Entry required: Leave Entry required as No, unless all of your music is in albums.
Length: Unless you have an album title that exceeds 100 characters counting the spaces,
do not change the length.
10
Getting Started with Base
In Base the maximum length of each field must be specified on creation. It is not easy
to change this later, so if in doubt specify a greater length. Base uses VCHAR as the
field format for text fields. This format only uses the actual number of characters in a
field up to the limit set. So, a field containing 20 characters will only use space for 20
characters even if the limit is set at 100. Two album titles containing 25 and 32
characters respectively will use space for 25 and 32 characters and not 100
characters.
Note
Artist: Use the Default setting. And since music has artists, set Entry Required to Yes.
Date Purchased: Field type: default date setting. Entry required should be No. (You may not
know the date.)
Format: Only change the Entry Required setting: from No to Yes.
Notes: No changes are required.
NumberofTracks: Change the Field Type to Tiny Integer [TINYINT]. Your allowable number of
tracks will be 999. Small Integer [SMALLINT] would allow 99999 tracks if you needed more
than 999 tracks.
Photo: Use the default settings.
When you have finished, click Next.
Each field has a Field Type, which must be specified. Types include text, integer,
date, and decimal. If the field is going to have general information in it (for example, a
name or a description), use text. If the field will always contain a number (for
example, a price), the type should be decimal or another numerical field. The wizard
picks the right field type, so to get an idea of how this works, see what the wizard has
chosen for different fields.
Note
Step 3: Set primary key.
Create a primary key should be checked.
Select option Use an existing field as a primary key.
In the Fieldname dropdown list, select CollectionID.
Check Auto value if it is not already checked.
Click Next.
A primary key uniquely identifies an item (or record) in the table. For example, you
might know two people called “Randy Herring” or three people living at the same
address and the database needs to distinguish between them.
Note
The simplest method is to assign a unique number to each one: number the first
person 1, the second 2, and so on. Each entry has one number and every number
is different, so it is easy to say “record ID 172”. This is the option chosen here:
CollectionID is just a number assigned automatically by Base to each record of this
table.
Step 4: Create the table.
If desired, rename the table at this point. If you rename it, make the name meaningful to you.
For this example, make no changes.
Leave the option Insert data immediately checked.
Click Finish to complete the table wizard.
Creating database tables
11
Close the window created by the table wizard. You are now back to the main window of the
database with the listing of the tables, queries, forms, and reports. Notice that a table named “CDCollection” is now listed in the Tables portion of the window.
Creating a table by copying an existing table
If you have a large collection of music, you might want to create a table for each type of music you
have. Rather than creating each table from the wizard, you can make copies of the original table,
naming each according to the type of music contained in it.
Click on the Tables icon in the Database pane to see the existing tables.
Right-click on the CD-Collection table icon. Choose Copy from the pop-up menu.
Move the mouse pointer below this table, right-click, and select Paste. The Copy table dialog
opens.
Change the table name to Pop and click Next.
Click the >> button to move all the fields from the left box to the right box and click Next.
Since all the fields already have the proper Field type, no changes should be needed. However,
this is the time and place to make any changes if they are needed. (See Caution below for the
reason why.) Click Create. The new table is created.
Caution
Once tables have been created using the wizard and data has been entered, editing
them should be very limited. Fields can be added or deleted, but adding a field
requires taking the time to enter the data for that one field for every record having
an entry for that field.
Deleting a field deletes all the data once contained in that field. Changing the field
type of a field can lead to data being lost either partially or completely. When
creating a new table, it pays to create the fields with the correct names, length, and
format before you add any data.
Deleting a table removes all of the data contained in every field of the table. Unless
you are sure, do not delete a table.
Creating tables in Design View
Design View is a more advanced method for creating a new table, in which you directly enter
information about each field in the table. We will use this method for the tables of our database.
Note
While the Field type and formatting are different in Design View, the concepts are the
same as in the Wizard.
The first table to be created is Fuel. Its fields are FuelID, Date, FuelCost, FuelQuantity, Odometer,
and PaymentType.
Click Create Table in Design View.
FuelID field:
Type FuelID as the first Field Name. Press the Tab key to move to the Field Type column.
Select Integer [INTEGER] as the Field Type from the dropdown list. (The default setting is Text
[VARCHAR].)
12
Getting Started with Base
A shortcut for selecting from the Field Type dropdown list: press the key for the first
letter of the choice. You can cycle through the choices for a given letter by repeatedly
pressing that key.
Tip
Change the Field Properties in the bottom section.
Change AutoValue from No to Yes.
Set FuelID as the Primary key.
Right-click on the green triangle to the left of FuelID (Figure 4) and choose Primary Key from
the menu. This places a key icon in front of FuelID.
Figure 4: Defining the primary key field
Note
The primary key serves only one purpose: to uniquely identify the record. Any name
can be used for this field. We have used FuelID for convenience, so we know to
which table it belongs.
1) All other fields (Date, FuelCost, FuelQuantity, Odometer, and PaymentType):
Type the next field name in the Field Name column.
Select the Field Type for each field.
For Date use Date[DATE]. (Press the D key to select it.)
PaymentType uses Text [VARCHAR], the default setting.
All other fields use Number [NUMERIC]. (Press the N key once to select it.)
FuelCost, FuelQuantity, and Odometer need changes in the Field Properties section (Figure 5).
FuelQuantity: Change Length to 6 and Decimal places to 3. (Many fuel pumps measure fuel to
thousands of a gallon in the USA where I live.)
Odometer: Change the Length to 10 and the Decimal places to 1.
FuelCost: Change the Length to 5 and Decimal places to 2. Click the Format example button
(Figure 5). This opens the Field Format window (Figure 6). Use Currency as the Category and your
currency as the Format. My currency has two decimal places. Use what is appropriate for yours.
Creating database tables
13
Figure 5: Changing field properties
Figure 6: Field Format options
To access additional formatting options, click the button to the right of the Format example field.
Description can be anything, or can be left blank.
To save and close the table, choose File > Save. Name the table Fuel. Close the Fuel table.
Follow the same steps to create the Vacations table. The fields and their field types are listed in
Figure 7. Make sure you make the Date field the primary key before closing. (Right-click the gray
box to the left of Date and select Primary key from the menu.) Save the table and name it
Vacations. Close the Vacations table.
14
Getting Started with Base
Figure 7: Fields in Vacations table
Creating tables for the list box
When the same information can be used in several fields, design a table for each type of
information. Each table will contain two fields: the information field and ID, in that order.
Caution
You must create these tables with the information field listed first and the ID field
listed last. Failure to do so will produce the wrong results. For my Payment table, I
use Name and ID as my fields, with Dan, Kevin, and Cash being the Name entries.
The corresponding ID entries are 0, 1, 2. When the Name field is listed first in the
table, one of the three names will appear in the payment field of the Fuel table. If the
ID field is listed first, 0, 1, or 2 appear in the payment field instead.
Follow the directions in “Creating tables in Design View” on page 12. In the table, the two fields can
be Type and PaymentID. In the Field Properties, set AutoValue to Yes for the PaymentID field. Set
the PaymentID field as the primary key. (See Figure 8.)
Save the table using the name Payment Type.
Figure 8: Table in Design View
Note
If you have several tables to create with the same fields, design one table and produce
the other tables by cutting and pasting. (See “Creating a table by copying an existing
table” on page 12.)
Adding data to the list table
List tables do not require a form. Instead, add their data directly to the table. In this example, use
the names of the two people with a bank card and Cash for cash purchases.
Creating database tables
15
In the main database window, click on the Tables icon (Figure 1). In the list of tables, right-click on
Payment Type and select Open from the pop-up menu.
Enter Dan in the Type column in the first row. Press the Tab key to move to the second row. Notice
that the PaymentID value for this row changes from <AutoField> to 0.
Enter Kevin in the second row. The PaymentID changes to 1.
a)
Enter Cash in the third row. The PaymentID changes to 2.
Save and close the table window.
Tip
16
You can also use the Enter key to move from entry field to entry field, or use the
down arrow key to move from row to row.
Getting Started with Base
Defining relationships
Now that the tables have been created, what are the relationships between our tables? This is the
time to define them based upon the questions we asked and answered in the beginning.
When on vacation, we want to enter all of our expenses all at one time each day. Most of these
expenses are in the Vacations table, but the fuel we buy is not. So, we will relate these two tables
using the Date fields. Since the Fuel table may have more than one entry per date, this relationship
between the Vacations and Fuel tables is one to many. (It is designated 1:n.)
The Vacations table also contains several fields for the type of payment used. For each field listing
the payment type, there is only one entry from the Payment Type table. This is a one to one
relationship: one field in one table to one entry from the other table. (It is designated 1:1.) Other
tables also contain fields for the type of payment. The relationship between the fields of those
tables and the Payment Type table are also 1:1.
Since the Payment Type table only provides a static list, we will not be defining a relationship
between the Payment Type table and the fields of the other tables which use the entries of the
Payment Type table. That will be done when the forms are created.
The Fuel and Maintenance tables do not really have a relationship even though they share similar
fields: Date and Odometer.
Tip
As you create your own databases, you need to also determine where tables are
related and how.
To begin defining relationships, choose Tools > Relationships. The Automobile – OpenOffice.org
Base: Relation Design window opens and the Add Tables dialog pops up. (You can also open it by
clicking the Add Tables icon on the Relation Design window.)
On the Add Tables dialog, use either of these ways to add a table to the Relation Design window:
Double-click the name of the table. In our case, do this for both Vacations and Fuel.
Or, click the name of the table and then click Add for each table.
Click Close to close the Add Tables dialog when you have added the tables you want.
You can define the relationship between the Vacations and Fuel tables in two ways:
Click and drag the Date field in the Fuel table to the Date field in the Vacations table. When you
release the mouse button, a connecting line forms between the two date fields.
Figure 9: Designation for a 1:n relationship
Or, click the New Relation icon. This opens the Relations window (Figure Figure 10). Our two
tables are listed in the Tables involved section.
In the Fields involved section, click the dropdown list under the Fuel label.
Select Date from the Fuel table list.
Click in the cell to the right of this dropdown list. This opens a dropdown list for the Vacations table.
Defining relationships
17
Select Date from the Vacations table list. It should now look like Figure 10.
Click OK.
Figure 10: Selected fields in a relationship
2) Modifying the Update options and Delete options section of the Relation window.
Right-click the line connecting the Date fields in the two table lists to open a menu.
Select Edit to open the Relations dialog (Figure 11).
Select Update cascade.
a)
Select Delete cascade.
Click OK to close the Relations dialog and choose File > Save to save the Relation Design window.
While these options are not strictly necessary, they do help. Having them selected permits you to
update a table that has a relationship defined with another table. It also permits you to delete a
field from the table.
Figure 11: Update options and Delete options section
18
Getting Started with Base
Creating a database form
Databases are used to store data. But, how is the data put into the database? Forms are used to
do this. In the language of databases, a form is a front end for data entry and editing.
Figure 12: Fields of a simple form
Figure 13: Simple form with additions
A simple form consists of the fields from a table (Figure 12). More complex forms can contain much
more, including additional text, graphics, selection boxes, and many other elements. Figure 13 is
made from the same table with a text label (Fuel Purchases), a list box placed in PaymentType,
and a graphic background.
Using the Wizard to create a form
We will use the Form Wizard to create a Vacations form, which will contain a form and a subform.
In the main database window (Figure 1), click the Forms icon in the left column. In the Tasks list,
double-click Use Wizard to Create Form to open the Form Wizard (Figure 14). Simple forms
require only some of these steps, while more complex forms may use all of them.
Step 1: Select fields.
Under Tables or queries, select Table: Vacations. Available fields lists the fields for the Vacations
table.
Click the right double arrow to move all of these fields to the Fields in the form list. Click Next.
Figure 14: Form Wizard steps
Step 2: Set up a subform.
Getting Started with Base
19
Since we have already created a relationship between the Fuel and Vacations tables, we will use
that relationship. If no relationship had been defined, this would be done in step 4.
Click the box labeled Add Subform.
Click Subform based upon existing relation.
Fuel is listed as a relation we want to add. So, click Fuel to highlight it, as in Figure 15. Click Next.
Figure 15: Adding a subform
Step 3: Add subform fields.
This step is exactly the same as step 1. The only difference is that not all of the fields will be used
in the subform.
Fuel is preselected under Tables or queries.
Use the >> button to move all the fields to the right.
Click the FuelID field to highlight it.
Use the < button to move the FuelID to the left (Figure 16).
Click Next.
Figure 16: Selecting fields of a subform
Step 4: Get joined fields.
20
Getting Started with Base
This step is for tables or queries for which no relationship has been defined. Because we have
already defined the relationship, the wizard skips this step.
Note
Caution
It is possible to create a relationship between two tables that is based upon more
than one pair of fields. How to do that and why is discussed in the Base Guide.
When selecting a pair of fields from two tables to use as a relationship, they have to
have the same field type. That is why we used the Date field from both tables: both
their field types are Date[DATE].
Whether a single pair of fields from two tables are chosen as the relationship or two
or more pairs are chosen, certain requirements must be met for the form to work.
• No field from the subform can be the Primary key for its table. (FuelID cannot
be used.)
• Each pair of joined fields must have the same file type.
• One of the fields from the main form must be the Primary key for its table.
(Date would have to be used.)
Step 5: Arrange controls.
Each control in a form consists of two parts: label and field. This step in creating the form
determines where a control’s label and field are placed in relationship with each other. The four
choices from left to right are Columnar left, Columnar - Labels on top, As Data Sheet, and In
Blocks - Labels Above.
Arrangement of the main form: Click the second icon (Columnar - Labels on top). The labels will be
placed above their field.
Arrangement of the subform: Click the third icon (As Data Sheet). (The labels are column headings
and the field entries are in spreadsheet format.) Click Next.
Step 6: Set data entry.
Unless you have a need for any of these entries to be checked, accept the default settings. Click
Next.
Step 7: Apply styles.
Getting Started with Base
21
Select the color you want in the Apply Styles list. (I chose the beige which is Orange 4 in the Color
table.)
Select the Field border you want. (I prefer the 3-D look. You might want to experiment with the
different possible settings.)
Click Next.
Step 8: Set name.
Enter the name for the form. In this case, it is Fuel.
Click Modify the form.
Click Finish. The form opens in Edit mode.
Modifying a form
We will be moving the controls to different places in the form and changing the background to a
picture. We will also modify the label for the PaymentType field as well as change the field to a list
box.
First, we must decide what we want to change. The discussion will follow this ten step outline of
our planned changes.
Provide a dropdown capability for the Date field in the main form, and lengthen the field to show
the day of the week, month, day, and year.
Shorten the length of the payment fields (all fields containing the word Payment).
Move the controls into groups: food, fuel subform, and miscellaneous.
Change the wording of some of the labels. Some single words should be two words. Some
abbreviations should be used if possible (Misc. for miscellaneous).
Change the lengths of several fields and labels. Only Lunch, Supper, Motel, and Tolls have
acceptable lengths. But for a better appearance, changes will be made to these as well.
Replace all the fields whose label ends in Payment with a list box containing the entries from the
Payment Type table.
Lengthen the Note field vertically, add a scroll bar, and move it.
Make changes in the Date and PaymentType columns of the subform that are similar to the
changes in the main form.
Add headings for each group in the main form.
Change the background to a picture, then modify some of the labels so that they can be read
clearly. Change the font color of the headings.
Here are some methods that we will be using in these steps. The controls in the main form consists
of a label and its field. Sometimes we want to work with the entire control, other times we want to
work with only the label or the field, and there are times when we want to work with a group of
controls.
• Clicking a label or field selects the entire control. A border appears around the control with
eight green handles. You can then drag and drop it where you want.
Figure 17: A selected control
22
Getting Started with Base
• Control+click a label or field selects only the label or the field. You can press the Tab key to
change the selection from the field to the label or the label to the field.
Figure 18: Selecting a field of a control
• Moving a group of controls is almost as easy as moving one of them.
Click the field of the top left control to be moved, to select it.
Move the cursor to just above and to the left of the selected control.
Drag the cursor to the bottom right of the group of controls and release the mouse button.
As you drag the cursor, a dashed box appears showing what is contained in your selection. Make
sure it is big enough to include the entire length of all the controls.
When you release the mouse button, a border with its green handles appears around the controls
you selected.
Figure 19: Selecting multiple controls
Move the cursor over one of the fields. It changes to a drag icon. Drag the group of controls to
where you want them.
Tip
When either changing size or moving a control, two properties of the Form Design
toolbar should be selected: Snap to Grid, and Guides when Moving. Your controls will
line up better, and an outline of what you are moving moves as the cursor moves.
You should also have both rulers active (View > Ruler).
Step 1: Change the Date field.
Control+click the Date field to select it.
Move the cursor over the middle green handle on the right side. It should change to a doubleheaded arrow.
Hold the left mouse button down as you drag the cursor to the right until the length is 6 cm. The
vertical dashed line is lined up with the 6. Release the mouse button.
Click the Control icon in the Form Controls toolbar. The Properties: Date Field window opens. Each
line contains a property of the field.
Figure 20: Form Controls toolbar
Scroll down to the Date format property. This is a dropdown list with Standard (short) as the default
setting. Click it to open the list. Select the Standard (long) entry.
Scroll down to the Dropdown property. Its default setting is No. It is also a dropdown list. Click to
open the list. Select Yes.
Getting Started with Base
23
Tip
To see what the Date field will look like, click the Form Mode On/Off icon (the second
icon from the left in Figure 20). You can do this any time you want to see the form
with the changes you have made.
Step 2: Shorten the width of some fields.
All of the fields with a label containing the word payment are too wide. They need shortening
before the controls are moved.
Control+click the BPayment field.
Figure 21: Selecting a field
Move the cursor over the middle green handle on the right. The cursor becomes a double-headed
arrow.
Drag the cursor to the left until the field is 2.5 cm wide (1 inch).
Tip
If you have the Snap to Grid and Guides when moving icons selected in the Design
Format toolbar, you will see how wide the field is as you shorten it.
Repeat these steps to shorten these fields: Lpayment, SPayment, SnPayment, Mpayment, and
MiscPayment.
Step 3: Move the controls to group them by category.
We want to move the controls so that they look like Figure 22.
Figure 22: Positioning of controls
Click the first control you want to move. A border appears around the control with eight green
handles.
Move the cursor over the label or field of the control. It change shape to a drag icon.
Drag and drop the control to where you want it.
Caution
24
Do not use Control+click when moving a field. It moves either the field or the label
but not both. To move both, use a mouse click and drag to the desired spot.
Getting Started with Base
Use the same steps to move the rest of the controls to where they belong.
Step 4: Change the label wording.
Field names have been single words for some time. However, the labels for the fields in a form
can be more than one word. So, we will change them by editing the text in the label.
The table wizard in Base contains suggested fields which are single words, often
consisting of two separate words. Table names in the wizard have been that way
also. However, you can use multiple words as the name of a field, label, or table. We
will do so when we create a list box for each of the payment type controls.
Note
Control+click the SnackNo label. Do one of the following:
Right-click the SnackNo label and select Control from the pop-up menu.
•
Or, click the Control icon in the Form Control toolbar (Figure 20).
The dialog that opens is labeled Properties: Label Field. It contains all of the properties of the
selected label.
In the Label selection, edit the label to Snack No.
Close the Properties dialog.
Use the same procedure to change these labels as well: BPayment to Payment, LPayment to
Payment, SPayment to Payment, Miscellaneous to Misc., SnackCost to Snack Cost, MPayment to
Payment, MiscPayment to Misc. Payment, and MiscNotes to Misc. Notes.
Tip
You can modify all of the listings in the Properties window. For example, if you
change the Alignment from Left to Center, the word or words in the label are centered
within the label. When you have some time, you might want to experiment with
different settings just to see the results you get.
Step 5: Change the widths of the labels and fields.
We want the following controls to be 2 cm wide (0.8 inches): Breakfast, Lunch, Supper, Odometer,
Snack No., Tolls, Snack Cost, Motel, and Misc. All of the payment fields were changed in step 2,
but Misc. Payment needs to be changed to 3 cm (1.2 inches).
Right-click Breakfast and choose Position and Size. On the Position and Size dialog, change Width
to 2 cm.
Repeat for the other listed controls, using 3 cm for Misc.Payment.
Caution
Note
When changing the position or size of an entire control, use the Position and Size
dialog or the drag and drop method.
When working with either the label or the field (but not both at the same time), you
can use the Properties dialog to make these changes when you want to be exact.
However, you need to be careful not to accidentally select the entire control for use
with the Properties dialog or you will apply the exact same values to both the label
and field. For example, if you enter the values for a new position, both the field and
the label moves to the same position and the field is positioned on top of the label.
Then you have to move each of them to where you want them.
To open the Properties window, right-click a control and select Control from the popup menu. Or, you can click the Control icon in the Form Controls toolbar. Just be
careful, and use Control+Z to undo any mistakes you may make. Detailed
instructions on how to use the Properties window will be in the Base Guide.
Getting Started with Base
25
Step 6: Replace fields with other fields.
We want to replace the PaymentType field with a List Box. Then we can choose the type of
payment from the Payment Type table rather than having to manually enter the type. In my case,
each of my payment types begins with a different letter. If I enter the first letter of the payment type,
the rest of the word automatically appears. I can then go to the next field.
Control+click the Payment field for Breakfast. The green handles appear around the field but not
around the Label.
Figure 23: Selecting a field of a control
Right-click within the green handles and select Replace with > List Box.
Click the Control icon in the Form Controls toolbar to open the Properties: List Box dialog.
On the General tab, scroll down to the Dropdown selection. Change the No to Yes.
Figure 24: Dropdown list open to reveal choices
Click the Data tab.
Type of list contents is a dropdown list. Change it to Sql.
Figure 25: Type of list contents dropdown list
Type the following exactly as it is in the List contents box:
26
Getting Started with Base
SELECT "Type", "Type" FROM "Payment Type"
Figure 26: List content for payment type fields
Note
What you wrote is called an SQL command. The words SELECT and FROM are
written in capital letters because they are commands. When the command SELECT
is used, it requires a field name within quotation marks and then the field’s alias, also
within quotation marks. In this case, the field and its alias are the same. The FROM
command requires the name of the table which contains the field. Single-word table
names do not require quotation marks, but multiple-word table names do.
Repeat these steps for the payment fields for Lunch, Supper, Motel, Snacks, and Misc. The main
form should look like Figure 27 as far as where the controls are located. It also shows what the
Note control should look like. Those changes are explained in the next step.
Close the Properties window.
Figure 27: Position of controls in main form
Step 7: Change the Misc. Notes field.
We want the Misc. Notes control, which has a field type of Memo, to have a vertical scrollbar for
additional text space if desired.
Control+click the Misc. Notes field. The green handles should surround the field but not its label.
Click the Control icon to open the Properties window (Figure 28).
Scroll down to the Scrollbars setting. Change the selection from None to Vertical in this dropdown
list.
Getting Started with Base
27
Figure 28: Scrollbar selections in the Properties window
Close the Properties window.
Lengthen the Misc. Notes field by moving the cursor over the middle green handle at the bottom of
the field and dragging down until the length is 6 cm (2.4 inches).
Step 8: Change labels and fields in the subform.
The subform is located at the bottom of the form. We want to widen the Date column, change the
field in the PaymentType column to a list box, and change the label for the PaymentType column to
two words.
To widen the Date column, move the mouse pointer over the dividing line between the Date and
FuelCost columns. When the pointer changes shape, click and drag to move the divider to the
right.
To change the PaymentType column:
Right-click the label PaymentType and choose Replace with > List box from the menu.
Again right-click the label PaymentType to open the menu. Select Column to open the Properties
dialog (Figure 29).
In the Label box, change PaymentType to Payment Type.
Click the Data tab.
From the Type of list contents dropdown list, select Sql.
Type the following exactly as it is written:
SELECT "Type", "Type" FROM "Payment Type"
Close the Properties dialog.
28
Getting Started with Base
Figure 29: Properties window for control in a subform
Step 9: Add headings to groups.
This step is easier to do if you have end-of-paragraph markers visible. Choose View > Nonprinting
Characters to turn them on.
Make sure the cursor in in the upper left corner. If it is not, click in that corner to move it there.
Press the Enter key to move the cursor down to the space between the Date field and the
Breakfast field.
Change the Apply Styles dropdown list from Default to Heading 2.
Figure 30: Apply Styles list
Use the spacebar to move the cursor to where you want the heading to start.
Type the heading Meals.
Use the spacebar to move the cursor to the center of snack area.
Type the heading Snacks.
Use the Enter key to move the cursor between the Supper control and the subform.
Use the spacebar to move the cursor to the center of the subform.
Type the heading Fuel Data.
Note
If you know how to use styles, you can open the Styles and Formatting window using
F11. Right-clicking the Heading 2 paragraph style allows you to modify the
appearance of all three headings. See Chapter 6 of the Writer Guide for details.
Step 10: Change the background of a form.
Getting Started with Base
29
The background for a form can be a color, or a graphic (picture). You can use any of the colors in
the Color Table at Tools > Options > OpenOffice.org > Colors. If you know how to create custom
colors, you can use them. You can also use a picture (graphic file) as the background.
If you choose a dark background, you many need to change many of the labels and headings so
they can be seen.
Select the labels of the top row of controls.
Control+click the Date label.
Control+shift+click the rest of the labels of the top row. The border will gradually grow to the right
as you do this until all the labels are enclosed in it.
Figure 31: Selecting multiple labels at one time
Click the Control icon in the Design Form toolbar to open the Properties dialog.
Change the Background color selection from Default to Light cyan. (This is a dropdown list.) Close
the Properties dialog.
Select the other labels in the same way and then change their background color.
To change the font color for the headings:
Open Styles and Formatting using the F11 key. Make sure the Paragraph icon is selected at the
left end of the icons in Figure 32.
Right-click the Heading 2 style to open a pop-up window and select Modify from this menu.
a)
In the Paragraph Style Heading 2 dialog, click the Font Effects tab. Change Font color
from Automatic to Light Cyan.
Figure 32: Styles and Formating window
Click OK to close the dialog.
Tip
Learning how to use styles can be very helpful at times. By using styles, we changed
the font color for all three headings at one time. There are other methods of changing
the font color, but they require repeating the same steps for each heading.
To add a graphic to the background:
Right-click on the background and select Page from the pop-up menu.
On the Page Style dialog, click the Background tab, change the As dropdown list from Color to
Graphic.
30
Getting Started with Base
Click Browse to find and select the graphic file you want to use, and click Open. In the Type section
of the Background tab, select Area.
Click OK to close the dialog. The form should look like Figure 33.
Figure 33: Finished form
Step 11: Change the tab order.
The Tab key moves the cursor from field to field. This is much easier to do than to click each field
to enter data into it. It also permits us to group our expenses into areas before we begin entering
data. For example, all of our meal receipts can be grouped together as can our snacks and also
our fuel purchases.
Control+click the Date field.
1) Click the Form Design icon in the Form Controls toolbar to open the Form Design toolbar
(Figure 34), or choose View > Toolbars > Form Design to open this toolbar.
2) Click the Activation Order icon (circled).
Figure 34: Form Design toolbar with Activation Order icon circled
Rearrange the order of the fields in the Tab Order window.
Find the txtMPayment listing near the bottom of the list and click it.
Click the Move Up button until txtPayment is just below fmtMotel.
Use the same two steps to put the fields in the same order as in Figure 35. Click OK.
Getting Started with Base
31
Figure 35: Tab order for the main form
Save and close the form.
Save the database.
Creating forms and subforms in Design View
This method requires using the Form Controls and Form Design toolbars extensively. These
techniques are beyond the scope of this document. Instructions for creating forms using Design
view will be described in the Database Guide.
32
Getting Started with Base
Accessing other data sources
Apache OpenOffice allows data sources to be accessed and then linked into OOo documents. For
example, a mail merge links an external document containing a list of names and addresses into a
letter, with one copy of the letter being generated for each entry.
To access a data source that is not a *.odb file:
File > New > Database opens the Database Wizard window.
1) Select Connect to an existing database. Click the arrow next to the Database type field and
select the database type from the dropdown list. Click Next.
Click Browse and select the database. Click Next.
Accept the default settings: Register the database for me, and Open the database for editing. Click
Finish. Name and save the database in the location of your choice.
Accessing a spreadsheet as a data source
Accessing a spreadsheet is similar to accessing other databases:
Choose File > New > Database.
Select Connect to an existing database. Select Spreadsheet as the Database type.
Click Browse to locate the spreadsheet you want to access. If the spreadsheet is password
protected, check the Password required box. Click Next.
If the spreadsheet requires a user’s name, enter it. If a password is also required, check its box.
Click Next.
Note
Using this method of accessing a spreadsheet, you cannot change anything in the
spreadsheet. You can only view the contents of the spreadsheet, run queries, and
create reports based upon the data already entered into the spreadsheet.
All changes in a spreadsheet must be made in the spreadsheet itself, using Calc.
After modifying the spreadsheet and saving it, you will see the changes in the
database. If you create and save an additional sheet in your spreadsheet, the
database will have a new table the next time you access it.
Registering *.odb databases
Databases created by OOo2.x or later are in the *.odb (OpenDocument Base) format. Other
programs can also produce databases in this format. Registered a *.odb database is simple:
Choose Tools > Options > OpenOffice Base > Databases.
Under Registered databases, click New.
Browse to where the database is located.
Make sure the registered name is correct.
Click OK.
Note
Sometimes when updating Apache OpenOffie to a newer version, your list of
registered database files disappears. When that happens, you need to use these
steps to register your database files with your latest version of Apache OpenOffice.
Accessing other data sources
33
Using data sources in Apache OpenOffice
Having registered the data source, whether a spreadsheet, text document, external database or
other accepted data source, you can use it in other OpenOffice.org components including Writer
and Calc.
Viewing data sources
Open a document in Writer or Calc. To view the data sources available, press F4 or select View >
Data Sources from the pull-down menu. This brings up a list of registered databases, which will
include Bibliography and any other database registered, such as the Automobile database created
earlier in this chapter.
To view each database, click on the + to the left of the database’s name (see Figure 36). This
brings up Tables and Queries. Click on the + next to Tables to view the individual tables created.
Now click on a table to see all the records held in it.
Figure 36: Databases
Editing data sources
Some data sources can be edited in the View Data Sources dialog. A spreadsheet can not. A
record can be edited, added, or deleted.
The data is displayed on the right side of the screen. Click in a field to edit the value.
Beneath the records are five tiny buttons. The first four move backwards or forwards through the
records, or to the beginning or end. The fifth button, with a small star, inserts a new record.
Insert new record
Figure 37: View Data Sources navigation buttons
To delete a record, right-click on the gray box to the left of a row to highlight the entire row, and
select Delete Rows to remove the selected row.
Figure 38: Deleting a row in the Data View window
Launching Base to work on data sources
You can launch OOo Base at any time from the View Data Source pane. Just right-click on a
database or the Tables or Queries icons and select Edit Database File. Once in Base, you can edit,
add, and delete tables, queries, forms, and reports.
34
Getting Started with Base
Using data sources in Writer and Calc
Data can be placed into Writer and Calc documents from the tables in the data source window. In
Writer, values from individual fields can be inserted. Or, a complete table can be created in the
Writer document. One common way to use a data source is to perform a mail merge.
Tip
Choosing Tools > Mail Merge Wizard or clicking on the Mail Merge icon on the View
Data Source pane launches the Mail Merge wizard which steps you through creating
a mail merge document. See Chapter 11 in the Writer Guide.
Writer documents
To insert a field from a table opened in the data source window into a Writer document, click on the
field name (the gray square at the top of the field list) and, with the left mouse button held down,
drag the field onto the document. In a Writer document, it will appear as <FIELD> (where FIELD is
the name of the field you dragged).
For example, to enter the cost of meals and who paid for them on a certain date of a vacation:
Open the list of data sources (F4) and select the Vacations table in the Automobile database.
3) Use this sentence: “On (date), our breakfast cost (amount) paid by (name), our lunch cost
(amount) paid by (name), and our supper cost (amount) paid by (name).” But only type “On
, our breakfast cost paid by , our lunch cost paid by , and our supper cost paid by .”
To replace (date), click the field name Date in the data source window and drag it to the right of the
word On. The result: On <Date>. If you have Field shadings turned on (View > Field shading),
<Date> has a gray background. Otherwise it does not.
To replace first (amount), click the Breakfast field name and drag it to the right of our breakfast
cost. Make sure you have the proper spacing between the field names and the words before and
after them. Result: breakfast cost <Breakfast>.
To replace the first (name), click the Bpayment field name and drag it to the right of paid by. Result:
paid by <Bpayment>.
In the same way, fill in the rest of the fields in the sentence.
Use <Lunch> and <LPayment> for the second set of (amount) and (name) in the sentence.
Use <Supper> and <SPayment> for the third set of (amount) and (name) in the sentence.
Final result: On <Date>, our breakfast cost <Breakfast> paid by <BPayment>, our lunch cost
<Lunch> paid by <LPayment>, and our supper cost <Supper> paid by <SPayment>.
Add data to the fields of the sentence:
Click the gray box to the left of the row of data you want to add. That row should be highlighted like
the second row of Figure 39.
Click the Data to Fields icon (circled). This should fill the fields with the data from the row you
chose.
Click another row and then click this icon again. The data in the sentence changes to this selected
row of data.
Save the document if you want to use it as an example later.
Accessing other data sources
35
Figure 39: Selected row in data source window
Adding data in table format is a little easier and takes perhaps fewer steps. Some of the steps will
be quite similar.
Navigate to the place you want to place the table and click the location.
Control+Click the gray box to the left of each row of the data source that you want to be a row in
your table when the rows are not consecutive. To select consecutive rows, click the gray box to the
left of the top desired row and Shift+click the bottom desired row.
Click the Data to text icon to open the Insert Database Columns dialog (Figure 40). (The Data to
text icon is to the left of the Data to Fields icon in Figure 39.)
4) Move the fields you want in your table from the Database Columns list to the Table
column(s) list.
To place the fields in the order you select, click the field and use the single arrow to move the fields
in the order you desire. You can also limit the fields you use to less than all of the fields available.
If you want to use all of the fields, use the double arrow pointing to the right to move all of them at
one time. The order of the fields in the table you create will be the same as in the data source
table.
To remove a single field from the Table Column(s) list, click the field and use the single arrow
pointing to the left.
5) To start over, click the double arrow pointing to the left.
Figure 40: Insert Database Columns dialog
Select the settings for your table. Use the default settings as in Figure 40.
Click OK. Save the document.
36
Getting Started with Base
Calc spreadsheets
There are two ways to enter data in a Calc spreadsheet. One enters the data into the spreadsheet
cells. The other creates records in the spreadsheet just like they are done in creating a form in a
database. While you can directly access the data in the spreadsheet cells, you can only see the
data in the records created in the spreadsheet.
Entering data directly to the spreadsheet cells uses the Data to Text icon as we did to make a table
in a Writer document. But differences exist in these two situations.
The steps are straightforward.
Click the cell of the spreadsheet which you want to be the top left of your data including the column
names.
Use F4 to open the database source window and select the table whose data you want to use.
Select the rows of data you want to add to the spreadsheet:
Click the gray box to the left of the row you want to select if only selecting one row. That row is
highlighted.
To select multiple rows, hold down the Control key while clicking the gray box of the rows you
need. Those rows are highlighted.
To select all the rows, click the gray box in the upper left corner. All rows are highlighted.
Click the Data to text icon to insert the data into the spreadsheet cells.
Save the spreadsheet.
Adding records to a spreadsheet is fairly easy. You need to have the Data Source window open,
your spreadsheet open, and the table you want to use selected.
Click the gray box above the field name for the table's ID field.
Drop and drag the gray box for the table's ID field to where you want the record to appear in the
spreadsheet.
Repeat until you have moved all of the fields you need to where you want them.
Name and save the spreadsheet.
Click a row of the table in the Data Source window.
Drag the data in the ID field in the selected row onto the ID field in the spreadsheet. The Save icon
should activate.
Click the Edit File button to make the spreadsheet read only. Click Save when asked if you want to
save the file.
The Data Source window goes blank, the fields in the spreadsheet are populated with data from
the row you selected, and the Form Navigation toolbar appears at the bottom of the spreadsheet.
Figure 41: Navigation arrows of a form
Click the arrows on the Form Navigation toolbar to view the different records of the table. (The
arrows are circled in red.) The number in the box changes when you change the record number by
clicking an arrow. The data in the fields changes correspondingly to the data for that particular
record number.
Accessing other data sources
37
Entering data in a form
Records are used to organize the data we enter into a form. They also organize the data we enter
into a subform.
Each type of field allows a different method to enter the data. In many if not all cases, more than
one method can be used.
The first step to entering data in a form is to open it from the main database window (Figure 1).
Click the Forms icon in the Database list.
Find the form’s name in the Forms list (Vacations).
Double-click the form’s name.
The quickest way to enter a date in the Date field is to click the arrow that opens the dropdown
calendar. Then click the day the you want. Then press the Tab key to go to the Odometer field.
Figure 42: Calendar dropdown
The Odometer, Tolls, and Motel fields are numerical fields. Enter values directly into them, or use
the up and down arrows. When the value is entered, use the Tab key to go to the next field.
Clicking the up arrow increases the value, and the down arrow decreases the value one unit.
These two arrows only change the numerals to the left of the decimal place.
Numerals to the right of the decimal place must be changed by deleting them and typing the
desired ones.
The Motel’s Payment field is a dropdown list. If as in my case, all of the elements of the list start
with different letters, typing the first letter selects the desired entry.
If two or more elements of the list have the same first letter, repeated typing of the first letter will
cycle through the elements with this same first letter.
When the selection is correct, use the Tab key to go to the Misc. field.
The rest of the fields of the main form are either numerical fields or dropdown lists until we reach
the Misc. Notes field. It is a text field. Type anything you desire in this field just as you would any
simple text editor.
Note
38
Since the Tab key is used to move between fields, it can not be used in a text field.
All spacing must be done by the spacebar. Finally, the Enter key only acts as a line
break to move the cursor to the next line. While the Enter key will move from nontext fields to non-text fields, it will not do so from a text field. Use the Tab key
instead.
If we did not have a subform for fuel data, pressing the Tab key in the last field would
save all of the fields, clear them, and make the form ready to accept data on the
second record.
Getting Started with Base
Since we have a subform form, using the Tab key places the cursor in the first Date field of the
subform with the date automatically entered to match the Date field of the main form.
The FuelCost, FuelQuantity, and Odometer fields are numerical fields. The Payment field is a
dropdown list. Enter the data just as you did in the main form, and use the Tab key to go to the next
field.
When you use the Tab key to leave the Payment field, it goes to the Date field of the next line and
automatically enters the date. Now you can enter your second set of fuel data for this day.
To move to another record when the form has a subform, click any of the fields of the main form. In
this case, click the Date field of the main form. Then use the directional arrows at the bottom.
There are four of them from left to right: First Record, Previous Record, Next Record, and Last
Record (Figure 41). To the right of these arrows is the New Record icon.
To create a new record while in another record in the main form, click either the Next Record icon
or the New Record icon.
Tip
The number in the Record box is the number of the record whose data is shown in
the form.
If you know the number of the record you want, you can enter it into the record box
and then press Enter to take you to that record.
Figure 43 is a record with data inserted in its fields.
Figure 43: Sample record of the Vacation form and subform
Entering data in a form
39
Creating queries
Queries are used to get specific information from a database. Query results are special tables
within the database.
To demonstrate the use of queries, we will use two different methods:
Using our CD-Collection table, we will create a list of albums by a particular artist. We will do this
using the Wizard.
• The information we might want from the Fuel table includes what our fuel economy is. We
will do this using the Design View. (Queries that require calculations are best created with
the Design view.)
Using the Wizard to create a query
Queries created by the wizard provide a list or lists of information based upon what one wants to
know. It is possible to obtain a single answer or multiple answers, depending upon the
circumstances.
In the main database window (Figure 1), click the Queries icon in the Databases section, then in
the Tasks section, click Use Wizard to Create Query. The Query Wizard window opens (Figure 44).
The information we want is what albums are by a certain musical group or individual (the album’s
author). We can include when each album was bought.
Note
When working with a query, more than one table can be used. Since different tables
may contain the same field names, the format for naming fields in a query is Table
name.field name, with a period (.) between the table name and the field name. For
example, The Lunch field of the Vacation table used in a query has the name
Vacation.Lunch.
Step 1: Select the fields.
Select the CD-Collection table from the dropdown list of tables.
Select fields from the CD-Collection table in the Available fields list.
Click Artist, and use the > button to move it to the Fields in the Query list.
Move the AlbumTitle and DatePurchased fields in the same manner.
Click Next.
Tip
40
To change the order of the fields, select the field you want to move and click the up or
down arrow.
Getting Started with Base
Figure 44: First page of the Query Wizard
Step 2: Select the sorting order.
Up to four fields can be used to sort the information of our query. A little simple logic helps at this
point. Which field is most important?
In our query, the artist is most important. The album title is less important, and the date purchased
is of least importance. Of course, if we were interested in what music we bought on a given day,
the date purchased would be the most important.
Figure 45: Sorting order page
Click the first Sort by dropdown list.
Click CD-Collection.Artist to select it.
To list the artists in alphabetical order (a-z), select Ascending on the right.
Click the second Sort by dropdown list.
Click CD-Collection.ArtistTitle. and select Ascending.
Repeat this process for CD-Collection.DatePurchased.
Click Next.
Step 3: Select the search conditions.
The search conditions allow us to compare the name we entered with the names of the artist in our
database and decide whether to include a particular artist in our query or not.
is equal to: the same as
is not equal to: not the same as
is smaller than: comes before
Getting Started with Base
41
is greater than: comes after
is equal or less than: the same as or comes before
is equal or greater than: the same as or comes after
like: similar to in some way
Note
These conditions apply to numbers, letters (using the alphabetical order), and dates.
Since we are only searching for one thing, we will use the default setting of Match all of the
following.
We are looking for a particular artist, so select CD-Collection. Artist in the Fields list and is equal to
as the Condition.
Type the name of the artist in the Value box. Click Next.
Step 4: Select type of query.
We want simple information, so the default setting: Detailed query is what we want. Click Next at
the bottom of the window.
Note
Since we have a simple query, the Grouping and Grouping conditions are not
needed. Steps 5 and 6 of the wizard are skipped in our query.
Step 7: Assign aliases if desired.
We want the default settings. Click Next.
Step 8: Overview.
Name the query (suggestion: Query_Artists). To the right of this are two choices. Select Display
Query. Click Finish.
Using the Design View to create a query
Creating a query using Design View is not as difficult as it may first seem. It may take multiple
steps, but each step is fairly simple.
What fuel economy is our vehicle getting (miles per gallon in the USA)? This question requires
creating two queries, with the first query used as part of the second query.
Step 1: Open the first query in Design View.
Click Create Query in Design View.
Step 2: Add tables.
Figure 46: Add Tables or Query window
Click Fuel to highlight it.
42
Getting Started with Base
Click Add. Click Close.
Tip
Move the cursor over the bottom edge of the fuel table (Figure 47) and drag the to
make it longer and easier to see all of the fields in the table.
Figure 47: Fuel table in query
Step 3: Add fields to the table at the bottom.
Double-click the FuelID field in the Fuel table.
Double-click the Odometer field.
Double-click the FuelQuantity field.
The table at the bottom of the query window should now have three columns.
Figure 48: Query table
Step 4: Set the criterion for the query.
We want the query’s FuelID to begin with the numeral 1.
Type >0 in the Criterion cell under FuelID in the query table.
Click the Run Query icon in the Query Design toolbar.
Figure 49: Query Design toolbar
Figure 50 contains the Fuel table with my entries and the query results based upon the Fuel table:
the query results are in the right table.
Getting Started with Base
43
Figure 50: Fuel table and query of the fuel table
Step 5: Save and close the query.
Since this query contains the ending odometer reading for our calculations, name it End-Reading
when saving it. Then close the query.
Step 6: Create the query to calculate the fuel economy.
Click Create Query in Design View to open a new query.
Add the Fuel table to the query just as you did in step 2: Add tables But, do not close the Add
Tables window.
Add the End-Reading query to this query.
Click Queries to get the list of queries in the database.
Figure 51: Selecting queries to add to another query
Click End-Reading.
Click Add, and then click Close.
Step 7: Add fields to the table at the bottom of the query.
We are going to calculate the fuel economy. To do this we need the FuelQuantity and distance
traveled. Since the FuelQuantity we want to use is at the ending odometer reading, we will use the
End-Reading query to get it. We will also use the Odometer field from the Fuel table and EndReading query.
Figure 52: Tables in this query
Double-click FuelQuantity in the End-Reading query.
Double-click Odometer in the End-Reading query.
Double-click Odometer in the Fuel table.
44
Getting Started with Base
Figure 53: Added fields to the query
Step 8: Enter the FuelID difference field.
We want the difference between the FuelID value of the Fuel table and FuelID value of the EndReading query to equal one (1).
Type "End-Reading".FuelID - Fuel.FuelID in the field to the right of the Odometer field of the Fuel
Table.
Type the numeral 1 (one) in the Criterion cell of this column.
Figure 54: Typing in calculation of fields
Calculate the distance traveled:
Type "End-Reading".Odometer – Fuel.Odometer in the Field cell.
Type >0 in the Criterion cell.
Figure 55: Field for distance traveled calculations
Calculate fuel economy:
Type ("End-Reading".Odometer – Fuel.Odometer)/"End-Reading".FuelQuantity in the next column
to the right of the word Field.
Getting Started with Base
45
Figure 56: Fuel economy calculation field
Note
When entering fields for these calculations, you must follow this format: table or
query name followed by a period follow by the field name. For hyphenated or
multiple-word names (table or query), use double quotes around the table or query
name. The query will then add the rest of the double quotes as in Figure 56.
Use the arithmetical symbol between the two. More than one calculation can be
done by using parentheses to group the arithmetical operations.
Step 9: Run the query and make some modification.
After we run the query to make sure it works correctly, we will hide all of the fields that we do not
need.
Click the Run Query icon in the Design Query toolbar (Figure 49). The results are in Figure 57.
Figure 57: Result of running the fuel economy query
Notice that not all of the last column label is visible because some of the labels are long. We can
fix this problem by using an alias for many of the fields. The labels are replaced by their aliases.
Add Aliases:
Type in the aliases as they are listed in Figure 58.
Figure 58: Query table with aliases added
Run the query again. The results are in Figure 59.
Figure 59: Query run with aliases
We really do not need the column showing the difference between the FuelID fields from the table
and query, so we will hide it. While it will not be visible, it will still be used in the calculations.
Hide a field that does not need to be seen.
Remove the check in the box of the Visible cell as in Figure 60.
46
Getting Started with Base
Figure 60: Making a field invisible in a query run
Rerun the query (Figure 61).
Figure 61: Query run with aliases
Step 10: Close, save, and name the query.
My suggestion for a name is Fuel Economy.
There are obviously other calculations that can be made in this query such as cost per distance
traveled and how much of the cost belongs to each of the payments types.
Note
To fully use queries requires a knowledge of set operations (unions, intersections,
and, or, complements, and any combinations of these). Having a copy of the Hsqldb
User Guide, available from http://hsqldb.org/, is also extremely useful.
Getting Started with Base
47
Creating reports
Reports provide information found in the database in a useful way. In this they are similar to
queries. Reports are generated from the database’s tables or queries. They can contain all of the
fields of the table or query or just a selected group of fields. Reports can be static or dynamic.
Static reports contain the data in the selected fields at the time the report was created. Dynamic
reports can be updated to show the latest data.
For example, a report on expenses for a vacation in the past should probably be a static report
because it is based upon specific data that does not change. However, a report on the fuel data
should probably be a dynamic report, because this report depends upon data that does change.
Caution
Dynamic reports update only the data that is changed or added to a table or query.
They do not show any modifications made to the table or query itself. For example,
after creating the report below, open the fuel economy query created in the previous
section. For the "End-Reading".”Odometer – Fuel.”Odometer” column, change the
number 1 to the number 3. The report will be identical before and after you make the
change.
All reports are based upon a single table or query. So you need first to decide what fields you want
to use in the report. If you want to use fields from different tables, you must first combine these
fields in a single query. Then you can create a report on this query.
For example, a report on vacation expenses includes both fuel costs and meal costs. These values
are contained in fields of two different tables: Vacations and Fuel. So this report requires creating a
query.
Creating a static report
We will create a report on vacation expenses. Certain questions need to be asked before creating
the report.
What information do we want in the report?
How do we want the information arranged?
What fields are required to provide this information?
Will a query have to be created because these fields are in different tables?
Are there any calculations required in the data before being added to the report?
The expenses for our vacation are motel, tolls, miscellaneous, breakfast, lunch, supper, snacks,
and fuel. One possible report would simply list the totals of each of these expense groups. Another
possible report would list the expense totals for each day of the vacation. A third possible report
would list the totals for each expense group for each type of payment. (This would let us know
where the money came from to pay the expenses.) The best way to create reports like these is to
create the queries needed to gather the needed data, insert the query data into a spreadsheet, and
use the necessary Calc functions on this data.
We will create two reports, one listing the expenses each day other than fuel and the second listing
the fuel costs each day.
The fields we need for the first report from the Vacations table are: Date, Motel, Toll, Breakfast,
Lunch, Supper, SnackCost, and Miscellaneous. This report will not require an additional query.
The second report involves the Fuel table. Since this table includes fuel purchases at times other
than during the vacation, we need to create a query that contains only the fuel purchased during
the vacation.
48
Getting Started with Base
Vacations table report
To create a new report.
Click the Reports icon in the Database list in the Automobile – OpenOffice.org Base window
(Figure 1).
In the Tasks list, click Use Wizard to Create Report. The Report Wizard opens.
Step 1: Field selection
Select Table: Vacations in the Tables or Queries dropdown list.
Use the > to move these fields from the Available fields list to the Fields in report list: Date, Motel,
Tolls, Miscellaneous, Breakfast, Lunch, Supper, and SnackCost. Click Next.
Figure 62: Adding fields to a report
Step 2: Labeling fields
Change any field labels you wish. We will shorten Miscellaneous to Misc. Click Next.
Step 3: Grouping
Since we are grouping by the date, use the > button to move the Date field to the Grouping list.
Click Next.
Figure 63: Selecting fields for grouping data
Step 4: Sort options
We do not want to do any additional sorting. Click Next.
Step 5: Choose layout
Use default settings for the layout. Click Next.
Step 6: Create report
Label the report: Vacation Expenses.
Select Static report.
Getting Started with Base
49
Click Finish.
If you feel adventurous, try selecting some of the other layout choices. After
selecting a choice, drag the Report Wizard window out of the way so that you can
see what you have selected. (Move the cursor over the Title Bar of the window, and
then drag and drop.)
Note
Vacation fuel report
Create a query containing only fuel bought on the days of the vacation.
Open a query in Design View.
a)
Follow the steps for adding tables in “Add tables” on page 42 to add the Fuel table.
b)
In the Fuel table, double-click Date and FuelCost to enter them in the table at the
bottom of the query.
In the Criterion cell of the Date field, type the following: BETWEEN #5/25/2007# AND #5/26/2007#
Figure 64: Setting the criterion for a query
Save, name, and close the query. (Suggestion: Vacation Fuel Purchases.)
Tip
When using dates in a query, enter them in numerical form MM/DD/YYYY or
DD/MM/YYYY depending upon your language's default setting for dates (my default
setting is MM/DD/YYYY).
Each date must have a # before and after it. Hence, May 25, 2007 is written
#05/25/2007# or #25/5/2007# depending upon your language’s default setting for
dates.
Open a new report.
Right-click the Vacation Fuel Purchases query.
Select Report Wizard from the pop-up menu.
Note
When a new report is opened in this way, the query used to open it is automatically
selected in the Tables or queries dropdown list in the Report Wizard.
Create the report.
Use >> to move both fields from the Available fields list to the Fields in report list. Click Next.
Label fields.
Add a space to FuelCost to make it Fuel Cost (two words). Click Next.
Group fields.
Click Date to highlight it. Use > to move the Date field to the Groupings list. Click Next.
Choose layout.
50
Getting Started with Base
We will be making no changes in the layout. Click Next.
Create report (final settings).
Use the suggested name, which is the same as the query.
Select Static report. Click Finish.
Creating a dynamic report
Now we will create a report with some statistics on our fuel consumption. To do this, we have to
modify two queries: End-Reading and Fuel Economy. We will be adding the FuelCost field to the
End-Reading query. Then we will add the FuelCost field from the End-Reading query to the Fuel
Economy query.
Tip
When opening a query to edit it, it might appear as in Figure 65. If you move your
cursor over the black line (circled), it becomes a double headed arrow. Drag it to a
lower position.
Figure 65: Appearance of query when opened for editing
Add the FuelCost field to the End-Reading query:
Right-click the End-Reading query and select Edit from the pop-up menu.
In the Fuel table list, double-click to add FuelCost to the bottom table (Figure 66).
Save and close the query.
Figure 66: Adding an additional field to the query
Add the FuelCost field from the End-Reading query to the Fuel Economy query:
Getting Started with Base
51
Right-click the Fuel Economy query and select Edit from the pop-up menu.
Double-click the FuelCost field in the End-Reading query list to add it to the query table at the
bottom.
Add a calculation field to the right of the FuelCost field.
Type the following in a Field cell in the table at the bottom:
"End-Reading".FuelCost/("End-Reading".Odometer – Fuel.Odometer)
Type the following in its Alias cell: cost per mile.
Note
If you use the metric system, cost per km is the appropriate alias.
Save and close the query.
Open a new report.
Right-click the Fuel Economy query and select Report Wizard.
Select fields.
Move all the fields from the Available fields to the Fields in report list. Use the >> to do so. Click
Next.
Label fields.
Change FuelCost to Fuel Cost by placing a space between the words. Click Next.
Group fields.
Use > to move the Date field to the Groupings list. Click Next.
Sort options: the wizard skipped this one.
Choose layout: accept the default. Click Next.
Create the report.
Change the report name to Fuel Statistics.
The default setting is Dynamic report, so no change is necessary.
Select Modify report layout.
Click Finish.
Modifying a report
At the end of the last section, we left the Fuel Statistics report open in the edit mode (Figure 67).
We will be working on that report. These same steps can be used with any report that you open for
editing.
52
Getting Started with Base
Figure 67: A report in edit mode
The Author is the name you listed in Tools > Options > OpenOffice.org > User Data. The date is not
correct. The columns need to be moved to the left to give a better appearance. None of the
numbers are correct, but their only purpose is to show the number of decimal places.
Step 1: Change the date.
Click to the right of the date (4/26/20) so that the cursor is next to the field. Use the Backspace key
to erase the date.
Insert > Fields > Date. This places today’s date where the original date was.
Change the date formatting:
Double-click the date field you just inserted. The Edit Fields: Document window opens.
Figure 68: Modifying a date field
Since this is a dynamic report, change the Select field from Date (fixed) to Date.
Change the Format to what you desire. (I use the Friday, December 31, 1999 choice.) Click OK.
Step 2: Change the column widths.
The column widths can be changed by moving the cursor over the right border of each column so
that it becomes a double-headed arrow. Then drag and drop it to where you want it. This has to be
done for each column in each table in the report. This can also be done with the last column on the
right even though there is no black border. It should now look something like Figure 69.
Getting Started with Base
53
Figure 69: Realigned columns in a report
Step 3: Change the number formatting in the cells.
The fuel quantity should have three decimal places. The Begin, End, and Distance should have
one decimal place. Fuel Cost should be currency and have two decimal places, and Cost per mile
should have three decimal places.
1) Right-click the cell below Quantity and select Number format. (The cell is circled in Figure
69.)
In the Options section (Figure 70),
Change the number of Decimal places to 3.
Click the green checkmark. Click OK.
Figure 70: Option section of the Number Formating window
Change the Cost per mile field.
Right-click in the cell below Fuel Cost.
Select Number Format.
In the Category list, select Currency. Click OK.
Change the Fuel Cost field.
Right-click in the cell below Cost per mile.
Select Number Format.
In the Category list, select Currency.
In the Option section:
Set the number of decimal places to 3.
Click the green checkmark.
Click OK.
Step 4: Save and close the report.
Double-click the report. It should now look like Figure 71.
54
Getting Started with Base
Figure 71: Final report
Getting Started with Base
55
Apendix 1 HSQL-SDBC internal query procedures
Overview
The HSQLdb database engine included with Base supports the following functions and stored
procedures for use within queries.
The Query component in Base allows for SQL commands that return a result set. i.e. SELECT and
CALL
The component supports two views:
GUI Query Designer (Designer View)
Text editor (SQL View)
Queries created and executed in Designer and SQL View support the use of named replaceable
parameters in these statements, in most cases. Use of this feature is controlled by the option
'Escape Processing'.
Escape Processing is always ENABLED when using Designer View.
Escape Processing is ENABLED by default in SQL View, but may be DISABLED by
selecting the 'Run SQL directly' tool button.
The SQL window in Base (opened with the menu commands TOOLS > SQL) allows any valid SQL
statement to be executed, but it does not return any data results to the user. Statements executed
in this window serve two main purposes.
Data Manipulation Language ( DML ) statements. i.e. UPDATE, DELETE, INSERT.
Data Definition Language ( DDL ) statements. i.e. CREATE TABLE, ALTER TABLE, etc.
Multiple statements may be executed as a batch by ending each statement with a semi-colon.
All functions listed below are available for use in the SQL window.
Each table below is formatted as follows:
Function Name - this is the actual function, along with required or optional parameters
Designer - Yes in this column means it may be used in Designer View. No, the function
must be used in SQL View.
Esc Proc - Yes in this column means it may be used in SQL View, with escape processing
ENABLED. No, the function is only available in SQL View with escape processing
DISABLED.
Comments - A brief description of what the function does, the parameters expected and the
type of output generated.
Numerical Functions
Function Name
Comments
ABS(d)
Returns the absolute value of a number.
ABS( -1 ) = ABS( 1 )
ACOS(d)
Returns the arc cosine of an angle, in the range of 0.0
through pi.
ACOS( .5 ) = 1.05
56
Getting Started with Base
ASIN(d)
Returns the arc sine of an angle, in the range of -pi/2
through pi/2.
ASIN( .5 ) = 0.52
ATAN(d)
Returns the arc tangent of an angle, in the range of -pi/2
through pi/2.
ATAN( .5 ) = 0.46
ATAN2(a,b)
Returns the tangent of a/b.
ATAN2( 1, 2 ) = 0.46
BITAND(a,b)
Returns a & b.
BITAND( 0, 1 ) = 0
BITOR(a,b)
Returns a | b
BITOR( 0,1 ) = 1
BITXOR(a,b)
Returns the bit-wise logical xor of the given integer values.
BITXOR( 0, 1 ) = 1
CEILING(d)
Rreturns the smallest integer that is not less than d
CEILING( 8.7 ) = 9
COS(d)
Returns the trigonometric cosine of an angle.
COS( .5 ) = 0.88
COT(d)
Returns the cotangent of an angle.
COT( .5 ) = 1.83
DEGREES(d)
Converts radians to degrees.
DEGREES( 1 ) = 57.29577951
EXP(d)
Returns the exponential number e (i.e., 2.718...) raised to
the power of a double value.
EXP( 2 ) = 7.389056
FLOOR(d)
Returns the largest double value that is not greater than
the d.
FLOOR( -8.7 ) = -9
LOG(d)
Returns the natural logarithm (base e) of d.
d must be greater than 0.0.
LOG( 1.5 ) = 0.41
LOG( -1 ) = -1.#NAN
LOG10(d)
Returns the logarithm (base 10) of d.
d must be greater than 0.0.
LOG10( 1.5 ) = 0.18
LOG10( -1 ) = -1.#NAN
Getting Started with Base
57
MOD(a,b)
Returns a modulo b
MOD( 7, 2 ) = 1
PI()
The double value that is closer than any other to pi, the
ratio of the circumference of a circle to its diameter.
PI() = 3.14159265
POWER(a,b)
Returns of value of the first argument, a, raised to the
power of the second argument, b.
POWER( 2, 2 ) = 4
RADIANS(d)
Converts degrees to radians
RADIANS( 1 ) = 0.01745329
RAND()
Returns a random number x >= 0.0 and < 1.0
RAND() MIGHT EQUAL 0.34
ROUND(a,b)
Rounds a to b digits after the decimal point.
ROUND( 1.0333, 2 ) = 1.0300
ROUNDMAGIC(d)
solves certain rounding problems, specifically when
numbers approach 0.0 such as 3.11-3.1-0.001
ROUNDMAGIC( 3.11-3.1-0.001 ) = 0.01
* Currently when used with escape processing enabled the
return value is changed to a string. The workaround for
this is to cast the result back to a dboule.
CAST( ROUNDMAGIC( D ) AS DOUBLE )
See Issue#81031
SIGN( d )
Returns -1 if d is smaller than 0, 0 if d==0 and 1 if d is
bigger than 0
SIGN( -0.001 ) = -1
SIN(d)
Returns the trigonometric sine of an angle.
d is an angle in radians
SIN( PI() / 12 ) = 0.25881905
SQRT( d )
Returns the square root of d. <br. SQRT( 9 ) = 3
TAN( A )
Returns the trigonometric tangent of an angle, A.
A - and angle in in radians.
TAN( 0.01745329 * 20 ) = 0.36397018
TRUNCATE(a,b)
Truncates a to b digits after the decimal point.
TRUNCATE( 1.0333, 3 ) = 1.0330
58
Getting Started with Base
String Functions
Function Name
Comments
ASCII(s)
Returns the Unicode code value of the leftmost character ofs
as an int. This is the same as the ASCII value if the string
contains only ASCII characters.
ASCII( 'ONE' ) = 79
BIT_LENGTH(str)
Returns the length of the string in bits
BIT_LENGTH ( 'ONE' ) = 48
Note Each character is assumed to be 16 bits long.
CHAR(c)
Returns the character string corresponding to the given
ASCII (or Unicode) value C.
Note: In some SQL CLI implementations, a null is returned if
the range is outside 0..255.
In HSQLDB, the corresponding Unicode character is returned
unchecked.
CHAR( 79 ) = O
CHAR_LENGTH(str)
Returns the length of the string in characters
CHAR_LENGTH('ONE') = 3
CONCAT(str1,str2)
Returns str1 + str2
CONCAT( 'ONE', 'HUNDRED' ) = ONEHUNDRED
DIFFERENCE(s1,s2)
Returns the difference between the sound of s1 and s2. If
either String is NULL, zero is returned.
DIFFERENCE( 'SMITH', 'SMYTH' ) = 0 ;
DIFFERENCE( 'WILD', 'CHILD' ) = 1 ;
DIFFERENCE( 'TUPLE', 'SUPPLE' ) = 1 ;
DIFFERENCE( 'BRAKE', 'BIKE' ) = 2
HEXTORAW(s1)
Returns translated string ; The given String must consist of a
sequence of 4 digit hexidecimal character substrings. If its
length is not evenly divisible by 4, null is returned. If any of its
4 character subsequences cannot be parsed as a 4 digit,
base 16 value, then a NumberFormatException is thrown.
'00FF', '00ff00ff' is acceptable ; '0x00FF', 'FF' is NOT and will
return null
HEXTORAW( '0041' ) = A ; HEXTORAW( 'FF41' ) = a ;
HEXTORAW( '00410061' ) = Aa
INSERT(s,start,len,s2)
Getting Started with Base
Returns a character sequence which is the result of writing
the first length number of characters from the second given
String over the first string. The start position in the first string
where the characters are overwritten is given by start.
Note: In order of precedence, boundry conditions are
handled as follows:
if either supplied String is null, then the other is returned; the
check starts with the first given String.
if start is less than one, s1 is returned
if length is less than or equal to zero, s1 is returned
if the length of s2 is zero, s1 is returned
59
if start is greater than the length of s1, s1 is returned
if length is such that, taken together with start, the indicated
interval extends beyond the end of s1, then the insertion is
performed precisely as if upon a copy of s1 extended in
length to just include the indicated interval.
INSERT( 'How brown cow.', 5, 1, 'now ' ) = How now brown
cow.
LCASE(s)
Converts s to lower case
LCASE( 'ONE' ) = one
LEFT(s,count)
Returns the leftmost count of characters of s
Note: boundry conditions are handled in the following order
of precedence:
if s is null, then null is returned
if count is less than 1, then a zero-length String is returned
if count is greater than the length of s, then a copy of s is
returned
- requires double quoting - use SUBSTRING() instead
LEFT( 'ONE', 2 ) = ON
LENGTH(s)
Returns the number of characters in s
LENGTH( 'ONE' ) = 3
LOCATE(search,s,[start])
Returns the first index (1=left, 0=not found) where search is
found in s, starting at start
LOCATE( 'ME', 'FIND ME IF YOU CAN', 1 ) = 6 ;
LOCATE( 'ME', 'FIND ME IF YOU CAN', 7 ) = 0
LTRIM(s)
Removes all leading blanks in s
LTRIM( ' ONE ' ) = "ONE "
LOWER(s)
Converts s to lower case
LOWER( 'ONE' ) = one
OCTET_LENGTH(str)
Returns the length of the string in bytes (twice the number of
characters)
OCTET_LENGTH( 'ONE' ) = 6
RAWTOHEX(s1)
Returns translated string, where s1 is any character string
and returns the string representation of the characters as hex
values
RAWTOHEX( 'A' ) = 0041 ; RAWTOHEX( 'Aa' ) = 00410061
POSITION (<string expression> IN <string
expression 1>)
If the first string is a sub-string of the second one, returns the
position of the sub-string, counting from one; otherwise 0
POSITION ( 'THIS' IN 'THIS AND THAT' ) = 1
REPEAT(s,count)
Returns s repeated count times
REPEAT( 'X', 4 ) = XXXX
60
Getting Started with Base
REPLACE(s,replace,s2)
Replaces all occurrences of replace in s with s2
REPLACE( 'WHAT XXXX BROWN COW.', 'XXXX', 'NOW' ) =
WHAT NOW BROWN COW.
Returns the rightmost count of characters of s
RIGHT(s,count)
Note:Boundry conditions are handled in the following order of
precedence:
if s is null, null is returned
if count is less than one, a zero-length String is returned
if count is greater than the length of s, a copy of s is returned
RIGHT( 'THIS AND THAT', 4 ) = THAT
RTRIM(s)
Removes all trailing spaces
RTRIM( ' ONE ' ) = " ONE"
SOUNDEX(s)
Returns a four character code representing the sound of s.
Non-ASCCI characters in the input String are ignored.
SOUNDEX( 'SMITH' ) = S530 ; SOUNDEX( 'SMYTH' ) =
S530
SPACE(count)
Returns a string consisting of count spaces
SPACE( 4 ) = " "
SUBSTR(s,start[,len])
SUBSTRING(s,start[,len])
Returns the substring starting at start (1=left) with length len
Note: The rules for boundary conditions on s, start and length
are,in order of precedence:
1.) if s is null, return null
2.) If length is less than 1, return null.
3.) If start is 0, it is treated as 1.
4.) If start is positive, count from the beginning of s to find the
first character postion.
5.) If start is negative, count backwards from the end of s to
find the first character.
6.) If, after applying 2.) or 3.), the start position lies outside s,
then return null
7.) if length is ommited or is greated than the number of
characters from the start position to the end of s, return the
remaineder of s, starting with the start position.
SUBSTR( 'HERE I AM', 6, 1 ) = I ; SUBSTR( 'HERE I AM', 6 )
= I AM
SUBSTRING( s FROM start [FOR len] )
Alternate syntax where s may be a string expression
SUBSTRING ( 'HERE I AM' FROM 6 FOR 1 ) = I ;
SUBSTRING ( 'HERE I AM' FROM 6 ) = I AM
TRIM( [[ LEADING | TRAILING | BOTH ] [TRIMSTR]]
FROM s )
Returns the character sequence s, with the leading, trailing or
both the leading and trailing occurences of the first character
of the character sequence trimstr removed.
If trimstr is not supplied SPACE is used.
TRIM( BOTH FROM ' ONE ' ) = "ONE" ; TRIM ( BOTH 'O'
FROM 'OONEOO' ) = NE
* Note with escape processing DISABLED the command may
be abbreviated to TRIM ( FROM ' ONE ' ) AS "OUTPUT" =
"ONE" - An alias must be used in this case also
Getting Started with Base
61
UCASE(s)
Converts s to upper case
UCASE( 'one' ) = ONE
UPPER(s)
Converts s to upper case
UPPER( 'one' ) = ONE
Date and Time Functions
Function Name
Comments
CURDATE()
Returns the current date. This is the current system date on
your PC.
CURDATE() = 09/01/07
NOTE - The parenthesize are required.
CURTIME()
Returns the current time. This is the current system time on
your PC.
CURTIME() = 10:16:04 PM
NOTE - The parenthesize are required.
DATEDIFF(string, datetime1, datetime2)
Returns the count of units of time elapsed from datetime1 to
datetime2. The string indicates the unit of time and can have
the following values 'ms'='millisecond',
'ss'='second','mi'='minute','hh'='hour', 'dd'='day', 'mm'='month',
'yy' = 'year'. Both the long and short form of the strings can be
used.
DATEDIFF('dd', '2007-08-01', '2007-09-01' ) = 31
DAYNAME(date)
Returns the name of the day of the week.
DAYNAME( '2007-09-01' ) = Saturday
DAYOFMONTH(date)
Returns the day of the month (1-31)
DAYOFMONTH( '2007-09-01' ) = 1
DAYOFWEEK(date)
Returns the day of the week (1 means Sunday)
DAYOFWEEK( '2007-09-01' ) = 7
DAYOFYEAR(date)
Returns the day of the year (1-366)
DAYOFYEAR( '2007-09-01' ) = 244
HOUR(time)
Return the hour (0-23)
HOUR( '21:16:04' )
MINUTE(time)
Returns the minute (0-59)
MINUTE( '21:16:04' ) = 16
MONTH(date)
Returns the month (1-12)
MONTH( '2007-09-01' ) = 9
62
Getting Started with Base
MONTHNAME(date)
Returns the name of the month,
MONTHNAME( '2007-09-01' ) = September
NOW()
Returns the current date and time as a timestamp)
use of CURRENT_TIMESTAMP instead is suggested
NOW() = 09/01/07 10:34 PM
QUARTER(date)
Returns the quarter (1-4), with the new year starting in
January
QUARTER( '2007-09-01' ) = 3
SECOND(time)
Returns the second (0-59)
SECOND( CURRENT_TIME ) MAY EQUAL 6
WEEK(date)
Returns the week of this year (1-53)
WEEK( '2007-09-01' ) = 35
YEAR(date)
Returns the year
YEAR( '2007-09-01' ) = 2007
CURRENT_DATE
Returns the current date
CURRENT_DATE = 09/01/07
CURRENT_TIME
Returns the current time
CURRENT_TIME = 10:44:28 PM
CURRENT_TIMESTAMP
Returns the current timestamp
CURRENT_TIMESTAMP = 09/01/07 10:34 PM
Returns a string from a date or datetime, based on the format
mask
Following is a list of valid format mask character sequences,
TO_CHAR( datetime, format String )
Getting Started with Base
Chr seq
returned value
example
YYYY
4 digit year
TO_CHAR( CURRE
NT_TIMESTAMP,
'YYYY' ) = 2007
YYY
YY
Y
Last 3, 2 or 1
digits of year
TO_CHAR( CURRE
NT_TIMESTAMP,
'YY' ) = 07
IYYY
IYY
IY
Last 4, 3, 2
digits of ISO
year
TO_CHAR( CURRE
NT_TIMESTAMP,
'IY' ) = 07
MM
Month (01-12;
JAN = 01)
TO_CHAR( CURRE
NT_TIMESTAMP,
'MM' ) = 09
MON
Abbreviated
name of month
TO_CHAR( CURRE
NT_TIMESTAMP,
'MON' ) = Sep
63
MONTH
Name of month,
padded with
blanks to length
of 9 characters.
TO_CHAR( CURRE
NT_TIMESTAMP,
'MONTH' ) =
September
w
Week of year
TO_CHAR( CURRE
NT_DATE, 'w' ) = 35
W
Week of month
TO_CHAR( CURRE
NT_DATE, 'W' ) = 1
IW
Week of year (152 or 1-53)
based on the
ISO standard.
TO_CHAR( CURRE
NT_DATE, 'IW' ) =
35
d
Day of week (17)
TO_CHAR( CURRE
NT_DATE, 'd' ) = 1
D
Abbreviation for
day of week
TO_CHAR( CURRE
NT_DATE, 'D' ) =
Sat
DD
dd
Day of month as
2 digits
TO_CHAR( CURRE
NT_DATE, 'DD' ) =
01
DDD
Day of year
TO_CHAR( CURRE
NT_DATE, 'DDD' ) =
244
H
Hour of day 0 23
TO_CHAR( CURRE
NT_TIME, 'H' ) = 23
HH
Hour of day 0-11
TO_CHAR( CURRE
NT_TIME, 'HH' ) =
11
m
Minute of
current hour
TO_CHAR( CURRE
NT_TIME, 'm' ) = 48
s
Seconds of
current minute
TO_CHAR( CURRE
NT_TIME, 's' ) = 33
a
AM or PM
TO_CHAR( CURRE
NT_TIME, 'a' ) = PM
LITERALS
TO_CHAR( CURRE
NT_DATE, 'D MON, dd YYYY' ) =
Sat - Sep, 01 2007
All other
characte
rs
System Functions
Function Name
DATABASE()
64
Comments
Returns the fully qualified file name of the Base file
DATABASE() = C:\Documents and Settings\HP_Owner\My
Getting Started with Base
Documents\Forum\ChucrchLibrary\new_library.odb
USER()
Returns the name of the user connected to the Base database
NOTE - This command requires use of the parentheses.
USER() = SA
CURRENT_USER
Returns the name of the user connected to the Base database. This
is actually a macro that calls the function USER().
NOTE - Use of parentheses is not allowed with this macro.
CURRENT_USER = SA
IDENTITY()
Returns the last identity value that was inserted by this connection.
Aggregate Functions
Aggregate functions are used to perform some computation against group of values. Each field in a
table can be thought of as one group of values. Use of the GROUP BY clause in a select
statement allows the creation of multiple value groups.
Function Name
Comments
COUNT( Any | * )
Returns the count of not null entries in a column or when used with *
the count of records.
MIN(d)
Returns the smallest value in a group.
MAX(d)
Returns the largest value in a group.
SUM(d)
Adds all values in a group together.
AVG(d)
Returns the average for the group of values.
SOME(b)
Returns TRUE if any value in a group = TRUE
EVERY(b)
Returns TRUE only if all values in a group = TRUE.
Statistical Functions
Function Name
VAR_POP
Getting Started with Base
Comments
Returns the biased variance of a group of numbers.
65
VAR_SAMP
Returns the sample variance of a group of numbers.
STDDEV_POP
STDDEV_SAMP
Modifiers
You may want to modify the results returned by a query to either limit the number of records
returned or you may want to only returns records with unique values. This is accomplished by
using the SELECT statement modifiers LIMIT, TOP, or DISTINCT.
In the case of LIMIT and TOP, Base does not allow their use without turning 'Escape Processing'
off first. This is done in the query design window by 1) Turn of the GUI designer 2) Select the 'Run
SQL Direct' toolbar button.
Example Data
TaskID
2
3
4
5
6
7
8
9
10
11
StartDate
01/01/07
01/01/07
01/02/07
01/02/07
01/03/07
01/04/07
02/01/07
02/11/07
03/01/08
03/02/08
EndDate
01/01/07
01/02/07
01/02/07
01/03/07
01/03/07
01/04/07
02/10/07
02/11/07
03/02/07
03/03/07
Description
Task1
Task2
Task3
Task4
Task5
Task6
Task7
Task8
Task9
Task10
Limit
The modifier LIMIT can be used in either of two ways
Just after the word SELECT - when used it you must supply two parameters 'Starting
Record' and 'Number of rows' separated by a space
At the end of a select statement, IF the statement contains a HAVING, GROUP BY or
ORDER BY clause. - Here you may supply one or two parameters. The 'number of rows'
and optionally the 'Starting Record' designated by the word OFFSET
Examples:
SELECT LIMIT 3 2 "TaskID", "StartDate", "EndDate", "Description" FROM
"Tasks"
This can be read as - return 2 rows, skipping the first 3 records in the result set.
The returned result set would be
TaskID
5
6
66
StartDate
01/02/07
01/03/07
EndDate
01/03/07
01/03/07
Description
Task4
Task5
Getting Started with Base
SELECT "TaskID", "StartDate", "EndDate", "Description" FROM "Tasks"
ORDER BY "StartDate" DESC LIMIT 2 OFFSET 3
This example can be also be read as - return 2 rows, skipping the first 3 records of the result set
after sorting by StartDate in descending order.
The returned result set would now be
TaskID
8
7
StartDate
02/01/07
01/04/07
EndDate
02/10/07
01/04/07
Description
Task7
Task6
Top
The modifier TOP is used to limit the number of records returned without an offset value. It must be
included directly after the word SELECT and maybe used with any select statement.
SELECT TOP 2 "TaskID", "StartDate", "EndDate", "Description" FROM
"Tasks" ORDER BY "StartDate" DESC
The returned result set
TaskID
StartDate
EndDate
Description
11
03/02/08
03/03/07
Task10
10
03/01/08
03/02/07
Task9
SELECT TOP 2 "TaskID", "StartDate", "EndDate", "Description" FROM
"Tasks"
The returned result set
TaskID
2
3
StartDate
01/01/07
01/01/07
EndDate
01/01/07
01/02/07
Description
Task1
Task2
Distinct
The modifier DISTINCT limits the returned to rows to only those for which every row contains
unique entries.
Getting Started with Base
67
Appendix 2 – OpenOffice Basic
Database
Apache OpenOffice has an integrated database interface (independent of any systems) called Star
Database Connectivity (SDBC). The objective of developing this interface was to provide access to
as many different data sources as possible.
To make this possible, data sources are accessed by drivers. The sources from which the drivers
take their data is irrelevant to a SDBC user. Some drivers access file-based databases and take
the data directly from them. Others use standard interfaces such as JDBC or ODBC. There are,
however, also special drivers which access the MAPI address book, LDAP directories or Apache
OpenOffice spreadsheets as data sources.
Since the drivers are based on UNO components, other drivers can be developed and therefore
open up new data sources. You will find details about this in the Apache OpenOffice Developer's
Guide.
Note – VBA : In terms of its concept, SDBC is comparable with the ADO and DAO libraries
available in VBA. It permits high level access to databases, regardless of the underlying database
backends.
SQL: a Query Language
The SQL language is provided as a query language for users of SDBC. To compare the differences
between different SQL dialects, the SDBC components from Apache OpenOffice have their own
SQL parser. This uses the query window to check the SQL commands typed and corrects simple
syntax errors, such as those associated with uppercase and lowercase characters.
If a driver permits access to a data source that does not support SQL, then it must independently
convert the transferred SQL commands to the native access needed.
Types of Database Access
The database interface from Apache OpenOffice is available in the Apache OpenOffice Writer and
Apache OpenOffice Calc applications, as well as in the database forms.
In Apache OpenOffice Writer, standard letters can be created with the assistance of SDBC data
sources and these can then be printed out. You can also move data from the database window into
text documents using the drag-and- drop function.
If you move a database table into a spreadsheet, Apache OpenOffice creates a table area which
can be updated at the click of the mouse if the original data has been modified. Conversely,
spreadsheet data can be moved to a database table and a database import performed.
Finally, Apache OpenOffice provides a mechanism for forms based on databases. To do this, you
first create a standard Apache OpenOffice Writer or Apache OpenOffice Calc form and then link the
fields to a database.
All the options specified here are based on the user interface from Apache OpenOffice. No
programming knowledge is needed to use the corresponding functions.
This section, however, provides little information about the functions specified, but instead
concentrates on the programming interface from SDBC, which allows for automated database
querying and therefore permits a much greater range of applications to be used.
Basic knowledge of the way in which databases function and the SQL query language is however
needed to fully understand the following sections.
68
Getting Started with Base
Data Sources
A database is incorporated into Apache OpenOffice by creating what is commonly referred to as a
data source. The user interface provides a corresponding option for creating data sources in the
Extras menu. You can also create data sources and work with them using Apache OpenOffice
Basic.
A database context object that is created using the createUnoService function serves as the
starting point for accessing a data source. This based on the com.sun.star.sdb.DatabaseContext
service and is the root object for all database operations.
The following example shows how a database context can be created and then used to determine
the names of all data sources available. It displays the names in a message box.
Dim DatabaseContext As Object
Dim Names
Dim I As Integer
DatabaseContext = createUnoService("com.sun.star.sdb.DatabaseContext")
Names = DatabaseContext.getElementNames()
For I = 0 To UBound(Names())
MsgBox Names(I)
Next I
The individual data sources are based on the com.sun.star.sdb.DataSource service and can be
determined from the database context using the getByName method:
Dim DatabaseContext As Object
Dim DataSource As Object
DatabaseContext = createUnoService("com.sun.star.sdb.DatabaseContext")
DataSource = DatabaseContext.getByName("Customers")
The example creates a DataSource object for a data source called Customers.
Data sources provide a range of properties, which in turn provide general information about the
origin of the data and information about access methods. The properties are:
Name (String)
name of data source
URL (String)
URL of data source in the form of jdbc: subprotocol : subname or sdbc: subprotocol : subname
Settings (Array)
array containing PropertyValue-pairs with connection parameters (usually at least user name
and password)
User (String)
user name
Password (String)
user password (is not saved)
IsPasswordRequired (Boolean)
the password is needed and is interactively requested from user.
IsReadOnly (Boolean)
permits read-only access to the database
Appendix 2 – OpenOffice Basic
69
NumberFormatsSupplier (Object)
object containing the number formats available for the database (supports the
com.sun.star.util.XNumberFormatsSupplier interface)
TableFilter (Array)
list of table names to be displayed
TableTypeFilter (Array)
list of table types to be displayed. Values available are TABLE, VIEW and SYSTEM TABLE
SuppressVersionColumns (Boolean)
suppresses the display of columns that are used for version administration
Note – The data sources from Apache OpenOffice are not 1:1 comparable with the data sources in
ODBC.
Whereas an ODBC data source only covers information about the origin of the data, a data source
in Apache OpenOffice also includes a range of information about how the data is displayed within
the database windows of Apache OpenOffice.
Queries
Predefined queries can be assigned to a data source. Apache OpenOffice notes the SQL
commands of queries so that they are available at all times. Queries are used to simplify working
with databases because they can be opened with a simple mouse click and also provide users
without any knowledge of SQL with the option of issuing SQL commands.
An object which supports the com.sun.star.sdb.QueryDefinition service is concealed behind a
query. The queries are accessed by means of the QueryDefinitions method of the data source.
The following example lists the names of data source queries can be established in a message
box.
Dim DatabaseContext As Object
Dim DataSource As Object
Dim QueryDefinitions As Object
Dim QueryDefinition As Object
Dim I As Integer
DatabaseContext = createUnoService("com.sun.star.sdb.DatabaseContext")
DataSource = DatabaseContext.getByName("Customers")
QueryDefinitions = DataSource.getQueryDefinitions()
For I = 0 To QueryDefinitions.Count() - 1
QueryDefinition = QueryDefinitions(I)
MsgBox QueryDefinition.Name
Next I
In addition to the Name property used in the example, the com.sun.star.sdb.QueryDefinition
provides a whole range of other properties. These are:
Name (String)
query name
Command (String)
SQL command (typically a SELECT command)
The following example shows how a query object can be created in a program-controlled manner
and can be assigned to a data source.
Dim DatabaseContext As Object
Dim DataSource As Object
70
Getting Started with Base
Dim QueryDefinitions As Object
Dim QueryDefinition As Object
Dim I As Integer
DatabaseContext = createUnoService("com.sun.star.sdb.DatabaseContext")
DataSource = DatabaseContext.getByName("Customers")
QueryDefinitions = DataSource.getQueryDefinitions()
QueryDefinition = createUnoService("com.sun.star.sdb.QueryDefinition")
QueryDefinition.Command = "SELECT * FROM Customer"
QueryDefinitions.insertByName("NewQuery", QueryDefinition)
The query object is first created using the createUnoService call, then initialized, and then inserted
into the QueryDefinitions object by means of insertByName.
Database Access
A database connection is needed for access to a database. This is a transfer channel which
permits direct communication with the database. Unlike the data sources presented in the previous
section, the database connection must therefore be re-established every time the program is
restarted.
Apache OpenOffice provides various ways of establishing database connections. This example
shows how to connect to an existing data source.
Dim DatabaseContext As Object
Dim DataSource As Object
Dim Connection As Object
Dim InteractionHandler as Object
DatabaseContext = createUnoService("com.sun.star.sdb.DatabaseContext")
DataSource = DatabaseContext.getByName("Customers")
If Not DataSource.IsPasswordRequired Then
Connection = DataSource.GetConnection("","")
Else
InteractionHandler =
createUnoService("com.sun.star.sdb.InteractionHandler")
Connection = DataSource.ConnectWithCompletion(InteractionHandler)
End If
The code used in the example first checks whether the database is password protected. If not, it
creates the database connection required using the GetConnection call. The two empty strings in
the command line stand for the user name and password.
If the database is password protected, the example creates an InteractionHandler and opens the
database connection using the ConnectWithCompletion method. The InteractionHandler ensures
that Apache OpenOffice asks the user for the required login data.
Iteration of Tables
A table is usually accessed in Apache OpenOffice through the ResultSet object. A ResultSet is a
type of marker that indicates a current set of data within a volume of results obtained using the
SELECT command.
This example shows how a ResultSet can be used to query values from a database table.
Dim
Dim
Dim
Dim
Dim
Dim
DatabaseContext As Object
DataSource As Object
Connection As Object
InteractionHandler as Object
Database Access
Statement As Object
Appendix 2 – OpenOffice Basic
71
Dim ResultSet As Object
DatabaseContext = createUnoService("com.sun.star.sdb.DatabaseContext")
DataSource = DatabaseContext.getByName("Customers")
If Not DataSource.IsPasswordRequired Then
Connection = DataSource.GetConnection("","")
Else
InteractionHandler =
createUnoService("com.sun.star.sdb.InteractionHandler")
Connection = DataSource.ConnectWithCompletion(InteractionHandler)
End If
Statement = Connection.createStatement()
ResultSet = Statement.executeQuery("SELECT ""CustomerNumber"" FROM
""Customer""")
If Not IsNull(ResultSet) Then
While ResultSet.next
MsgBox ResultSet.getString(1)
Wend
End If
Once the database connection has been established, the code used in the example first uses the
Connection.createObject call to create a Statement object.
This Statement object then uses the executeQuery call to return the actual ResultSet.
The program now checks whether the ResultSet actually exists and traverses the data records
using a loop.
The values required (in the example, those from the CustomerNumber field) returns the ResultSet
using the getString method, whereby the parameter 1 determines that the call relates to the values
of the first column.
Note – VBA : The ResultSet object from SDBC is comparable with the Recordset object from DAO
and ADO, since this also provides iterative access to a database.
– StarOffice 5 : The database is actually accessed in Apache OpenOffice through a ResultSet
object. This reflects the content of a table or the result of a SQL-SELECT command. In the past,
the ResultSet object provided the resident methods in the Application object for navigation within
the data, for example, DataNextRecord.
Type-Specific Methods for Retrieving Values
As can be seen in the example from the previous section, Apache OpenOffice provides a getString
method for accessing table contents. The method provides the result in the form of a string. The
following get methods are available:
getByte()
supports the SQL data types for numbers, characters and strings
getShort()
supports the SQL data types for numbers, characters and strings
getInt()
supports the SQL data types for numbers, characters and strings
getLong()
supports the SQL data types for numbers, characters and strings
72
Getting Started with Base
getFloat()
supports the SQL data types for numbers, characters and strings
getDouble()
supports the SQL data types for numbers, characters and strings
getBoolean()
supports the SQL data types for numbers, characters and strings
getString()
supports all SQL data types
getBytes()
supports the SQL data types for binary values
getDate()
supports the SQL data types for numbers, strings, date and time stamp
getTime()
supports the SQL data types for numbers, strings, date and time stamp
getTimestamp()
supports the SQL data types for numbers, strings, date and time stamp
getCharacterStream()
supports the SQL data types for numbers, strings and binary values
getUnicodeStream()
supports the SQL data types for numbers, strings and binary values
getBinaryStream()
binary values
getObject()
supports all SQL data types
In all instances, the number of columns should be listed as a parameter whose values should be
queried.
The ResultSet Variants
Accessing databases is often a matter of critical speed. Apache OpenOffice provides several ways
of optimizing ResultSets and thereby controlling the speed of access. The more functions a
ResultSet provides, the more complex its implementation usually is and therefore the slower the
functions are.
A simple ResultSet, provides the minimum scope of functions available. It only allows iteration to
be applied forward, and for values to be interrogated. More extensive navigation options, such as
the possibility of modifying values, are therefore not included.
The Statement object used to create the ResultSet provides some properties which allow the
functions of the ResultSet to be influenced:
ResultSetConcurrency (const)
specifications as to whether the data can be modified (specifications in accordance with
com.sun.star.sdbc.ResultSetConcurrency).
Appendix 2 – OpenOffice Basic
73
ResultSetType (const)
specifications regarding type of ResultSets ( specifications in accordance with
com.sun.star.sdbc.ResultSetType).
The values defined in com.sun.star.sdbc.ResultSetConcurrency are:
UPDATABLE
ResultSet permits values to be modified
READ_ONLY
ResultSet does not permit modifications
The com.sun.star.sdbc.ResultSetConcurrency group of constants provides the following
specifications:
FORWARD_ONLY
ResultSet only permits forward navigation
SCROLL_INSENSITIVE
ResultSet permits any type of navigation, changes to the original data are, however, not noted
SCROLL_SENSITIVE
ResultSet permits any type of navigation, changes to the original data impact on the ResultSet
Note – VBA : A ResultSet containing the READ_ONLY and SCROLL_INSENSITIVE properties
corresponds to a record set of the Snapshot type in ADO and DAO.
When using the ResultSet's UPDATEABLE and SCROLL_SENSITIVE properties, the scope of
function of a ResultSet is comparable with a Dynaset type Recordset from ADO and DAO.
Methods for Navigation in ResultSets
If a ResultSet is a SCROLL_INSENSITIVE or SCROLL_SENSITIVE type, it supports a whole
range of methods for navigation in the stock of data. The central methods are:
next()
navigation to the next data record
previous()
navigation to the previous data record
first()
navigation to the first data record
last()
navigation to the last data record
beforeFirst()
navigation to before the first data record
afterLast()
navigation to after the last data record
All methods return a Boolean parameter which specifies whether the navigation was successful.
To determine the current cursor position, the following test methods are provided and all return a
Boolean value:
74
Getting Started with Base
isBeforeFirst()
ResultSet is before the first data record
isAfterLast()
ResultSet is after the last data record
isFirst()
ResultSet is the first data record
isLast()
ResultSet is the last data record
Modifying Data Records
If a ResultSet has been created with the ResultSetConcurrency = UPDATEABLE value, then its
content can be edited. This only applies for as long as the SQL command allows the data to be rewritten to the database (depends on principle). This is not, for example, possible with complex SQL
commands with linked columns or accumulated values.
The ResultSet object provides Update methods for modifying values, which are structured in the
same way as the get methods for retrieving values. The updateString method, for example, allows
a string to be written.
After modification, the values must be transferred into the database using the updateRow()method.
The call must take place before the next navigation command, otherwise the values will be lost.
If an error is made during the modifications, this can be undone using the
cancelRowUpdates()method. This call is only available provided that the data has not be re-written
into the database using updateRow().
Dialogs
You can add custom dialog windows and forms to Apache OpenOffice documents. These in turn
can be linked to Apache OpenOffice Basic macros to considerably extend the usage range of
Apache OpenOffice Basic. Dialogs can, for example, display database information or guide users
through a step-by-step process of creating a new document in the form of a Wizard.
Tip - You will find another description of dialogs in the Developer's Guide:
chapter Apache OpenOffice_Basic_IDE describes more fully the IDE
chapter Programming Dialogs and Dialog Controls shows more examples in Basic.
Working With Dialogs
Apache OpenOffice Basic dialogs consist of a dialog window that can contain text fields, list boxes,
radio buttons, and other control elements.
Creating Dialogs
You can create and structure dialogs using the Apache OpenOffice dialog editor:
Create and structure dialogs in the dialog editor
You can drag the control elements from the design pallet (right) into the dialog area, and define
their position and size.
The example shows a dialog that contains a label and a list box.
A dialog containing a label and a list box
Appendix 2 – OpenOffice Basic
75
You can open a dialog with the following code:
Dim Dlg As Object
DialogLibraries.LoadLibrary("Standard")
Dlg = CreateUnoDialog(DialogLibraries.Standard.DlgDef)
Dlg.Execute()
Dlg.dispose()
CreateUnoDialog creates an object called Dlg that references the associated dialog. Before you
can create the dialog, you must ensure that the library it uses (in this example, the Standard
library) is loaded. The LoadLibrary method performs this task.
Once the Dlg dialog object has been initialized, you can use the Execute method to display the
dialog. Dialogs such as this one are described as modal because they do not permit any other
program action until they are closed.
While this dialog is open, the program remains in the Execute call.
The dispose method at the end of the code releases the resources used by the dialog once the
program ends.
Closing Dialogs
Closing With OK or Cancel
If a dialog contains an OK or a Cancel button, the dialog is automatically closed when you click one
of these buttons. More information about working with these buttons is discussed in Dialog Control
Elements in Detail.
If you close a dialog by clicking the OK button, the Execute method returns a return value of 1,
otherwise a value of 0 is returned.
Dim Dlg As Object
DialogLibraries.LoadLibrary("Standard")
Dlg = CreateUnoDialog(DialogLibraries.Standard.MyDialog)
Select Case Dlg.Execute()
Case 1
MsgBox "Ok pressed"
Case 0
MsgBox "Cancel pressed"
End Select
Working With Dialogs
Closing With the Close Button in the Title Bar
You can close a dialog by clicking the close button on the title bar of the dialog window. The
Execute method of the dialog returns the value 0, which is the same as when you click Cancel.
Closing With an Explicit Program Call
You can also close an open dialog window with the endExecute method:
Dlg.endExecute()
The Execute method of the dialog returns the value 0, which is the same as when you click Cancel.
Access to Individual Control Elements
A dialog can contain any number of control elements. You can access these elements through the
getControl method that returns the control element by name.
76
Getting Started with Base
Dim Ctl As Object
Ctl = Dlg.getControl("MyButton")
Ctl.Label = "New Label"
This code determines the object for the MyButton control element and then initializes the Ctl object
variable with a reference to the element. Finally the code sets the Label property of the control
element to the New Label value.
Note – Unlike Apache OpenOffice Basic identifiers, the names of control elements are case
sensitive.
Working With the Model of Dialogs and Control Elements
The division between visible program elements (View) and the data or documents behind them
(Model) occurs at many places in Apache OpenOffice API. In addition to the methods and
properties of control elements, both dialog and control element objects have a subordinate Model
object. This object allows you to directly access the content of a dialog or control element.
In dialogs, the distinction between data and depiction is not always as clear as in other API areas
of Apache OpenOffice. Elements of the API are available through both the View and the Model.
The Model property provides program-controlled access to the model of dialog and control element
objects.
Dim cmdNext As Object
cmdNext = Dlg.getControl("cmdNext")
cmdNext.Model.Enabled = False
This example deactivates the cmdNext button in the Dlg dialog with the aid of the model object
from cmdNext.
Every control element has its own name that can be queried using the following model property:
Model.Name (String)
control element name
You can specify the title that appears in the title bar of a dialog with the following model property:
Model.Title (String)
dialog title (only applies to dialogs)
You can query the size and position of a control element using the following properties of the
model object:
Model.Height (long)
height of control element (in ma units)
Model.Width (long)
width of control element (in ma units)
Model.PositionX (long)
X-position of control element, measured from the left inner edge of the dialog (in ma units)
Model.PositionY (long)
Y-position of control element, measured from top inner edge of the dialog (in ma units)
To ensure platform independence for the appearance of dialogs, Apache OpenOffice uses the Map
AppFont (ma) internal unit to specify the position and size within dialogs. An ma unit is defined as
being one eighth of the average height of a character from the system font defined in the operating
system and one quarter of its width.
Appendix 2 – OpenOffice Basic
77
By using ma units, Apache OpenOffice ensures that a dialog looks the same on different systems
under different system settings.
If you want to change the size or position of control elements for runtime, determine the total size
of the dialog and adjust the values for the control elements to the corresponding part ratios.
Note – The Map AppFont (ma) replaces the Twips unit to achieve better platform independence.
Focus and Tabulator Sequence
You can navigate through the control elements in any dialog by pressing the Tab key. The following
properties are available in this context in the control elements model:
Model.Enabled (Boolean)
activates the control element
Model.Tabstop (Boolean)
allows the control element to be reached through the Tab key
Model.TabIndex (Long)
position of control element in the order of activation
Finally, the control element provides a getFocus method that ensures that the underlying control
element receives the focus:
getFocus
control element receives the focus (only for dialogs)
Multi-Page Dialogs
A dialog in Apache OpenOffice can have more than one tab page. The Step property of a dialog
defines the current tab page of the dialog whereas the Step property for a control element specifies
the tab page where the control element is to be displayed.
The Step-value of 0 is a special case. If you set this value to zero in a dialog, all of the control
elements are visible regardless of their Step value. Similarly, if you set this value to zero for a
control element, the element is displayed on all of the tab pages in a dialog.
Designing Page 1 of the dialog
In the preceding example, you can also assign the Step value of 0 to the dividing line as well as the
Cancel, Prev, Next, and Done buttons to display these elements on all pages. You can also assign
the elements to an individual tab page (for example page 1).
The following program code shows how the Step value in event handlers of the Next and Prev
buttons can be increased or reduced and changes the status of the buttons.
Sub cmdNext_Initiated
Dim cmdNext As Object
Dim cmdPrev As Object
cmdPrev = Dlg.getControl("cmdPrev")
cmdNext = Dlg.getControl("cmdNext")
cmdPrev.Model.Enabled = Not cmdPrev.Model.Enabled
cmdNext.Model.Enabled = False
Dlg.Model.Step = Dlg.Model.Step + 1
End Sub
Sub cmdPrev_Initiated
78
Getting Started with Base
Dim cmdNext As Object
Dim cmdPrev As Object
cmdPrev = Dlg.getControl("cmdPrev")
cmdNext = Dlg.getControl("cmdNext")
cmdPrev.Model.Enabled = False
cmdNext.Model.Enabled = True
Dlg.Model.Step = Dlg.Model.Step - 1
End Sub
A global Dlg variable that references an open dialog must be included to make this example
possible. The dialog then changes its appearance as follows:
Page 1
Page 2
Tip - You can find an other OOoBasic example here.
Dialogs supporting several languages
The strings of a Dialog can be localized, see the Developer's Guide chapter Dialog Localization.
Events
Apache OpenOffice dialogs and forms are based on an event-oriented programming model where
you can assign event handlers to the control elements. An event handler runs a predefined
procedure when a particular action occurs. You can also edit documents or open databases with
event handling as well as access other control elements.
Apache OpenOffice control elements recognize different types of events that can be triggered in
different situations.
These event types can be divided into four groups:
Mouse control: Events that correspond to mouse actions (for example, simple mouse
movements or a click on a particular screen location).
Keyboard control: Events that are triggered by keyboard strokes.
Focus modification: Events that Apache OpenOffice performs when control elements are
activated or deactivated.
Control element-specific events: Events that only occur in relation to certain control
elements.
When you work with events, make sure that you create the associated dialog in the Apache
OpenOffice development environment and that it contains the required control elements or
documents (if you apply the events to a form).
The Apache OpenOffice Basic development environment
The figure above shows the Apache OpenOffice Basic development environment with a dialog
window that contains two list boxes. You can move the data from one list to the other using the
buttons between the two list boxes.
If you want to display the layout on screen, then you should create the associated Apache
OpenOffice Basic procedures so that they can be called up by the event handlers. Even though
you can use these procedures in any module, it is best to limit their use to two modules.
To make your code easier to read, you should assign meaningful names to these procedures.
Jumping directly to a general program procedure from a macro can result in unclear code. Instead,
to simplify code maintenance and troubleshooting, you should create another procedure to serve
as an entry point for event handling - even if it only executes a single call to the target procedure.
Appendix 2 – OpenOffice Basic
79
The code in the following example moves an entry from the left to the right list box of a dialog.
Sub cmdSelect_Initiated
Dim lstEntries As Object
Dim lstSelection As Object
lstEntries = Dlg.getControl("lstEntries")
lstSelection = Dlg.getControl("lstSelection")
If lstEntries.SelectedItem > 0 Then
lstSelection.AddItem(lstEntries.SelectedItem, 0)
lstEntries.removeItems(lstEntries.SelectItemPos, 1)
Else
Beep
End If
End Sub
If this procedure was created in Apache OpenOffice Basic, you can assign it to an event required
using the property window of the dialog editor.
The Assign Action dialog
The Assign Action dialog lists all of the available Events. To assign a macro to an event:
1)
2)
3)
4)
Select the event
Click Macro...
Browse to and select the macro you want to assign
Click OK
Parameters
The occurrence of a particular event is not always enough for an appropriate response. Additional
information may be required. For example, to process a mouse click, you may need the screen
position where the mouse button was pressed.
In Apache OpenOffice Basic, you can use object parameters to provide more information about an
event to a procedure, for example:
Sub ProcessEvent(Event As Object)
End Sub
The structure and properties of the Event object depend on the type of event that triggers the
procedure call. Regardless of the type of event, all objects provide access to the relevant control
element and its model.
The control element can be reached using Event.Source and its model using Event.Source.Model.
You can use these properties to trigger an event within an event handler.
Mouse Events
Apache OpenOffice Basic recognizes the following mouse events:
Mouse moved
user moves mouse
Mouse moved while key pressed
user drags mouse while holding down a key
Mouse button pressed
user presses a mouse button
80
Getting Started with Base
Note – This event is also used for notifying requests for a popup context menu on the control. In
this case, the member PopupTrigger of the event passed to your macro function will be TRUE. In
particular, if such a request is made by pressing the right mouse button on the control, the event
will be fired twice: once for the popup menu request, and once for the real mouse event. If you are
interested in only the mouse click, your macro should ignore all calls where PopupTrigger is TRUE.
Mouse button released
user releases a mouse button
Mouse outside
user moves mouse outside of the current window
The structure of the associated event objects is defined in the com.sun.star.awt.MouseEvent
structure which provides the following information:
Events
Buttons (short)
button pressed (one or more constants in accordance with
com.sun.star.awt.MouseButton)
X (long)
X-coordinate of mouse, measured in pixels from the top left corner of the control element
Y (long)
Y-coordinate of mouse, measured in pixels from the top left corner of the control element
ClickCount (long)
number of clicks associated with the mouse event (if Apache OpenOffice can respond fast
enough, ClickCount is also 1 for a double-click because only an individual event is initiated)
The constants defined in com.sun.star.awt.MouseButton for the mouse buttons are:
LEFT
left mouse button
RIGHT
right mouse button
MIDDLE
middle mouse button
The following example outputs the mouse position as well as the mouse button that was pressed:
Sub MouseUp(Event As Object)
Dim Msg As String
Msg = "Keys: "
If Event.Buttons AND com.sun.star.awt.MouseButton.LEFT Then
Msg = Msg & "LEFT "
End If
If Event.Buttons AND com.sun.star.awt.MouseButton.RIGHT Then
Msg = Msg & "RIGHT "
End If
If Event.Buttons AND com.sun.star.awt.MouseButton.MIDDLE Then
Msg = Msg & "MIDDLE "
End If
Appendix 2 – OpenOffice Basic
81
Msg = Msg & Chr(13) & "Position: "
Msg = Msg & Event.X & "/" & Event.Y
MsgBox Msg
End Sub
Note – VBA : The VBA Click and Doubleclick events are not available in Apache OpenOffice Basic.
Instead use the Apache OpenOffice Basic MouseUp event for the click event and imitate the
Doubleclick event by changing the application logic.
Keyboard Events
The following keyboard events are available in Apache OpenOffice Basic:
Key pressed
user presses a key.
Key released
user releases a key
Both events relate to logical key actions and not to physical actions. If the user presses several
keys to output a single character (for example, to add an accent to a character), then Apache
OpenOffice Basic only creates one event.
A single key action on a modification key, such as the Shift key or the Alt key does not create an
independent event.
Information about a pressed key is provided by the event object that Apache OpenOffice Basic
supplies to the procedure for event handling. It contains the following properties:
KeyCode (short)
code of the pressed key (default values in accordance with com.sun.star.awt.Key)
KeyChar (String)
character that is entered (taking the modification keys into consideration)
The following example uses the KeyCode property to establish if the Enter key, the Tab key, or one
of the other control keys has been pressed. If one of these keys has been pressed, the name of
the key is returned, otherwise the character that was typed is returned:
Sub KeyPressed(Event As Object)
Dim Msg As String
Select Case Event.KeyCode
Case com.sun.star.awt.Key.RETURN
Msg = "Return pressed"
Case com.sun.star.awt.Key.TAB
Msg = "Tab pressed"
Case com.sun.star.awt.Key.DELETE
Msg = "Delete pressed"
Case com.sun.star.awt.Key.ESCAPE
Msg = "Escape pressed"
Case com.sun.star.awt.Key.DOWN
Msg = "Down pressed"
Case com.sun.star.awt.Key.UP
Msg = "Up pressed"
Case com.sun.star.awt.Key.LEFT
Msg = "Left pressed"
Case com.sun.star.awt.Key.RIGHT
Msg = "Right pressed"
82
Getting Started with Base
Case Else
Msg = "Character " & Event.KeyChar & " entered"
End Select
MsgBox Msg
End Sub
Information about other keyboard constants can be found in the API Reference under the
com.sun.star.awt.Key group of constants.
Focus Events
Focus events indicate if a control element receives or loses focus. You can use these events to, for
example, determine if a user has finished processing a control element so that you can update
other elements of a dialog.
The following focus events are available:
When receiving focus
element receives focus
When losing focus
element loses focus
The Event objects for the focus events are structured as follows:
FocusFlags (short)
cause of focus change (default value in accordance with
com.sun.star.awt.FocusChangeReason)
NextFocus (Object)
object that receives focus (only for the When losing focus event)
Temporary (Boolean)
the focus is temporarily lost
Control Element-Specific Events
In addition to the preceding events, which are supported by all control elements, there are also
some control element-specific events that are only defined for certain control elements. The most
important of these events are:
When Item Changed
the value of a control element changes
Item Status Changed
the status of a control element changes
Text modified
the text of a control element changes
When initiating
an action that can be performed when the control element is triggered (for example, a button is
pressed)
When you work with events, note that some events, such as the When initiating event, can be
initiated each time you click the mouse on some control elements (for example, on radio buttons).
No action is performed to check if the status of the control element has actually changed. To avoid
Appendix 2 – OpenOffice Basic
83
such “blind events”, save the old control element value in a global variable, and then check to see
if the value has changed when an event is executing.
The When initiating event is also noteworthy for the following reasons:
This event is initiated by either a key-press or a mouse button. Thus, it provides a
consistent interface for users who navigate by mouse or by keyboard.
When the Repeat property of a command button is set to True, this event is the one which
is repeatedly sent, as long as the triggering action (key down or mouse-button down)
remains in effect.
The properties for the Item Status Changed event are:
Selected (long)
currently selected entry
Highlighted (long)
currently highlighted entry
ItemId (long)
ID of entry
Dialog Control Elements
Apache OpenOffice Basic recognizes a range of control elements which can be divided into the
following groups:
Entry fields
Text fields
Date fields
Time fields
Numerical fields
Currency fields
Fields adopting any format
Buttons
Standard buttons
Checkboxes
Radio Buttons
Selection
lists
List boxes
Combo-boxes
Tree Control
Other
Scrollbars (horizontal and vertical)
Fields of groups
Progress bars
Dividing lines (horizontal and vertical)
Graphics
File selection fields
84
Getting Started with Base
Buttons
A button performs an action when you click it.
The simplest scenario is for the button to trigger a When Initiating event when it is clicked by a
user. You can also link another action to the button to close a dialog using the PushButtonType
property. When you click a button that has this property set to the value of 0, the dialog remains
unaffected. If you click a button that has this property set to the value of 1, the dialog is closed, and
the Execute method of the dialog returns the value 1 (dialog sequence has been ended correctly).
If the PushButtonType has the value of 2, the dialog is closed and the Execute method of the
dialog returns the value 0 (dialog closed). In the Dialog Editor, the property values are shown
symbolically, as Default (0), Okay (1), and Cancel (2).
The following are some of the properties that are available through the button model:
Model.BackgroundColor (long)
color of background
Model.DefaultButton (Boolean)
The button is used as the default value and responds to the Enter key if it has no focus
Model.FontDescriptor (struct)
structure that specifies the details of the font to be used (in accordance with
com.sun.star.awt.FontDescriptor structure)
Model.Label (String)
label that is displayed on the button
Model.Printable (Boolean)
the control element can be printed
Model.TextColor (Long)
text color of the control element
Model.HelpText (String)
help text that is displayed when you move the mouse cursor over the control element
Model.HelpURL (String)
URL of the online help for the corresponding control element
PushButtonType (short)
action that is linked to the button (0: no action, 1: OK, 2: Cancel)
Option Buttons
These buttons are generally used in groups and allow you to select from one of several options.
When you select an option, all of the other options in the group are deactivated. This ensures that
at any one time, only one option button is set. An option button control element provides two
properties:
State (Boolean)
activates the button
Label (String)
label that is displayed on the button
You can also use the following properties from the model of the option buttons:
Appendix 2 – OpenOffice Basic
85
Model.FontDescriptor (struct)
structure with details of the font to be used (in accordance with
com.sun.star.awt.FontDescriptor)
Model.Label (String)
label that is displayed on the control element
Model.Printable (Boolean)
control element can be printed
Model.State (Short)
if this property is equal to 1, the option is activated, otherwise it is deactivated
Model.TextColor (Long)
text color of control element
Model.HelpText (String)
help text that is displayed when the mouse cursor rests over the control element
Model.HelpURL (String)
URL of online help for the corresponding control element
To combine several option buttons in a group, you must position them one after another in the
activation sequence without any gaps (Model.TabIndex property, described as Order in the dialog
editor). If the activation sequence is interrupted by another control element, then Apache
OpenOffice automatically starts with a new control element group that can be activated regardless
of the first group of control elements.
Note – VBA : Unlike VBA, you cannot insert option buttons in a group of control elements in
Apache OpenOffice Basic. The grouping of control elements in Apache OpenOffice Basic is only
used to ensure a visual division by drawing a frame around the control elements.
Checkboxes
Checkboxes are used to record a Yes or No value and depending on the mode, they can adopt two
or three states.
In addition to the Yes and No states, a check box can have an in-between state if the
corresponding Yes or No status has more than one meaning or is unclear.
Checkboxes provide the following properties:
State (Short)
state of the checkbox (0: no, 1: yes, 2: in-between state)
Label (String)
label for the control element
enableTriState (Boolean)
in addition to the activated and deactivated states, you can also use the in-between state
The model object of a checkbox provides the following properties:
Model.FontDescriptor (struct)
structure with details of the font used (in accordance with
com.sun.star.awt.FontDescriptor structure)
86
Getting Started with Base
Model.Label (String)
label for the control element
Model.Printable (Boolean)
the control element can be printed
Model.State (Short)
state of the checkbox (0: no, 1: yes, 2: in-between state)
Model.Tabstop (Boolean)
the control element can be reached with the Tab key
Model.TextColor (Long)
text color of control element
Model.HelpText (String)
help text that is displayed when you rest the mouse cursor over the control element
Model.HelpURL (String)
URL of online help for the corresponding control element
Text Fields
Text fields allow users to type numbers and text. The com.sun.star.awt.UnoControlEdit. service
forms the basis for text fields.
A text field can contain one or more lines and can be edited or blocked for user entries. Text fields
can also be used as special currency and numerical fields as well as screen fields for special
tasks. As these control elements are based on the UnoControlEdit Uno service, their programcontrolled handling is similar.
Text fields provide the following properties:
Text (String)
current text
SelectedText (String)
currently highlighted text
Selection (Struct)
read-only highlighting of details (structure in accordance with
com.sun.star.awt.Selection, with the Min and Max properties to specify the start and
end of the current highlighting)
MaxTextLen (short)
maximum number of characters that you can type in the field
Editable (Boolean)
True activates the option for entering text, False blocks the entry option (the property cannot be
called up directly but only through IsEditable)
IsEditable (Boolean)
the content of the control element can be changed, read-only
The following properties are provided through the associated model object:
Appendix 2 – OpenOffice Basic
87
Model.Align (short)
orientation of text (0: left-aligned, 1: centered, 2: right-aligned)
Model.BackgroundColor (long)
color of the background of the control element
Model.Border (short)
type of border (0: no border, 1: 3D border, 2: simple border)
Model.EchoChar (String)
echo character for password fields
Model.FontDescriptor (struct)
structure with details of font used (in accordance with
com.sun.star.awt.FontDescriptor structure)
Model.HardLineBreaks (Boolean)
automatic line breaks are permanently inserted in the control element text
Model.HScroll (Boolean)
the text has a horizontal scrollbar
Model.MaxTextLen (Short)
maximum length of text, where 0 corresponds to no length limit
Model.MultiLine (Boolean)
permits entry to spans several lines
Model.Printable (Boolean)
the control element can be printed
Model.ReadOnly (Boolean)
the content of the control element is read-only
Model.Tabstop (Boolean)
the control element can be reached with the Tab key
Model.Text (String)
text associate with the control element
Model.TextColor (Long)
text color of control element
Model.VScroll (Boolean)
the text has a vertical scrollbar
Model.HelpText (String)
help text that is displayed when the mouse cursor rests over the control element
Model.HelpURL (String)
URL of online help for the corresponding control element
List Boxes
List boxes (com.sun.star.awt.UnoControlListBox service) support the following
properties:
88
Getting Started with Base
ItemCount (Short)
number of elements, read-only
SelectedItem (String)
text of highlighted entry, read-only
SelectedItems (Array Of Strings)
data field with highlighted entries, read-only
SelectedItemPos (Short)
number of the entry highlighted at present, read-only
SelectedItemsPos (Array of Short)
data field with the number of highlighted entries (for lists which support multiple selection),
read-only
MultipleMode (Boolean)
True activates the option for multiple selection of entries, False blocks multiple selections (the
property cannot be called up directly but only through IsMultipleMode)
IsMultipleMode (Boolean)
permits multiple selection within lists, read-only
List boxes provide the following methods:
addItem (Item, Pos)
enters the string specified in the Item into the list at the Pos position
addItems (ItemArray, Pos)
enters the entries listed in the string's ItemArray data field into the list at the Pos position
removeItems (Pos, Count)
removes Count entries as of the Pos position
selectItem (Item, SelectMode)
activates or deactivates highlighting for the element specified in the string Item depending on
the SelectMode Boolean variable
makeVisible (Pos)
scrolls through the list field so that the entry specified with Pos is visible
The model object of the list boxes provides the following properties:
Model.BackgroundColor (long)
background color of control element
Model.Border (short)
type of border (0: no border, 1: 3D border, 2: simple border)
Model.FontDescriptor (struct)
structure with details of font used (in accordance with
com.sun.star.awt.FontDescriptor structure)
Model.LineCount (Short)
number of lines in control element
Appendix 2 – OpenOffice Basic
89
Model.MultiSelection (Boolean)
permits multiple selection of entries
Model.SelectedItems (Array of Strings)
list of highlighted entries
Model.StringItemList (Array of Strings)
list of all entries
Model.Printable (Boolean)
the control element can be printed
Model.ReadOnly (Boolean)
the content of the control element is read-only
Model.Tabstop (Boolean)
the control element can be reached with the Tab key
Model.TextColor (Long)
text color of control element
Model.HelpText (String)
automatically displayed help text which is displayed if the mouse cursor is above the control
element
Model.HelpURL (String)
URL of online help for the corresponding control element
Note – VBA : The VBA option for issuing list entries with a numerical additional value (ItemData)
does not exist in Apache OpenOffice Basic. If you want to administer a numerical value (for
example a database ID) in addition to the natural language text, you must create an auxiliary data
field that administers in parallel to the list box.
Forms
In many respects, the structure of Apache OpenOffice forms corresponds to the dialogs. There are,
however, a few key differences:
Dialogs appear in the form of one single dialog window, which is displayed over the
document and does not permit any actions other than dialog processing until the dialog is
ended. Forms, on the other hand, are displayed directly in the document, just like drawing
elements.
A dialog editor is provided for creating dialogs, and this can be found in the Apache
OpenOffice Basic development environment. Forms are created using the Form Controls
and the Form Design Toolbar directly within the document.
Whereas the dialog functions are available in all Apache OpenOffice documents, the full
scope of the form functions are only available in text and spreadsheets.
The control elements of a form can be linked with an external database table. This function
is not available in dialogs.
The control elements of dialogs and forms differ in several aspects.
Users who want to provide their forms with their own methods for event handling, should refer to
the Dialogs chapter. The mechanisms explained there are identical to those for forms.
90
Getting Started with Base
Working With Forms
Apache OpenOffice forms may contain text fields, list boxes, radio buttons, and a range of other
control elements, which are inserted directly in a text or spreadsheet. The Form Functions Toolbar
is used for editing forms.
A Apache OpenOffice form may adopt one of two modes: the draft mode and the display mode. In
draft mode, the position of control elements can be changed and their properties can be edited
using a properties window.
The Form Functions Toolbar is also used to switch between modes.
Determining Object Forms
Apache OpenOffice positions the control elements of a form at drawing object level. The actual
object form can be accessed through the Forms list at the drawing level. The objects are accessed
as follows in text documents:
Dim Doc As Object
Dim DrawPage As Object
Dim Form As Object
Doc = ThisComponent
DrawPage = Doc.DrawPage
Form = DrawPage.Forms.GetByIndex(0)
The GetByIndex method returns the form with the index number 0.
When working with spreadsheets, an intermediate stage is needed for the Sheets list because the
drawing levels are not located directly in the document but in the individual sheets:
Dim Doc As Object
Dim Sheet As Object
Dim DrawPage As Object
Dim Form As Object
Doc = ThisComponent
Sheet = Doc.Sheets.GetByIndex(0)
DrawPage = Sheet.DrawPage
Form = DrawPage.Forms.GetByIndex(0)
As is already suggested by the GetByIndex method name, a document may contain several forms.
This is useful, for example, if the contents of different databases are displayed within one
document, or if a 1:n database relationship is displayed within a form. The option of creating subforms is also provided for this purpose.
The Three Aspects of a Control Element Form
A control element of a form has three aspects:
The Model of the control element is the key object for the Apache OpenOffice Basicprogrammer when working with control element forms.
The counterpart to this is the View of the control element, which administers the display
information.
Since control element forms within the documents are administered like a special drawing
element, there is also a Shape object which reflects the drawing element-specific properties
of the control element (in particular its position and size).
Accessing the Model of Control Element Forms
The models of the control elements of a form are available through the GetByName method of the
Object form:
Dim Doc As Object
Appendix 2 – OpenOffice Basic
91
Dim Form As Object
Dim Ctl As Object
Doc = ThisComponent
Form = Doc.DrawPage.Forms.GetByIndex(0)
Ctl = Form.getByName("MyListBox")
The example determines the model of the MyListBox control element, which is located in the first
form of the text document currently open.
If you are not sure of the form of a control element, you can use the option for searching through all
forms for the control element required:
Dim Doc As Object
Dim Forms As Object
Dim Form As Object
Dim Ctl As Object
Dim I as Integer
Doc = ThisComponent
Forms = Doc.Drawpage.Forms
For I = 0 To Forms.Count - 1
Form = Forms.GetbyIndex(I)
If Form.HasByName("MyListBox") Then
Ctl = Form.GetbyName("MyListBox")
Exit Function
End If
Next I
The example uses the HasByName method to check all forms of a text document to determine
whether they contain a control element model called MyListBox. If a corresponding model is found,
then a reference to this is saved in the Ctl variable and the search is terminated.
Accessing the View of Control Element Forms
To access the view of a control element form, you need the associated model. The view of the
control element can then be determined with the assistance of the model and using the document
controller.
Dim Doc As Object
Dim DocCrl As Object
Dim Forms As Object
Dim Form As Object
Dim Ctl As Object
Dim CtlView As Object
Dim I as Integer
Doc = ThisComponent
DocCrl = Doc.getCurrentController()
Forms = Doc.Drawpage.Forms
For I = 0 To Forms.Count - 1
Form = Forms.GetbyIndex(I)
If Form.HasByName("MyListBox") Then
Ctl = Form.GetbyName("MyListBox")
CtlView = DocCrl.GetControl(Ctl)
Exit Function
End If
Next I
The code listed in the example is very similar to the code listed in the previous example for
determining a control element model. It uses not only the Doc document object but also the DocCrl
document controller object which makes reference to the current document window. With the help
92
Getting Started with Base
of this controller object and the model of the control element, it then uses the GetControl method to
determine the view (CtlView variable) of the control element form.
Accessing the Shape Object of Control Element Forms
The method for accessing the shape objects of a control element also uses the corresponding
drawing level of the document. To determine a special control element, all drawing elements of the
drawing level must be searched through.
Dim Doc As Object
Dim Shape as Object
Dim I as integer
Doc = ThisComponent
For i = 0 to Doc.DrawPage.Count - 1
Shape = Doc.DrawPage(i)
If HasUnoInterfaces(Shape, "com.sun.star.drawing.XControlShape") Then
If Shape.Control.Name = "MyListBox" Then
Exit Function
End If
End If
Next
The example checks all drawing elements to determine whether they support the
com.sun.star.drawing.XControlShape interface needed for control element forms. If this is
the case, the Control.Name property then checks whether the name of the control element is
MyListBox. If this is true, the function ends the search.
Determining the Size and Position of Control Elements
As already mentioned, the size and position of control elements can be determined using the
associated shape object. The control element shape, like all other shape objects, provides the Size
and Position properties for this purpose:
Size (struct)
size of control element (com.sun.star.awt.Size data structure)
Position (struct)
position of control element (com.sun.star.awt.Point data structure)
The following example shows how the position and size of a control element can be set using the
associated shape object:
Dim Shape As Object
Dim Point As New com.sun.star.awt.Point
Dim Size As New com.sun.star.awt.Size
' ... Initialize Shape object, as previously shown ...
Point.x = 1000
Point.y = 1000
Size.Width = 10000
Size.Height = 10000
Shape.Size = Size
Shape.Position = Point
The shape object of the control element must already be known if the code is to function. If this is
not the case, it must be determined using the preceding code.
Appendix 2 – OpenOffice Basic
93
Control Element Forms
The control elements available in forms are similar to those of dialogs. The selection ranges from
simple text fields through list and combo boxes to various buttons.
Below, you will find a list of the most important properties for control element forms. All properties
form part of the associated model objects.
In addition to the standard control elements, a table control element is also available for forms,
which enables the complete incorporation of database tables. This is described in the Database
Forms chapter.
Buttons
The model object of a form button provides the following properties:
BackgroundColor (long)
background color
DefaultButton (Boolean)
the button serves as a default value. In this case, it also responds to the entry button if it has no
focus
Enabled (Boolean)
the control element can be activated
Tabstop (Boolean)
the control element can be reached through the tabulator button
TabIndex (Long)
position of control element in activation sequence
FontName (String)
name of font type
FontHeight (Single)
height of character in points (pt)
Tag (String)
string containing additional information, which can be saved in the button for programcontrolled access
TargetURL (String)
target URL for buttons of the URL type
TargetFrame (String)
name of window (or frame) in which TargetURL is to be opened when activating the button (for
buttons of the URL type)
Label (String)
button label
TextColor (Long)
text color of control element
HelpText (String)
automatically displayed help text which is displayed if the mouse cursor is above the control
element
94
Getting Started with Base
HelpURL (String)
URL of online help for the corresponding control element
ButtonType (Enum)
action that is linked with the button (default value from
com.sun.star.form.FormButtonType)
State (Short)
in toggle button, 1 = pushed, 0 = normal
Through the ButtonType property, you have the opportunity to define an action that is automatically
performd when the button is pressed. The associated com.sun.star.form.FormButtonType
group of constants provides the following values:
PUSH
standard button
SUBMIT
end of form entry (particularly relevant for HTML forms)
RESET
resets all values within the form to their original values
URL
call of the URL defined in TargetURL (is opened within the window which was specified through
TargetFrame)
The OK and Cancel button types provided in dialogs are not supported in forms.
Option Buttons
The following properties of an option button are available through its model object:
Enabled (Boolean)
the control element can be activated
Tabstop (Boolean)
the control element can be reached through the tab key
TabIndex (Long)
position of control element in the activation sequence
FontName (String)
name of font type
FontHeight (Single)
height of character in points (pt)
Tag (String)
string containing additional information, which can be saved in the button for programcontrolled access
Label (String)
inscription of button
Printable (Boolean)
the control element can be printed
Appendix 2 – OpenOffice Basic
95
State (Short)
if 1, the option is activated, otherwise it is deactivated
RefValue (String)
string for saving additional information (for example, for administering data record IDs)
TextColor (Long)
text color of control element
HelpText (String)
automatically displayed help text, which is displayed if the mouse cursor is above the control
element
HelpURL (String)
URL of online help for the corresponding control element
The mechanism for grouping option buttons distinguishes between the control elements for dialogs
and forms.
Whereas control elements appearing one after another in dialogs are automatically combined to
form a group, grouping in forms is performed on the basis of names. To do this, all option buttons
of a group must contain the same name. Apache OpenOffice combines the grouped control
elements into an array so that the individual buttons of a Apache OpenOffice Basic program can be
reached in the same way.
The following example shows how the model of a control element group
can be determined. Dim Doc As Object
Dim Forms As Object
Dim Form As Object
Ctl As Object
Dim I as Integer
Doc = ThisComponent
Forms = Doc.Drawpage.Forms
For I = 0 To Forms.Count - 1
Form = Forms.GetbyIndex(I)
If Form.HasByName("MyOptions") Then
Ctl = Form. GetGroupbyName("MyOptions")
Exit Function
End If
Next I
The code corresponds to the previous example for determining a simple control element model. It
searches through all forms in the current text document in a loop and uses the HasByName
method to check whether the corresponding form contains an element with the MyOptions name it
is searching for. If this is the case, then the model array is accessed using the GetGroupByName
method (rather than the GetByName method to determine simple models).
Checkboxes
The model object of a checkbox form provides the following properties:
Enabled (Boolean)
the control element can be activated
Tabstop (Boolean)
the control element can be reached through the tab key
96
Getting Started with Base
TabIndex (Long)
position of control element in the activation sequence
FontName (String)
name of font type
FontHeight (Single)
height of character in points (pt)
Tag (String)
string containing additional information, which can be saved in the button for programcontrolled access
Label (String)
button label
Printable (Boolean)
the control element can be printed
State (Short)
if 1, the option is activated, otherwise it is deactivated
RefValue (String)
string for saving additional information (for example, for administrating data record IDs)
TextColor (Long)
text color of control element
HelpText (String)
automatically displayed help text, which is displayed if the mouse cursor is above the control
element
HelpURL (String)
URL of online help for the corresponding control element
Text Fields
The model objects of text field forms offer the following properties:
Align (short)
orientation of text (0: left-aligned, 1: centered, 2: right-aligned)
BackgroundColor (long)
background color of control element
Border (short)
type of border (0: no border, 1: 3D border, 2: simple border)
EchoChar (String)
echo character for password field
FontName (String)
name of font type
FontHeight (Single)
height of character in points (pt)
Appendix 2 – OpenOffice Basic
97
HardLineBreaks (Boolean)
the automatic line breaks are permanently inserted in the text of the control element
HScroll (Boolean)
the text has a horizontal scrollbar
MaxTextLen (Short)
maximum length of text; if 0 is specified, there are no limits
MultiLine (Boolean)
permits multi-line entries
Printable (Boolean)
the control element can be printed
ReadOnly (Boolean)
the content of the control element is read-only
Enabled (Boolean)
the control element can be activated
Tabstop (Boolean)
the control element can be reached through the tab key
TabIndex (Long)
position of the control element in the activation sequence
FontName (String)
name of font type
FontHeight (Single)
height of character in points (pt)
Text (String)
text of control element
TextColor (Long)
text color of control element
VScroll (Boolean)
the text has a vertical scrollbar
HelpText (String)
automatically displayed help text, which is displayed if the mouse cursor is above the control
element
HelpURL (String)
URL of online help for the corresponding control element
List Boxes
The model object of the list box forms provides the following properties:
BackgroundColor (long)
background color of control element
98
Getting Started with Base
Border (short)
type of border (0: no border, 1: 3D frame, 2: simple frame)
FontDescriptor (struct)
structure with details of font to be used (in accordance with
com.sun.star.awt.FontDescriptor structure)
LineCount (Short)
number of lines of control element
MultiSelection (Boolean)
permits multiple selection of entries
SelectedItems (Array of Strings)
list of highlighted entries
StringItemList (Array of Strings)
list of all entries
ValueItemList (Array of Variant)
list containing additional information for each entry (for example, for administrating data record
IDs)
Printable (Boolean)
the control element can be printed
ReadOnly (Boolean)
the content of the control element is read-only
Enabled (Boolean)
the control element can be activated
Tabstop (Boolean)
the control element can be reached through the tab key
TabIndex (Long)
position of control element in the activation sequence
FontName (String)
name of font type
FontHeight (Single)
height of character in points (pt)
Tag (String)
string containing additional information which can be saved in the button for program-controlled
access
TextColor (Long)
text color of control element
HelpText (String)
automatically displayed help text, which is displayed if the mouse cursor is above the control
element
Appendix 2 – OpenOffice Basic
99
HelpURL (String)
URL of online help for the corresponding control element
Note – VBA : Through their ValueItemList property, list box forms provide a counterpart to the VBA
property, ItemData, through which you can administer additional information for individual list
entries.
Furthermore, the following methods are provided though the view object of the list box:
addItem (Item, Pos)
inserts the string specified in the Item at the Pos position in the list
addItems (ItemArray, Pos)
inserts the entries listed in the string's ItemArray data field in the list at the Pos position
removeItems (Pos, Count)
removes Count entries as of the Pos position
selectItem (Item, SelectMode)
activates or deactivates the highlighting for the element specified in the string Item depending
on the SelectMode variable
makeVisible (Pos)
scrolls through the list field so that the entry specified by Pos is visible
Database Forms
Apache OpenOffice forms can be directly linked to a database. The forms created in this way
provide all the functions of a full database front end without requiring independent programming
work.
You can page through and search in the selected tables and queries, as well as change data
records and insert new data records. Apache OpenOffice automatically ensures that the relevant
data is retrieved from the database, and that any changes made are written back to the database.
A database form corresponds to a standard Apache OpenOffice form. In addition to the standard
properties, the following database-specific properties must also be set in the form:
DataSourceName (String)
name of data source (refer to Database Access; the data source must be globally created in
Apache OpenOffice)
Command (String)
name of table, query, or the SQL select command to which a link is to be made
CommandType (Const)
specifies whether the Command is a table, a query or a SQL command (value from
com.sun.star.sdb.CommandType enumeration)
The com.sun.star.sdb.CommandType enumeration covers the following values:
TABLE
Table
QUERY
Query
100
Getting Started with Base
COMMAND
SQL command
The database fields are assigned to the individual control elements through this property:
DataField (String)
name of linked database field
Tables
Another control element is provided for work with databases, the table control element. This
represents the content of a complete database table or query. In the simplest scenario, a table
control element is linked to a database using the autopilot form, which links all columns with the
relevant database fields in accordance with the user specifications.
Appendix 2 – OpenOffice Basic
101