Vous êtes sur la page 1sur 262

4D v11 SQL

Self-training
Windows®/Mac OS®

4D® v11 SQL


© 1985 - 2008 4D SAS / 4D, Inc. All Rights Reserved.
4D v11 SQL
Self-training
Copyright© 1985 - 2008 4D SAS / 4D, Inc.
All Rights Reserved.

The software and the manual are copyrighted and may not be reproduced in whole or in part except for the
personal licensee’s use and solely in accordance with the contractual terms. This includes copying the elec-
tronic media, archiving, or using the software in any manner other than that provided for in the Software
license Agreement.
4D, 4D Draw, 4D Write, 4D View, 4th Dimension®, 4D Server and the 4th Dimension and 4D logos are reg-
istered trademarks of 4D SAS.
Windows, Windows XP, Windows Vista and Microsoft are registered trademarks of Microsoft Corporation.
Apple, Macintosh, QuickTime, and Mac OS are trademarks or registered trademarks of Apple Computer Inc.
Mac2Win Software is a product of Altura Software, Inc.
ICU Copyright © 1995-2008 International Business Machines Corporation and others. All rights reserved.
This product includes software developed by the Apache Software Foundation (http://www.apache.org/).
4D includes cryptographic software written by Eric Young (eay@cryptsoft.com)
4D includes software written by Tim Hudson (tjh@cryptsoft.com).
Spellchecker © Copyright SYNAPSE Développement, Toulouse, France, 1994-2008.
ACROBAT © Copyright 1987-2008, Secret Commercial Adobe Systems Inc. All rights reserved. ACROBAT is a
registered trademark of Adobe Systems Inc.
All other referenced trade names are trademarks, registered trademarks, or copyrights of their respective
holders.
Contents

Welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
The Fundamentals . . . . . . . . . . . . . . . . . . . . . . . 11
Sample Presentation Overview . . . . . . . . . . . . . . . . . 13

Chapter 1 Taking your First Steps with 4D. . . . . . . . . 15


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 15
Let’s discover the interface . . . . . . . . . . . . . . . . . 15
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

Chapter 2 Forms and Buttons . . . . . . . . . . . . . . . 21


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 21
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Chapter 3 Startup Display . . . . . . . . . . . . . . . . . 29


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 29
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

Chapter 4 Menubar . . . . . . . . . . . . . . . . . . . . 35
Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 35
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

Chapter 5 Page 0 and Page 1 . . . . . . . . . . . . . . . 39


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 39
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

4D v11 - Self-training 3
Contents

Chapter 6 Navigation and Form Pages . . . . . . . . . . . 47


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 47
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

Chapter 7 Tables and Fields . . . . . . . . . . . . . . . . 51


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 51
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

Chapter 8 Entering and Modifying Records . . . . . . . . 57


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 57
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

Chapter 9 Relations . . . . . . . . . . . . . . . . . . . . . 61
Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 61
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

Chapter 10 Input and Deletion . . . . . . . . . . . . . . . 67


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 67
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

Chapter 11 Importing . . . . . . . . . . . . . . . . . . . . 73
Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 73
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

Chapter 12 Output forms . . . . . . . . . . . . . . . . . . 77


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 77
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

Chapter 13 Query and Order by . . . . . . . . . . . . . . . 85


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 85
Order By . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

4 4D v11 - Self-training
Contents

Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

Chapter 14 Quick Reports and Exports . . . . . . . . . . . 91


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 91
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

Chapter 15 Query and Order by Using Formulas, Applying a


Formula . . . . . . . . . . . . . . . . . . . . . . . . 101
Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 101
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

Chapter 16 Inheriting Forms . . . . . . . . . . . . . . . 109


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 109
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

Chapter 17 Printing Forms . . . . . . . . . . . . . . . . 113


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 113
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

Chapter 18 Working with Form Objects . . . . . . . . . 119


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 119
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

Chapter 19 Object Properties . . . . . . . . . . . . . . . 127


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 127
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

Chapter 20 Formulas and Calculations . . . . . . . . . . 133


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 133
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

4D v11 - Self-training 5
Contents

Chapter 21 Variables Overview . . . . . . . . . . . . . . 137


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . 137
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

Chapter 22 Trace Mode and Debugging . . . . . . . . . 141


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . 141
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

Chapter 23 Basic Programming (Without Pointers). . . . 147


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . 147
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

Chapter 24 Pointers . . . . . . . . . . . . . . . . . . . . 151


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . 151
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 154

Chapter 25 Events . . . . . . . . . . . . . . . . . . . . . 155


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . 155
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

Chapter 26 Arrays, Pop-ups, ListBox. . . . . . . . . . . . 161


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . 161
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

Chapter 27 4D Write . . . . . . . . . . . . . . . . . . . . 169


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . 169
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 174

Chapter 28 Windows and Navigation . . . . . . . . . . . 175


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . 175
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 181

6 4D v11 - Self-training
Contents

Chapter 29 4D Internet Commands . . . . . . . . . . . . 183


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 183
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 186

Chapter 30 Passwords and Groups . . . . . . . . . . . . 187


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 187
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

Chapter 31 Triggers . . . . . . . . . . . . . . . . . . . . 193


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 194
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 195

Chapter 32 Current Selection . . . . . . . . . . . . . . . 197


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 198
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

Chapter 33 Sets and Named Selections . . . . . . . . . . 207


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 207
Named selections . . . . . . . . . . . . . . . . . . . . . . 208
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 210

Chapter 34 Process . . . . . . . . . . . . . . . . . . . . 211


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 212
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 215

Chapter 35 SQL . . . . . . . . . . . . . . . . . . . . . . 217


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . . 217
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 221

4D v11 - Self-training 7
Contents

Chapter 36 BLOBS . . . . . . . . . . . . . . . . . . . . . 223


Getting it Done . . . . . . . . . . . . . . . . . . . . . . . . 224
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . 227

Chapter 37 Key . . . . . . . . . . . . . . . . . . . . . . . 229


Exercise: “Forms and Buttons”, page 26 . . . . . . . . . . . . 229
Exercise: “Startup Display”, page 34 . . . . . . . . . . . . . 229
Exercise: “Navigation and Form Pages”, page 49 . . . . . . . 230
Exercise: “Tables and Fields”, page 54 . . . . . . . . . . . . . 230
Exercise: “Entering and Modifying Records”, page 60 . . . . 231
Exercise: “Relations”, page 66 . . . . . . . . . . . . . . . . . 231
Exercise: “Input and Deletion”, page 71 . . . . . . . . . . . 231
Exercise: “Importing”, page 75 . . . . . . . . . . . . . . . . 231
Exercise: “Output forms”, page 83 . . . . . . . . . . . . . . 232
Exercise: “Query and Order by”, page 89 . . . . . . . . . . . 232
Exercise: “Quick Reports and Exports”, page 99 . . . . . . . 233
Exercise: “Query and Order by Using Formulas, Applying a
Formula”, page 106 . . . . . . . . . . . . . . . . . . . . . . 237
Exercise: “Inheriting Forms”, page 112 . . . . . . . . . . . . 237
Exercise: “Object Properties”, page 132 . . . . . . . . . . . . 238
Exercise: “Formulas and Calculations”, page 135 . . . . . . . 238
Exercise: “Variables Overview”, page 140 . . . . . . . . . . . 239
Exercise: “Basic Programming (Without Pointers)”, page 149 241
Exercise: “Pointers”, page 153 . . . . . . . . . . . . . . . . . 242
Exercise: “Events”, page 160 . . . . . . . . . . . . . . . . . . 244
Exercise: “Arrays, Pop-ups, ListBox”, page 167 . . . . . . . . 245
Exercise: “4D Write”, page 173 . . . . . . . . . . . . . . . . 246
Exercise: “Windows and Navigation”, page 181 . . . . . . . 247
Exercise: “4D Internet Commands”, page 186 . . . . . . . . 248
Exercise: “Passwords and Groups”, page 191 . . . . . . . . . 249
Exercise: “Triggers”, page 195 . . . . . . . . . . . . . . . . . 250
Exercise: “Current Selection”, page 205 . . . . . . . . . . . . 251
Exercise: “Sets and Named Selections”, page 210 . . . . . . . 253
Exercise: “Process”, page 214 . . . . . . . . . . . . . . . . . 253
Exercise: “SQL”, page 220 . . . . . . . . . . . . . . . . . . . 256
Exercise: “BLOBS”, page 227 . . . . . . . . . . . . . . . . . 258

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Going Further . . . . . . . . . . . . . . . . . . . . . . . . . 262

8 4D v11 - Self-training
PRESENTATION
Welcome

Hello! Welcome to your new 4D environment.

I’m Prof4D, your personal assistant; I’ll be your guide throughout our
time together during this guide.

What do you say we take a quick tour of some of the things you can do
with 4D? Of course, I won’t get in to everything, but by the time we
get to the end of this guide, you’ll know everything you need to know
to create working databases that are both ergonomic and efficient!

Each chapter contains the following sections:

1) Introduction table
This table that introduces the chapter contains:
- the goal(s) for the chapter
- the estimated amount of time needed to complete the
exercise
- the list of elements used in the exercise

2) Getting it Done

The steps and instructions needed to complete the lesson.

3) Exercises
Additional exercises that add to the lesson and make sure that
you’ve mastered the main concepts.
The keys for these exercises are found in the Key chapter at the
end of the guide.

4D v11 - Self-training 9
Welcome
PRESENTATION

4) Comments
General commentary related to the chapter. If you wish to
learn even more about a given topic, the “Going further”
section provides additional information or sources to study.

You can also navigate the guide using the chapter themes.

Theme

There are five different themes are your disposal:


■ Usage
■ Interface
■ Programming
■ Plug-ins
■ Security

I’ll be there to help you every step of the way... after all, I need to work
a bit, too! :-)

In the interest of efficiency, at the start of each chapter, you can either
use the database that you completed in the previous chapter or the
sample database that is provided. That way, we can work using
identical databases. The sample databases are located in the Selftraining
Database folder.

Your goal (mine too!) is to get right to the essential information and
understand 4D’s global architecture without entering in to too much
detail. If we were to do that, this would be an encyclopedia and not a
quickstart guide!

At the end of this guide, you’ll find the exercise keys as well as useful
information to complete your training.

10 4D v11 - Self-training
The Fundamentals

PRESENTATION
THE FUNDAMENTALS
Let’s starting discovering 4D right now!

To create your professional application, you’ll need the following tools


and concepts (the list is open):
■ Data model
■ Menus
■ Passwords
■ Pictures
■ Interface (forms)
■ Methods
■ Process
■ Pointers
■ Transactions
■ ...

These are illustrated in the following diagram:

Of course, you can progressively implement these elements; but


remember, they aren’t all necessary in every application.

4D v11 - Self-training 11
Welcome
PRESENTATION

On the other hand, you application must be able to offer the following
functionalities:
■ Add, Edit, Delete
■ Query, Order by
■ Print
■ Import, Export
■ Send e-mail
■ Access the Web (Web publishing)
■ Exchange data (XML, Web Services, etc.) and communicate (TCP,
FTP, etc.)
■ Interact with other databases (ODBC, Oracle, MySQL, etc.)
■ ...

To sum things up, you need three main elements:


■ Have an interface

■ Store data

■ Some programming

We will touch upon these three points through the different lessons.

12 4D v11 - Self-training
Sample Presentation Overview

PRESENTATION
SAMPLE PRESENTATION OVERVIEW
Throughout this guide, we will strive to create a database that responds
to specific needs (such as the kinds you will likely come across at some
point as a 4D developer).

The first step is to identify these needs.

❿ What is the objective of the application that we’re being asked to


develop?
■ It’s a database that will be used to handle maintenance of an asset
management park.
■ It must be able to handle intervention requests for the park.
■ These intervention requests must be published on the Web

❿ What interface is requested?


■ A toolbar that groups essential functions by theme
■ A menu bar that contains some tables and options
■ a Preferences management windows customizable for each user

The following steps, made up of different lessons, will help you find
the solution.

Remember: This guide was not designed to cover every aspect and
feature of 4D, nor is it an analysis guide (Merise, UML, etc.). We’re
trying to stay pragmatic and efficient.

4D v11 - Self-training 13
Welcome
PRESENTATION

Here’s one last piece of information from the client - this layout
designed by their graphic artists after several meetings. We have icons
that were created according to our thumbnails (we’ll see the detail a
little further).

14 4D v11 - Self-training
GETTING STARTED
1 Taking your First Steps
with 4D

• Understanding 4D
Objective
• Discovering the interface and architecture
Estimated time 10 minutes
4D Standard Edition
What we’ll use Navigating menus
Using a sample database

GETTING IT DONE
You just downloaded and installed your software and now you want to
get up and running as fast as possible.

Let’s discover the


interface
1 Launch the 4D application.

If you haven’t yet registered your product (or if you don’t have a
product number), you can click “I would like to evaluate 4D”. This

4D v11 - Self-training 15
GETTING STARTED

Taking your First Steps with 4D

allows you to enter your product number at a later time (you can find
out more about this in the 4D Installation Guide).

4D has two work environments:


■ The Design environment lets you create and test your development.
■ The Application environment is accessible to your users or clients.

The first four menus from the left on the menu bar (File, Edit, Mode,
Run) let you manage every aspect of development.

The two menus to the right (Records and Tools) let you quickly test
your application.
Two additional menus appear to the right of these menus depending
on where you’re working in 4D (form, method, tools, etc.).

You’ll frequently use the 4D toolbar when working with your project.
Like with the menus, the buttons to the left of the Find feature are for
development purposes while the buttons to the right are for usage
(working with data).

A detailed description of these buttons is provided in the 4D


documentation.

16 4D v11 - Self-training
GETTING STARTED
Getting it Done

Like I already mentioned, the sample that we’ll use throughout this
guide concerns setting up an application that will manage an asset
management park. Whew! We lucked out — we won’t have to worry
about handling the bills! :)

I chose this example because it integrates several concepts (planning,


stock, tracking, and follow-up) that can be used is pretty much any
type of professional database (managing inventory, real estate, CRM,
operation tracking, managing workshops, team management, quality
control, etc.) or personal (video library, wine cellar, day planner, etc.)
Since we want this guide to remain easy to follow and fun to use, I’ve
limited the number of features because the goal is for you to
understand the basics without getting in to the nitty gritty of advanced
development.

Before we learn how to do that, let’s look at what our project will look
like once our work is complete. You’ll love how easy it is to get started
- not to mention all the feature!
2 In the toolbar, click the Open menu and select
MyITManager_36_key.4dbase" in the "Selftraining Database" folder.
Once opened, the database is displayed and shows you the contents of
the Technicians table. Each and every table can contain billions of
records... are you ready to have a go?

Let’s take a look at the features that we’ll use in the database, starting
with the main navigation screen.

The button bar at the top allows you to:


■ Handle records for each table (add, find, sort, print, delete, etc.)

Each of these tables are displayed as a list. You simply need to double-
click a list row to display the detail screen in the same window (this is
the detailed content of a single record.)

When you double-click a list row, the DETAIL record appears along
with navigation buttons.

4D v11 - Self-training 17
GETTING STARTED

Taking your First Steps with 4D

To display the records of another table, click on the corresponding


button in the toolbar on the left side of the window.

The cursor tells you on which table you’re working.

The last two choices allow you to manage:


■ Preferences (language, etc.)

■ Settings (lists of pre-defined values)

You can click the title of list headers; the header also allows you to
perform a search on or sort column data.
You can re-open this database at any time to find a feature
(expected or requested) in the exercises.
TIP

18 4D v11 - Self-training
GETTING STARTED
Exercise

EXERCISE
Spend some time browsing within the database to discover the primary
features (help bubbles, entry aids, parameters, preferences, Web access,
etc.)

You’ll now create a new database:


1 In the File menu, select New -> Database.
2 Name your database (for example, “MyITManager”).

3 Once your database is saved, 4D displays the Explorer.

4D v11 - Self-training 19
GETTING STARTED

Taking your First Steps with 4D

On your hard disk,.the MyITManager.4dbase folder will contain the


following elements:

COMMENTS
This database mirrors what you will get at the end of this guide. Of
course, you can always add more features to your database (for
example, ergonomics, programming, etc.) to create a professional
application.

I recommend that you check out the other sample databases as well as
the website www.4d.com to discover the many features and solutions
imaginable that were put created by ingenious developers just like us!

...and for those who need specific features or commands that aren’t
available in 4D or in plug-ins, you can use the SDK Plugin (free!) that
allows you to create projects in C++ in the wink of an eye!

• Setting automatic backups


Going further
• Interface objects

20 4D v11 - Self-training
INTERFACE
2 Forms and Buttons

Objective Setup and test the first interface elements (buttons) on a form
Estimated time 10 minutes
What we’ll use Forms, Buttons, Object properties

GETTING IT DONE
To get you quickly up to speed, let’s check out the navigational layout.

Let’s go step-by-step; we have:


■ a “home” form with fully-working and decorative objects
■ several lines of code used to display the form on the screen
■ entry/modification screens for each record to process

Let’s start by creating the main navigation window of our application.


We’ll need to integrate the following features into our 4D_IT software:
■ Multiple site management for users and machines

■ Personal preference management

■ Material configuration management (by machine)

■ Network configuration management (by machine)

4D v11 - Self-training 21
Forms and Buttons
INTERFACE

■ Software configuration management by machine with version and


license tracking
■ Service management and tracking

■ Peripheral management (printers, scanners, cameras, video projectors,


etc.)

The interdependencies are illustrated in the following schema:

See, we’re going to stick with a simple structure that is amply sufficient
for getting to know 4D.

In the toolbar:
1 Click Explorer .
2 Click Forms.
3 Select “Project Forms” and click the button at the bottom of the
Explorer.
4 Enter “Navigation” in the Form Name box.

5 Click OK.

22 4D v11 - Self-training
Getting it Done

INTERFACE
An empty form appears:

The tools on the left allow adding objects to the form (buttons,
variables, fields, arrays, texts, plug-ins, etc.)

The tools at the top of the form let you work with objects (group,
align, move) and to manage display options within the form (zoom,
pages, views, etc.)

The triangle to the right of a tool indicates that several options are
available for the tool.

Let’s start by creating a simple navigation interface that will help us


better understand how it works:
■ include a button to display the Technicians list,
■ include a button to close the form,
■ include a title at the top of the page.
1 Select the Button object.

2 Draw a button on the form.


The Property List appears.
To make the Property List reappear once you’ve closed it,
double click the button or right-click and select Property
TIP

List.

4D v11 - Self-training 23
Forms and Buttons
INTERFACE

3 Rename the button “Finished” by changing the Title property in the


Objects theme.
4 Click Enter to validate your change.
5 Click on “No Action” in the Standard Action property towards the
bottom of the Property List and select “Accept”.
This selection allows you to close the window.
6 Draw a second button and name it “Technicians”.
We’ll soon see how to program this button to display the list of techni-
cians.
7 Place the buttons as follows:

To test your creation, click the green triangle in the upper left of the
form window. 4D displays the form exactly how the user will see it.

You’ll notice that the window has automatically set its size to that of
the form. Resizing is done automatically and will help you save time
during both development and maintenance (of course, this feature can
be disabled if desired).
8 Click Finished to go back to the Design environment.

Let’s check and see if the second button works:


1 Right-click Technicians.

24 4D v11 - Self-training
Getting it Done

INTERFACE
2 Select “Object Method”:

3 In the Object Method window, enter the following:


ALERT(“List of technicians coming soon...”)

4 Shut the method’s window.


Did you notice the “shield” that indicates that a method is associated
with the object?

5 Test your form again and then click Technicians.


The following message should appear:

4D v11 - Self-training 25
Forms and Buttons
INTERFACE

As you can see, getting started with creating forms is easy! By now, you
should be completely independent and ready to tackle some exercises!
:=)

In a future lesson, we’ll transform these buttons into picture buttons


that will help improve the flow of our application.

EXERCISE
Let’s create a second button designed to display the list of “Help
Requests”.

Then finish the form so that it looks like the following example:

See key on page 229.

26 4D v11 - Self-training
Comments

INTERFACE
COMMENTS
When you copy a button (copy-paste), you are also copying its set of
properties as well as the associated method. Note: Only the object
name is different because an object name is unique to each form.

I generally recommend that you polish the initial object and then copy
it so that you only have to change a few necessary parameters.

• Form object detail


Going further
• Managing views

4D v11 - Self-training 27
Forms and Buttons
INTERFACE

28 4D v11 - Self-training
PROGRAMMING
3 Startup Display

• Displaying a form once a database is opened.


Objective • Creating a project method called from the “On open”
database method.
Estimated time 5 minutes
What we’ll use Database method, basic programming, operators

GETTING IT DONE
Before we move forward, let’s take a look at the basic syntax rules and
primary operators used in 4D.

Manipulation Operator Example


Comparisons Equals = If(Value = 12)
Different than # If(vtext # "4D")
Greater than >
If(Value1 > Value2)
Less than <
Greater or equal
to >=
If(Value1 >= Value2)
Less than or <=
equal to
Conjunctions (for
AND & If(($Euros=Rich) & ($Esthet=Beautiful))
queries, tests, etc.)

4D v11 - Self-training 29
PROGRAMMING

Startup Display

|
This character is
accessible using:
OR • Shift-\ on If((it_rains) | (it_snows))
Windows
• Alt-Shift-L on
Mac OS
# used only during
EXCEPT
searches
Add a field or variable
Assign := vName:="Napoléon"
value
Addition + vTotal:=vSubtotal+vTax
Subtraction - vRevenues:=vSalaries-vWitholdings-vTax
Operators for Multiplication * vTotal:=vNumHours*vHourlyRate
numbers Division / vLength:=vSurface/vWidth
Exponential ^ vKiloByte:=2^10
Parentheses () vTotal:=(5+3*(2-7)-((4*5)/(2+4)))
Concatenation + vName:="Mickey"+" "+"Mouse"
Multiplication * vTest:="x"*4 (we get "xxxx")
Operators for strings
String index [[ ]] (Windows) and vName[[1]]:=Uppercase(vName [[1]])
≤ ≥ (Mac OS)
VNumDays:=!06/05/2007! -
Operators for dates Addition + or -
!22/04/2007!

To get additional information on operators for pictures, strings, etc.


you can refer to the 4D documentation (Operators theme).

These databases are now ready to go!

Our application should be able to display the navigation screen as


soon as the user starts the program. To do that, we need to make the
form display automatically each time the database is opened.

Let’s create a method using the Explorer. This method is a Project


Method.
1 Launch the Explorer.
2 Select Methods (it’s the fourth icon down).

3 Click the button at the bottom of the Explorer.

30 4D v11 - Self-training
PROGRAMMING
Getting it Done

4 Name the method Initialization and then click OK.

5 Copy the following code:

The first row creates a container the size of the Navigation form, taking
in to consideration the properties we defined.

The second row displays the Navigation form in the container.

The third line is executed when you shut the window by clicking
Finished. It shuts the container.

4D v11 - Self-training 31
PROGRAMMING

Startup Display

To make sure that everything works properly in the method, click


Execute at the upper left of the method window. Your form must
appear in a “customized size” window:

The autodisplay on startup is almost complete. Now we need to “call”


the method when 4D is launched:
1 Display the Explorer.
2 Expand the “Database Methods” list.

32 4D v11 - Self-training
PROGRAMMING
Getting it Done

3 Double-click the “On Startup” database method.

This method is automatically launched at startup. We’re going to call


the Initialization method so that we don’t have to re-enter the
previously entered code:
1 Enter the first letters of the method name to call (Init) then press the
Tab key.
4D recognizes that it is a method and displays it in blue, bold italics.

2 Close the “On Startup” database method.

To test it:
1 Select “Open Recent Databases” in the File menu.
2 Select the name of your database.
The database closes and then re-opens. You must see the form in a
multi-user window.

Click Finished; the Design environment re-appears and displays the


windows that were open when you last shut down.

Great job! This step is completed, we will now carry on and improve
the look and feel of our form... it certainly needs it! :=)

4D v11 - Self-training 33
PROGRAMMING

Startup Display

EXERCISE
Set up a system that allows you to display the message “See you later”
when you close a database.

Tip: This exercise requires the use of the “On Exit” database method.

See key on page 229.

COMMENTS
A project method can be called by any other method (object, form,
database, project, trigger, plug-in, menu rows, etc.). A method can call
itself, in which case it becomes a recursive method.

When working with database methods, I recommend only calling


project methods. This lets you remain able to execute or call the
method when you’re good and ready without having to quit and re-
start your database.

We’ll learn how to apply parameters from one method to another a


little later in this guide.

• Fully understanding database methods


Going further
• The different kinds of methods

34 4D v11 - Self-training
INTERFACE
4 Menubar

Objective Set up an interface using menus


Estimated time 5 minutes
What we’ll use Menu bars, basic programming

Even though the interface is really geared towards clicking buttons, the
menu bars are still an efficient tool that your users are used to using.

In 4D, you can create up to 32,000 menu bars. You can name any
menu bar so that its easily located.

A menu bar can be displayed either programmatically (using the SET


MENU BAR command) or using a form that is associated with the menu
bar. In that case, the menu bar replaces the previous one when the
form appears.

GETTING IT DONE
Now that the set works, we will create a menu bar and call this method
from a menu row.
1 Select Tool Box from the toolbar.

4D v11 - Self-training 35
Menubar
INTERFACE

2 Select Menus.

This window first displays the list of all menu bars; when you click one
of the menu bars, its set of menus appears. You can then display each
row for that menu. The right side if the screen displays information
concerning the selected elements.
3 Rename Bar #1 as “Navigation” (by double-clicking its name in the
list).

36 4D v11 - Self-training
Getting it Done

INTERFACE
4 Display the contextual button by right-clicking the Navigation bar.
Choose “Attach a menu to the menu bar Navigation” then “New
menu”.

5 Rename this menu as “Tools”.


6 Display the contextual menu and for the new menu and click Add an
item to menu “Tools”.
7 Rename this item as “Dashboard”.
8 Choose the INITIALIZATIONS method in the drop down list on the
right side of the screen. The name of the selected method appears to
the right of the line.

To associated this new menu with the Navigation bar, you can also do
the following:
1 Click the Navigation bar.
2 In the right-hand column containing the current menus for the bar,
display the contextual menu (right-click).
3 Select “Attach a menu to the Navigation bar”.
4 Click the Tools menu, it is automatically attached.

To test this new way of accessing items in your project, select Test
Application in the Run menu. You will see your menu appear and can
test the efficiency of the row you created.

4D v11 - Self-training 37
Menubar
INTERFACE

EXERCISE
In the next lessons, you can add a row of menus in the Tools menu for
each specific feature.

COMMENTS
You can enable/disable menu rows depending on the user’s actions.

Perhaps you noticed that the standard menus call a resource called
:xliff:name. This indicates that the menu title comes from the
parameters file named CommonEN.xlf located in the
/Contents/Resources/English.lproj folder.
This allows you to better understand the interaction that can exist
between a resource file (an XML file, in this case) and your database.
This is particularly relevant when creating multilingual applications.

Be careful! Don’t modify the aforementioned resource because it is


managed and used by 4D. Doing so may cause some things not to
work! I simply mentioned it as an example.

In the “Menus” theme, you will find a number of commands that


allow you to:
- modify the method associated to a menu row
Going further
- modify a row’s shortcut
- programmatically learn the menu (Chosen menu) and the row
selected by the user

38 4D v11 - Self-training
INTERFACE
5 Page 0 and Page 1

Objective Set up a form so that it displays certain objects on every page


Estimated time 20 minutes
What we’ll use Page 0 and 1, picture library

GETTING IT DONE
4D forms allow multiple pages per form (up to 32,767 to be exact!),
which allows us to spread information across a form either by theme or
function and be able to access a specific page according to our needs.
You can browse pages using tabs, buttons, etc.

Certain objects (texts, buttons, etc.) should remain visible irregardless


of the page displayed.

In that case, these objects must be added to page 0, which 4D always


displays “below” the current page (1, 2, etc.)

For example, all the buttons to the left and at the top in the final
version of the sample database are found on page 0.

To browse from page to page, or to add another page, you can use the
left and right buttons in the tools at the top of the form window or use

4D v11 - Self-training 39
Page 0 and Page 1
INTERFACE

the pop-up menu between the two arrows. This allows you to access
existing pages.

To move objects from one page to another, simply cut the object and
copy it on to the desired page.
1 Move the set of buttons on your form to page 0.
The page indicator becomes:

We will now replace all of these buttons with a more, let’s say “system”
look and feel. Don’t worry, these buttons are completely functional,
they’re just not aesthetically up to par for a rather modern-looking
interface.
2 Double-click Finish to display its properties.
Let’s take a moment to give the button a variable name that’s slightly
more exciting. For example, let’s say “B_End”.

3 Click Button in the “Type” property (first in the list) and select Picture
Button.

40 4D v11 - Self-training
Getting it Done

INTERFACE
The button changes to:

If you take a look at the other properties, you’ll see that just below the
name, the picture related properties (the source and reference number)
are available:

At this point, there aren’t any pictures in the Picture Library. We are
unable to indicate the number of picture name.

Let’s now take a look at adding a picture to the library:


1 Open the Tool Box.
2 Click Pictures.

3 At the bottom, click the options menu and select Open...

4 Select the picture “Fermer.png” in the “Pictures_PNG” folder in the


“Selftraining Database” folder.
You can also drag-and-drop pictures directly from the folder
to the Picture editor list. 4D will ask you to define the
TIP

properties of the dragged picture.

4D v11 - Self-training 41
Page 0 and Page 1
INTERFACE

Notice that the button is created using four superimposed pictures


representing the four states of a button (displayed, clicked, mouse-
over, disabled):

The properties window for the picture is displayed:

5 Set a name for the picture (its number and size are automatically set,
but can be modified at this point). You should also indicate that the
picture is composed of four pictures (1 column on 4 rows):

42 4D v11 - Self-training
Getting it Done

INTERFACE
6 Memorize the picture number and size (48x48); click OK.

Your first picture is imported. You can now shut the Tool Box and go
back to your form and indicate the source and the picture number that
the button should use.

Your button is now changed! Relax, we’re going to clean it up a bit.

7 Change the size and the properties of the button as follows:


■ 4 rows on 1 column:

■ Switch when Roll Over, Switch back when Released, and Use Last
Frame when Disabled:

■ Width and Height set to 48:

Our button has now completed its face-lift successfully!

8 Test your form ( ).


Notice that by placing the cursor over a button or by clicking the but-
ton, the picture changes.

Now you’re set to add a more aesthetically pleasing interface.

4D v11 - Self-training 43
Page 0 and Page 1
INTERFACE

To save time when your pictures are already in the Picture


Library, you can drag-and-drop the name of the picture in the
TIP

library on to your form. 4D automatically creates a picture


button at the right size. You simply need to set its behavior.

Generally speaking, all objects (methods, tables, fields, forms,

ADVICE
pictures, etc.) in your 4D database can be used in any new
database via transfer. You won’t need to recreate pictures,
buttons, and other elements for each new database.

EXERCISE
■ Repeat these procedures for each button on your form.

■ Add functional buttons (find, order by, etc.) like in the provided sam-
ple.

It gathers the different ways of accessing the left-hand tables and the
functional buttons (add, print, delete, etc.) at the top of the form.

44 4D v11 - Self-training
Comments

INTERFACE
Don’t add any programming to these latest buttons, we will do it when
they are used.

Note: All the buttons in the left hand colum (from technicians to
parameters) remain are 1 row x 1 column. The checkboxes to select are:

All buttons across the top (from Finish to Delete) are cut in groups of 4
rows x 1 column and use the following settings:

■ Create text for these buttons. They will be set later on to take the selec-
ted language into account.

COMMENTS
It can be tempting (and why not, it’s usually a lot faster) to paste a
picture in several forms rather than to include it in the Picture Library.
Keep in mind that any change to a picture in the library is instantly
made to the entire database and only absorbs the size of the picture a
single time.

Duplicating pictures can be difficult to maintain if we’re talking about


a picture used in 10, 20, or even 80 forms! Plus, if you do that, you’ll
also increase the size of your structure file X times the size of the
picture.

4D v11 - Self-training 45
Page 0 and Page 1
INTERFACE

For example, a picture file is 8kb and we’re going to use 10 pictures of
the same size. That brings us to 80kb, and if we use it in 50 forms,
we’re quickly at 4MB that we really don’t need to add to the structure.

Now that you understand how pages work, you can start to have a
think about basic programming. Be sure to take in to account the
page on which the user is working when adapting, for example,
Going further
menus, as we saw in the previous chapter.In the following chapters,
we’ll take this one step further and discuss the concept of inheriting
forms.

46 4D v11 - Self-training
INTERFACE
6 Navigation and Form
Pages

• Add form pages


Objective
• Set up a navigation system within a form
Estimated time 5 minutes
What we’ll use Form pages, browsing programmatically

GETTING IT DONE
We now have a database that is aesthetically correct!

In the sample database that you just opened, we added “procedural”


buttons at the top of the form in page 0 (Add, Select all, Query, Print,
etc.)

We now need to make it functional by creating pages 2 through 8,


then positioning information on each of these pages and making
navigation possible between these different pages.

To create pages:
1 Display the “Navigation” Project form.
2 Select “Add Page” in the Form menu.

4D v11 - Self-training 47
Navigation and Form Pages
INTERFACE

3 Confirm the add dialog message:

4 Repeat the operation so that your form has 7 pages (8 total if you’re
counting page 0).
You can also click on the right arrow in the navigation
panel .
TIP

Now we need to indicate for each button which form page to display.
1 Open the method for the Technicians button.
2 Delete its content.
3 Enter the following statement:
GOTO PAGE(1)

4 Repeat steps 1 through 3 with the “Help Requests” button, by


setting the page number to 2.
5 Add a different text or drawing (or a different location) on each page.
This allows you to visually control any changes made to the page.
6 Test your form and its new browse sequence.

Our navigation form now responses to users’ expectations and needs.


We must now give the customers some data, which is covered in the
next chapter.

48 4D v11 - Self-training
Exercise

INTERFACE
EXERCISE
■ Repeat this procedure for each of the buttons by modifying the page
number.
■ To verify that pages have changed, add a different text or drawing (or a
different location) on each page.

See key on page 230.

COMMENTS
Instead of managing the same line of code in each button, you can call
a method and pass the page number to display as a parameter. This is a
lot easier to maintain and also allows conditioning the page change
depending on the selected criteria.

You can also manage more pages than visible buttons and keep certain
information “hidden” so that it is only available under certain
conditions.

• Navigation with tabs


Going further • Manage tabs during compilation
• Browse using the button grid

4D v11 - Self-training 49
Navigation and Form Pages
INTERFACE

50 4D v11 - Self-training
DESIGN
7 Tables and Fields

Creating tables, fields, and setting properties to handle and


Objective
store data
Estimated time 10 minutes
What we’ll use Structure editor, tables, fields

GETTING IT DONE
To keep data from one session for another, or to share data among
several users, we can store it in:
■ a table
■ a text file
■ an XML file
■ resources
■ somewhere else (another database)

Let’s take a look at storing data in a table. To do that, we’ll need to:
1. Create the table
2. Create fields
3. Create at least one entry/visualization form

❿ To create a table:
1 Click the Structure icon .

4D v11 - Self-training 51
Tables and Fields
DESIGN

2 Click the button in the upper left-hand side of the window.


3 Select “Table”.

A new table is created in the structure.

4 Name the table “TECHNICIANS”.

❿ To add fields, there are several ways of going about it. Let’s take the
quickest way:
1 Double-click the first row of the table.
2 Enter the name of the first field (don’t change the type, we’ll come
back to this later.)
3 Press the Enter key, a new field is created.

52 4D v11 - Self-training
Getting it Done

DESIGN
4 Repeat as necessary for all the fields to create.

■ You can come back to each field and select the desire type to the right
of the field name.
■ You can also double-click fields to display the Inspector and change its
properties in detail.

The help tip is displayed when the user mouses over the field. The
comments allow specifying any information that you feel is useful
(ideas, field information, etc.)

4D v11 - Self-training 53
Tables and Fields
DESIGN

If you select several fields, the Inspector displays elements related to


the set of fields and specifies the number of concerned fields.

In the following chapter, we’ll create forms and start data input.

EXERCISE
Create the “Material” and “Help Request” tables in the same way using
the below model:

See key on page 230.

COMMENTS
To modify the type for multiple fields:
■ Select multiple contiguous (using the Shift key) or several non-con-
tiguous fields (using the Ctrl key in Windows or Cmd for MacOS)
fields
■ Changing the type of one of these fields => all selected fields are
modified

To move a field:
■ Hold the Alt key (the cursor changes in to a hand)
■ Drag the field to its new location

54 4D v11 - Self-training
Comments

DESIGN
There are several solutions available to you for adding tables and fields:
■ Right-click (within the structure to add a table, in the table to add a
field)
■ File -> New menu
■ The New button in the toolbar
■ The Add button in the structure window
■ Data import
■ Getting an existing database

You’l save a lot of time by creating your tables using existing


ADVICE

text files (txt, csv, dbf, etc.) I recommend that you consult
4D documentation for more information (importing data).

To learn how to strategize your database and use a professional


approach in your projects, you should participate in the following
Going further training sessions:
• How to conceptualize your database
• Managing project quality

4D v11 - Self-training 55
Tables and Fields
DESIGN

56 4D v11 - Self-training
USAGE
8 Entering and Modifying
Records

• Create input forms quickly using the Form editor


Objective
• Start entering data
Estimated time 10 minutes
What we’ll use Managing data mode, adding records

We’re now going to add input forms in the Navigation form created in
the previous chapters.

GETTING IT DONE
For this first input, we will use standard forms automatically created by
4D:
1 Choose “Display the current table” in the Records menu.
4D asks if you want to create forms.
2 Click “Yes for All”.

4D created two forms:


■ the INPUT form which presents the set of fields of a record.

4D v11 - Self-training 57
Entering and Modifying Records
USAGE

■ the OUTPUT form, which presents the list of records for the selec-
tion.
3 Choose the TECHNICIANS table in the list of tables.

4 In the Records menu, select New Record:

5 Input the data as shown in the following example:

To go from one field to another, you can use the Tab key.

58 4D v11 - Self-training
Getting it Done

USAGE
To add a value to the picture field, you have three options:
■ Copy a picture and paste it in the field.
■ Drag the picture from another application or another system win-
dow.
■ Use the import feature in the picture’s contextual menu.
6 To save the file, click the OK button.
4D asks, by default, if you want to create a new record.
7 To stop and return to the list, click the cancel button.

You can re-display a record’s details by double-clicking the record (be


careful, this only works if the record isn’t being entered in to the list.)

To input information in another table, you have the choice of:


■ Clicking the name of the desired table in the list of tables.

(Note: to re-display the above list of tables, select List of tables in


the Records menu)
■ Choosing one of the last used tables using the Records menu.

Did you notice during these inputs that a number of elements can be
improved (default values, input filters for dates, list of suggested
values, etc.)?

The input table by table that we just performed is practice, but it


doesn’t allow managing the presence of records in other tables, nor
does it really guarantee record integrity.

For that, 4D offers three solutions:


■ using relations
■ programming
■ a bit of both

We’ll discuss these three options coming up in the next chapter. We’ll
first start with setting up relations.

4D v11 - Self-training 59
Entering and Modifying Records
USAGE

EXERCISE
Finish any remaining input in the TECHNICIANS table from the list of
provided information.

Here’s a good exercise for testing your chops:


■ Create the SOFTWARE table using the following data:

■ Create forms automatically.

■ Enter the first three rows of data.

See key on page 231.

COMMENTS
You have four options at your disposal for creating a new record:
■ Clicking the Add button => the input is done in the list.

■ Choose New Record in List in the Records menu => input is also done
in the list.
■ Choose New record in the Records menu => input is done through the
input form (detailed content of a single record.)
■ Double-clicking an empty row to display a new record in the input
form.

For any use-related features (searches, order by, quick reports,


Going further
exports, etc.), I recommend that you visit the 4D documentation.

60 4D v11 - Self-training
STRUCTURE
9 Relations

• Understand the usefulness of relations in the sample


Objective database, learn how to trace and set relations
• Discover the power of 4D relations, non-programming
Estimated time 10 minutes
What we’ll use Relations, automatic integration

GETTING IT DONE
4D is a relational database. The relation between tables is created using
relations between the FOREIGN KEY and the PRIMARY KEY.

The power of relations in 4D is based on several automations that


considerably increase your capabilities without having to write a single
line of code. These automations can be disabled, but they’re also
customizable and can be used with programming.

Tracing a relation is simple: Click a field (Foreign Key = start) and drag
it to another field (Primary key = finish).

You need to keep two things in mind when tracing a relation:


■ the fields must both be the same type.

■ the relation of a field in table X (Foreign Key) must always be traced


towards a field in table 1 (Primary Key).

4D v11 - Self-training 61
Relations
STRUCTURE

Let’s talk for a little bit about billing - I know you’ll love that! :=)) You
can trace relations:
■ from the Invoice rows table to Invoices (X invoice rows for 1
invoice)
■ from the Invoice table to Customers (X invoices for 1 customer)
■ from the Invoice rows table to Products (X invoice rows for 1 prod-
uct)

According to the following example:

Perhaps you prefer the movies? So be it! What is the relationship


between Actors and Movies? It uses the Roles table as an intermediary
as follows:

You can associate as many roles as you want to a film, and even
represent the different roles a single actor might play in the same film
(for example, Eddy Murphy in the Nutty Professor).

Now that you’ve mastered relations, in what direction will you trace
the relation between “Technicians” and “Help requests”? Or between
“Help requests” and “Materials”?

62 4D v11 - Self-training
Getting it Done

STRUCTURE
These are basically the questions you should be asking yourself:
■ Can a single technical perform several interventions?
■ Can an intervention concern multiple technicians?

Concerning the relation between “Materials” and “Help requests”:


■ Can an intervention concern several pieces of material?
■ Can a piece of material be used for several interventions?

This subject could be debated for hours and hours using many
arguments and examples. This is where careful analysis and working in
the field with users really becomes important. In this exercise, we’ll
make the following arbitrary choices:
■ an intervention is handled by a single technician,
■ an intervention only concerns a single piece of material,
■ a piece of material will have an associated set of peripherals, soft-
ware, and networks.

We can then conclude that:


■ 1 Technician can perform X interventions.
■ 1 piece of Material can last X interventions.

As with any relational database, 4D uses “foreign” keys that must be


configured in table X.
1 If you haven’t already done so, create the “ID_Technician” in the HELP
REQUESTS table.
This field must be the same type as the Primary key (ID of the Techni-
cian table).

4D v11 - Self-training 63
Relations
STRUCTURE

To create a relation:
2 Trace the relation between the “ID” field in the HELP REQUESTS
table and the “ID” field in the TECHNICIANS table.

3 Double-click the relation to display the Inspector.


We want 4D to work in our place this time around and to create joints
(getting records from related tables) without using programming. In
other words, to do it automatically.

To do that, we must set the relation as follows:


4 Select “Automatic” instead of Manual in the “Many to One”
options.
5 Select “Automatic” instead of Manual in the “One to Many”
options.
6 Select also “Auto Wildcard Support” and “Prompt if related one
does not exist”.

64 4D v11 - Self-training
Getting it Done

STRUCTURE
This allows managing a portion of referential integrity; we’ll get back
to this point a little later on.

By making these choices, 4D creates the necessary requests to load the


related records in to memory. We can use them, for example, for
displaying.

The automatic Many to One relation allows, when inputting a help


request, to have the technician record with the code in memory. Once
the record is in memory, we can display information on the screen,
print, modify the record, etc.

The automatic One to Many relation allows, when viewing a


technician record, to have the list of interventions performed by the
technician in memory. This lets you display the list without any
programming.

We’ll come back and discuss the other Inspector parameters for
relations a little later.

4D v11 - Self-training 65
Relations
STRUCTURE

EXERCISE
Create relations between other tables and apply settings. Don’t hesitate
to add fields if any are missing.
See key on page 231. Note that in the key, we moved the fields so
that the structure is linear.

COMMENTS
To complete relation automation, you can use the integrity manager in
the relation inspector. It allows you to set how 4D should behave
when deleting a table record containing the primary key:
■ Leave related many intact: This implies management is done pro-
grammatically; 4D performs no integrity verification.
■ Delete related many: If you delete a Technician you’re deleting all
dependant records in table X (starting point for the relation). In our
case, this would be all help requests (interventions).
■ Cannot delete if related many: Even though records for table X are
related to the primary key, we’re not allowed to delete the record. In
other words, we can’t get rid of a technician who hasn’t performed
an intervention.

You can create tables, fields, and relations programmatically. Please


Going further visit the 4D documentation to find out more about these features!
You can also create tables and fields with SQL scripts.

66 4D v11 - Self-training
USAGE
10 Input and Deletion

• Inputting data
Objective
• Deleting data
Estimated time 10 minutes
What we’ll use Managing data mode, using relations, deletion

GETTING IT DONE
In previous chapters, we created records for Technicians as well as a
few records for Software.

We’re now going to input data while taking in to account relations


that we set up in the last chapter.
1 Go to the Entry page for the first record in the HELP REQUESTS table.
If 4D asks if you want to create the missing forms, click “Yes for All”.
2 Select the ID_Technician field and type the identifier for a non-existing
technician.
4D uses the automatic Many to one relation to see if this identifier
exists in the Technicians table.

4D v11 - Self-training 67
Input and Deletion
USAGE

4D will offer to create the record since it doesn’t exist:

This control is due to the checkbox “Prompt if related one does not
exist” that we selected previously. It lets you manage database integrity
during input and avoiding the presence of orphaned files.

In case the code doesn’t work, click Try Again and re-enter an existing
code.

If you want to create the technician with the typed code:


1 Click Create it.
2 Fill in the Technician form that is superimposed on the Services form.
3 Validate the record.
4D takes you back to the Help request input page and you can con-
tinue filling in the record.

We just create a multiple-table input with integrity check using a


relation and no programming whatsoever!

We can still use the relation to simply input. After all, we don’t know
the identifier of the records in each of the tables. In that case, simply
type the first letter(s) of the identifier using the @ character to display a
list of all records starting with that letter.

You can also start entry using the @ symbol; for example, you can type
@m. This will display any technician with the letter ‘m’ in their name.
When the results are returned on your screen, the text that is in

68 4D v11 - Self-training
Getting it Done

USAGE
parentheses is the “Wildcard choice” field selected in the relation
properties.

With relations, you can use the at sign (@) anywhere in the
foreign key to displays primary key records. For example:
TIP

• ab@ = displays any records starting with ab


• @ab = displays any records ending with ab
• @ab@ = displays any records containing ab
• @a@b@ = displays any records containing a and b ("a" first
and then "b")

Deleting records also depends on the settings for the relation. In this
case, the One to many relation is taken into account.

Now that we’ve related Help Requests to a Technician, we will try to


delete the Technician (voluntarily or by accident). What must happen?

If the one to many relation is manual 4D doesn’t perform any check and deletes it.
If the one to many relation is automatic 4D acts depending on the integrity check parameters.
If Leave Related Many Intact is
4D doesn’t perform any check and deletes it.
selected
If Delete Related Many is
4D deletes the technician and his services.
selected
If Cannot Delete if Related 4D refuses to delete the Technician record and doesn’t delete
Many is selected any services performed by the technician.

4D v11 - Self-training 69
Input and Deletion
USAGE

Note The deletions discussed above susceptible to record permissions


(read/write) and to any locks placed on the records by other process
users.

These elements remain valuable regardless of how records are deleted


(usage, programming).

Learning how to set parameters for links depends on how they are to
be used. Let’s take a look at the software -> material relation. Should
we delete the Software records when a piece of material is used (sale,
damaged, end of lease, etc.)?
In theory, software is purchased separately from a computer (with the
exception of OEM software), and it can be re-attributed to another
piece of equipment. For that reason, deleting software when deleting a
piece of material seems inappropriate.

❿ To delete a record:
1 Double-click the Technician to delete.
The technician is displayed in an input form.
2 Click the trash bin to delete the record.

3 Confirm deletion of the record.

EXERCISE
Set parameters for all relations using the following information:

Cascading records:
■ Create a piece of software and assign it a piece of material that
hasn’t been recorded yet => creation of a Material record
■ Create a help request for a non-existing piece of material (it’s not
yet in the database) => creation of a Material record. This is often
the case when a piece of material is installed for the first time.
■ Set a non-existing Technician for the Help request record => cre-
ation of a Technician record.
■ Validate each of these records (they are held in memory).

70 4D v11 - Self-training
Comments

USAGE
Did you notice how we were able to create records in four tables and
ensure the integrity of data without having to program? This is an
important lesson when working with 10 cascading tables.

To prepare for importing, which is discussed in the next chapter, let’s


delete all records in all tables... what happens?

If you select the Cannot delete if related many... checkbox for certain
relations, you must start by deleting records in Many table (relation
starting point) and work your way upward.

On the other hand, if all relations have the Delete related many option
selected, deleting a piece of material deletes the records in all related
tables (Help requests, Software, etc.)

See key on page 231.

COMMENTS
There’s a debate raging about whether to enable or disable automatic
relations. As you can imagine, there are several varying schools of
thoughts on the topic. The more choice you have, the more questions
we tend to ask! :=))

Generally speaking, here’s my advice:


■ Always trace relations.
■ Set as many relations as possible to automatic if you need to quickly
develop a functional database.
■ Don’t set any relation to automatic if you want to manage every-
thing and are afraid that when working with large volumes of data
(several hundred thousands or even millions of records) that auto-
mations will needlessly load unnecessary records.
■ Regardless of which solution you choose, it’s always possible to
enable or disable a relate one or relate many instance programati-
cally.

Planning and creating a structure depends on a number of factors. I


recommend taking the training course “Conceptualizing a
Going further
database”. It will teach you different approaches to conceiving a
database, as well as potential pitfalls and solutions you might face.

4D v11 - Self-training 71
Input and Deletion
USAGE

72 4D v11 - Self-training
USAGE
11 Importing

• Import data
Objective
• Automatically create tables
Estimated time 10 minutes
What we’ll use Data manipulation, importing with or without creating tables

GETTING IT DONE
To save time, and to prepare for getting previously inputted
information, we will learn about importing data and automatically
creating tables from a tabbed file.

❿ To import data:
1 In the File menu, select “Import” and then “From File...”
2 Select the Technicians.txt file in the “Selftraining Database” folder,
“Import_Files” subfolder.
The Setting dialog box appears.
3 Select the Technicians table in the list.
4 Match each field with the column to which it will be imported.
5 Click Import.
The data is added to any previously existing records.

4D v11 - Self-training 73
Importing
USAGE

The import feature also allows creating tables directly during import.
This function is critical when transferring data from other databases or,
as is often the case, from data stored in a spreadsheet.

❿ To create a table during import:


1 In the File menu, select “Import” and then “From File...”
2 Select the “Lists.txt” file.
The Settings dialog box appears:

3 Click (the list of tables disappears and allows inputting a


name.)
4 Enter the name of the table in the checkbox.

If the file that you are importing contains column headers (which I
recommend using), go on to the next step.
5 Click the second settings tab.

74 4D v11 - Self-training
Exercise

USAGE
6 Select the checkbox “Column Titles as Field Name”.

Row 1 automatically disappears and the fields are all renamed.

Afterwards, whether you selected this option or not, you can define
the type of fields:
7 Click each of the column headers and indicate the desired field type.
8 Click Import.

Once the import is complete, 4D asks you if you want to create forms
for the new table. Not a bad idea, if I say so myself! Go ahead and click
Yes.

EXERCISE
Import all of the files available in the Import_files subfolder in to each
table.

See key on page 231.

COMMENTS
■ When importing Boolean values (true-false in 4D), you can request
automatic conversion by going to the last tab in the Import dialog box
and selecting “yes;no”, “internal;external”, “man;woman”, etc. 4D
automatically converts the imported data (the first value as True and
the second as False).

4D v11 - Self-training 75
Importing
USAGE

■ You can also offer your users access to the Import or Export dialog
boxes by using the commands:
IMPORT DATA("")
EXPORT DATA("")

There are also other ways to import data in 4D:


■ Import by form
■ ODBC import
■ Import data from an old database
■ Oracle, MySQL, etc. connections (via the use of plug-ins)

Using the Import dialog box, you can also import your data using a
form. This form contains the fields that should receive the data,
they must be arranged in the same order as the import file
columns. You can then program the form method and object
Going further
methods to perform automatic checks, reformatting, automatic
population of calculated fields, etc. This is exactly like if the user
entered the data in the form. You can also created programmed
imports using the Open document and GET PACKET commands.

76 4D v11 - Self-training
INTERFACE
12 Output forms

Objective • Using the Form creation wizard


Estimated time 15 minutes
What we’ll use Output Form creation wizard + integration in the navigation page

GETTING IT DONE
Now that inputting no longer hold any secrets from you, we’ll use the
Form creation wizard to define forms that we’ll integrate with the
navigation interface.

These forms will be list presentations like you saw in the sample
database at the beginning of this guide.

4D v11 - Self-training 77
Output forms
INTERFACE

❿ To create list forms using the wizard:


1 Display the Explorer and select Forms.

2 Select New Form using Form Wizard from the options menu:

You display the Form creation Wizard.


3 Name the form: LIST.
4 Select the type.

5 Select the sample buttons:

They are already present in the navigation form.

The TECHNICIANS table is already selected.


6 In the “Available fields” menu, choose (fields are
displayed in the order they were created.)
7 Click the button for all fields in the list of “selected fields” and
appear in the form that appears on the right.

78 4D v11 - Self-training
Getting it Done

INTERFACE
8 Delete the field(s) that you do not wish to display by selecting them
and clicking .

In the Navigation form, we now have a width of 860 pixels for


displaying lists. We must verify the width of forms that we create:
1 Click Advanced.
2 Select Options in the main tab.
3 Select Target width and set the width to 860 points.

4 Click OK to create the form.

4D v11 - Self-training 79
Output forms
INTERFACE

4D displays the following screen where we will choose to set a tem-


plate (set parameters for an identical screen):

A template memorizes the set of display settings (except fields)


ADVICE

to re-apply them when creating forms in the future. By using


templates, you can maintain a number of settings when
working with important projects as well as to guarantee
coherence.

5 Click Edit to display the form in the Design environment.

80 4D v11 - Self-training
Getting it Done

INTERFACE
You may notice the presence of yellow markers:

These markers note the position of each area of the form. For example,
objects place between the header and body are displayed once for each
selection record while those placed between the top of the form and
the header are displayed once they are at the top of the form.

To move the markers, simply use drag-and-drop.


To move markers together, keep holding down the Shift key
then slide the highest marker. This will maintain the original
TIP

distance between markers. The position of markers can also


be set in the list of form properties.

We now need to integrate it into the Navigation form:


1 Close the form that we just created (LIST).
2 Open the Navigation form using the Explorer.
3 Select the page where we will integrate the list of technicians (page 1
in our example).
4 Re-display the Explorer.
5 Click the LIST form name and drag it to the window of the Navigation
form.

4D v11 - Self-training 81
Output forms
INTERFACE

The form that you dragged automatically integrates into the displays
form, similar to the example below:

6 Click the Navigation form.


7- Position the upper left corner of the dragged form below and to the
right of the existing buttons.

By default, the form can be resized freely. For display aesthetics and
usability, it’s better to force the width and height.
8 Display the form properties (right-click the background of the form
and not on an object.)
9 Set the form as shown below:

The automatic width allows displaying complete rows, which prevents


them from being truncated or cut during display.

82 4D v11 - Self-training
Exercise

INTERFACE
You now know how to display the fields of different tables. However,
for the moment, no record appears even though you imported data
into each table in the previous chapter.

That’s ok - it’s normal because we haven’t made any previous


selection.

To select records in the Technicians table, simply add a line of code in


the Technicians button of the Navigation form:

■ The first row, we saw, allows you to navigate between pages.


■ The second row creates a selection with the set of records from the
table (we’ll get to discussing selections in a little bit.)

EXERCISE
For each table, create the display form as a list form and then integrate
it into the Navigation form.

Think about modifying the button methods to create record selections.

Also thinkabout copying the blue pointer, indicating which page you
are on.

See key on page 232.

COMMENTS
If you want to modify the template you created, you can do so as
follows:
■ Create a new form using the template to modify
■ Click the Advanced button to make the desired changes.

Go up to where your new form is created - the last dialog box asks you
to either create a new template or to modify the template that you just
used. Choose this second option.

• Using styles in templates


Going further
• Using inherited forms

4D v11 - Self-training 83
Output forms
INTERFACE

84 4D v11 - Self-training
USAGE
13 Query and Order by

• Query and sort records using criteria from one or more tables
Objective
• Finish the use of automatic relations
Estimated time 10 minutes
“Manipulating data” environment, Query and Order by editor,
What we’ll use
programming

GETTING IT DONE
There are a series of buttons at the top of the Navigation form that we
added in the previous chapter. We’re now going to program them
taking into consideration the displayed list, in other words, the current
page with which we’re working.

❿ Let’s start with the Find button :


1 Display the Navigation form.
2 Select the Find button (on page 0).
3 Display the associated object method (Right-click -> Object method).

We must use the QUERY command that uses the name of the relevant
table as a parameter. That’s all well and good, but which table is
displayed at any given moment?

We know that we positioned the list of Technicians in page 1 of the


form; in page 2, we have the list of Services, etc.

4D v11 - Self-training 85
Query and Order by
USAGE

Simply ask 4D to tell us which page is displayed and to prepare the


query on that page.

To start off, we will write it as follows:

Note: The “Current form page” function returns the number of the
displayed page.
1 Save the method (File -> Save object method...)
2 Execute your form to see if the button works.
3 Put your mouse over the Technicians list.
4 Click Find.
The following Query screen appears. The fields match up with the
Technicians table... Great job! We’re on the right track!

❿ To perform a Query:
1 Click a field then a comparator, then type the value to query.

86 4D v11 - Self-training
Getting it Done

USAGE
The query argument gradually finishes:

2 Click Query to start the query.


4D performs the requested query and displays the records found in the
list (if any).

To use multiple query criteria, you must set parameters in the first line
of the argument and then click Add. You can carry on and modify the
next rows of the argument using any of the available conjunctions:

You can also perform a query and then perform a second query using
the results of the first selection:
1 Start the second query in the same way you performed the first query.
2 Start the query by clicking Query in Selection.

In a little bit, we’ll learn how to program a user’s most frequently


performed queries.

Order By The second goal of this chapter is to learn how to order by (or sort) a
selection. Like with the query button, we need to adapt the order by to
work with the displayed page. You can start exactly like we did with
the query button.
1 Display the Navigation form.

4D v11 - Self-training 87
Query and Order by
USAGE

2 Select the Sort button (on page 0).


3 Display the associated object method (Right-click -> Object method)
then enter the following:

4 Save the method (File -> Save object method...)


5 Execute your form to see if the button works.
6 Open the Technicians list and display several technicians by
performing a query.
7 Click Sort.
The following screen appears:

To set your criteria:


8 Drag the fields of the left column to the right column.
9 Indicate the order by direction for each column by clicking
(Increasing) or (Decreasing).
10 Click Order By.

88 4D v11 - Self-training
Exercise

USAGE
EXERCISE
Modify the code for the two buttons so that they work for all lists in
the Navigation form.

See key on page 232.

COMMENTS
As you undoubtedly have guessed by now, you can optimize the
procedure for creating these methods. In the course of the next few
chapters, we will learn how to use generic programming, passing
parameters between methods, and the use of pointers to make
reference to tables, fields, etc.

You can complete semi-automatic input in the Method editor by


changing the Macros.xml file that is located in the “Application
Going further
data” (Windows) or “Application Support” (Mac OS X) folder on
the user’s machine.

4D v11 - Self-training 89
Query and Order by
USAGE

90 4D v11 - Self-training
USAGE
14 Quick Reports and
Exports

Objective Use the Quick Report editor to extract data


Estimated time 30 minutes
Data manipulation environment, Report editor / settings +
What we’ll use
programming

The interest of using a database isn’t in your ability to enter data, but
rather your ability to get to data.

Getting data is, for now, done using pre-defined forms on screen (via
the programmer). In a number of cases, your users would want to
adapt data extraction to specific needs that aren’t available in a
functional specification or need to be very precise.

In addition to pre-defined forms created by the programmer or forms


that the user can modify (see 4D documentation), 4D provides a
customizable Quick Report editor. That’s what we’re going to check
out in this chapter!

GETTING IT DONE
The Quick Report editor allows presenting data from the current
selection, in other words, the result of a previously performed query1.

1. The final Boolean settings for the command allows you to bypass the pre-
vious query.

4D v11 - Self-training 91
Quick Reports and Exports
USAGE

1 Modify the Quick Report button method of the Navigation form:

The parameters passed to the command are:


■ the table name: [TECHNICIANS]
■ the name of access path of a pre-defined document. In the present
case Char(1) forces the display of the wizard.
■ display the hierarchical navigation between tables (using relations):
True
■ display the wizard module: True
■ allow a specific query: True
2 Click Quick Report in the Tools toolbar button.
The following screen is displayed:

2 3 4

It is comprised of four areas:


■ 1- The upper potion (menu bars, tool bars, column resizing rectan-
gle)

92 4D v11 - Self-training
Getting it Done

USAGE
■ 2- The bottom area that allows choosing the table, performing a
query, set the quick report type or launch the wizard (the magi-
cian’s hat on the right)
■ 3- The column of fields of the selected table
■ 4- The column of requested order by procedures.

❿ To quickly create a Quick Report:


1 Double-click the fields in area 3.
They appear like columns in area 1:

2 Choose “Preview” in the File menu or by clicking .


You can see the following window (in this case the Technicians table
must be selected):

If you’re working with Mac OS, the preview displays as a PDF in the
system tool Preview.

4D v11 - Self-training 93
Quick Reports and Exports
USAGE

3 To change the sort order, drag on or more fields in area 3 to area 4.


Note that a subtotal row appears in the area for each of the added order
by criteria.

In the row for the subtotal, you can add summary calculations by
right-clicking the intersection of the column and the subtotal row.

In this example, 4D performed a calculation on the number of


technicians for each help request type.

94 4D v11 - Self-training
Getting it Done

USAGE
To distinguish between the detail lines (each record) and summary
lines, you can apply styles, such as bold or italics, and apply spaces
between the summary and subsequent lines:

4 Set the space after to 25 points...

4D v11 - Self-training 95
Quick Reports and Exports
USAGE

... and the line alignment:

You’ll get the following result:

96 4D v11 - Self-training
Getting it Done

USAGE
You can also display only synthetic lines by “hiding” the body (the
detail of each record):

The hidden body is materialized by a gray grid over the entire row:

In this example, we no longer need 20 points spacing, so you can


remove it:

4D v11 - Self-training 97
Quick Reports and Exports
USAGE

The preview only shows synthetic lines:

Very nice, but it doesn’t say a whole lot! :=)) That’s because we didn’t
tell the Quick Reports editor that we want to know what these
synthetic values represent. To find out, simply click the # character in
one of the synthetic row Checkbox.

The results are a bit more colorful:

This behavior is valid regardless of what subtotal line you add these
markers. The result calculated or displayed for each subtotal is
evaluated by the Quick Reports editor depending on the grouping level
being processed.

The results of your Quick Report can be sent to multiple destinations:

To save it to disk as a text file, select Disk File. A system dialog box
appears allowing you to choose a name and location for your file.

98 4D v11 - Self-training
Exercise

USAGE
You can also perform an export using the Export editor.

Usually for a simple export, I recommend using the Export


editor. As soon as your data needs to be synthesized or

TIP
summarized as a list or cross-table or saved as HTML with
formatting, you will need to use the Quick Reports editor.

EXERCISE
Try to create the quick reports that follow:
■ List of help requests per technician
■ Number of help requests per technician
■ Number of help requests by request type and technician
■ Number of help requests by object and technician

See key on page 233.

COMMENTS
It is important to fully understand and work with all the possibilities
that the report editor affords you. You’ll become much more
productive and avoid pulling your hair out over things that 4D already
does so well. Also, you can totally program generation of quick reports
starting from reports that you’ve already set - just like we did in this
chapter - and then generating the corresponding source code (using
the Finalizing step of the wizard). In fact, the quick report generating is
a plug-in that is already integrated into 4D. It has its own
programming language.

• We quickly saw how to create forms with 4D and how to display


data. If we compare this behavior with a SELECT request in SQL:
- the form contains selected columns = the first part of SELECT
- query and order by of records equivalent to the WHERE and
ORDER BY options of SELECT.
Going further
• 4D integrates a SQL engine and can work natively with SQL
orders. In addition to the lesson on using SQL, please refer to the
4D documentation.
• Programming of the Quick Report editor (fully programmable
and customizable)

4D v11 - Self-training 99
Quick Reports and Exports
USAGE

100 4D v11 - Self-training


USAGE
15 Query and Order by Using
Formulas, Applying a
Formula

Objective Advanced query and global data changes


Estimated time 15 minutes
Data manipulation environment, Advanced functions, Formula
What we’ll use
editor

GETTING IT DONE
The set of 4D language commands is at our fingertips in several editors
(a limited version is available to end-users when they access standard
editors.)

This feature allows refining queries, order by, quick reports, but it also
applies formulas to the record selection of the current table. For
example, if you want to pass a field entirely in capital letters, lowercase
letters, to concatenate character strings or to separate them (if these
processes weren’t taken care of before importing them or if you forms
don’t specify conversions and automatic checks.)

4D v11 - Self-training 101


Query and Order by Using Formulas, Applying a Formula
USAGE

The use of forms allows performing the equivalent of a high-level find


and replace. The commands used are part of the 4D programming
language - the better you know them, the better you’ll be at working
with 4D in the right way.

Let’s use an example: in the file that you imported into the Users table,
I purposely forgot to use capital letters in the first letters of first and
last names. Some are capital, lower case, or even both! Also, telephone
numbers aren’t all formatted in the same manner; some have spaces,
some do not, some use dashes, some don’t. The number zero wasn’t
imported due to a spreadsheet that was improperly formatted during
export. We need to take care of this misrepresented data and badly
formatted content.

4D works with the idea of the current selection, which is a list of records
whose numbers are stored in memory and act as a starting point for
each process (except in a few rare cases.)

The order for executing processes can be broken down like this:
1 Select (create a selection of records that suit your needs).
2 Act (one or more actions).

The first step is to find the records, either using query (QUERY
command) or by selecting a set of records in the table (ALL RECORDS
command).

Let’s first pull out the last names:


1 Select HELP_REQUESTS from the list of tables.
2 Select “Show All” in the Records menu.

102 4D v11 - Self-training


Getting it Done

USAGE
3 Select “Apply Formula” in the same menu.

This screen allows writing the formula in the line at the bottom, using
the content of the three columns. Simply drag or double-click a field
name, operator, or a command to add it to the formula line.
4 Enter the following formula:
[HELP_REQUESTS]Object:=Uppercase([HELP_REQUESTS]Object)

5 Click OK to apply the formula to the selection.

4D v11 - Self-training 103


Query and Order by Using Formulas, Applying a Formula
USAGE

When you apply a formula, test it before you use it on several


records to make sure that your formula works properly and does

TIP
what you want it to do.

The query by formula works the same way, using the same formula
editor; the only difference is that allocation (:=) disappears because it is
incompatible with the query context.

Let’s find all help requests that occured in april.

The last step: sort by formula. This allows using the Formula editor in
the same way.

104 4D v11 - Self-training


Getting it Done

USAGE
The most informative example is generally the dictionary order by,
which, by definition, is sorted in alphabetical order and doesn’t
require a formula. However, what if it is the dictionary for the game
Scrabble™ ? First, you must sort names by length, by number of
characters (1 character words, then 2, then 3, etc.) then within these
groups you sort by alphabetical order.

In this case, you must use the order by formula for the first sort.

In our example, we can perform the order by for first names; for
example, if we want to see who has the shortest first name (ascending
sort) or the longest (descending sort).

In the Order by editor, click Add Formula at the bottom left and then
type:

4D v11 - Self-training 105


Query and Order by Using Formulas, Applying a Formula
USAGE

We can combine criteria using a formula using an additional criteria by


sorting first name alphabetically:

We then get the list of users sorted by length of first name (in
ascending order) and then alphabetically within each length.

EXERCISE
Exercise 1: Re-write the first name with the first letter in capitals and
the rest of the name in lower case.

See key on page 237.

106 4D v11 - Self-training


Comments

USAGE
COMMENTS
You can also apply a method to the selection. If you must apply several
formulas to a single selection, you can write the formula to apply
inside a method:

Then, enter the name of this method in the formula line to apply:

Formulas can also be used in the columns of the Quick Reports editor,
whose features were discussed in earlier chapters. This feature provides
you with a number of combinations (almost an unlimited number), to
create your quick reports or your exports.

To authorize or limit access to methods in the editors, refer to the


Going further
4D documentation (Preferences).

4D v11 - Self-training 107


Query and Order by Using Formulas, Applying a Formula
USAGE

108 4D v11 - Self-training


INTERFACE
16 Inheriting Forms

Configuring forms to have a coherent interface, stored in a


Objective
single and unique location for all forms
Estimated time 10 minutes
What we’ll use Form wizard, properties palette

GETTING IT DONE
So far, I’ve tried to familiarize you with simple procedures... let’s keep
it up! :=))

Let’s recall how page 0 is used in forms; it centralizes common


elements among all the pages in a single form.

Inheritance is about creating a form on which you place common


objects for several forms. This allows applying an update a single time
to a set of forms. Think of it like a “super page 0!”

You need to do the following in this order:


■ Create a form. We’ll call it the “parent form”, after all, you need one
to have an inheritance! :=)
■ Indicate the “family line” in the relevant forms. Those that inherit
are “children forms.”

4D v11 - Self-training 109


Inheriting Forms
INTERFACE

To create a parent form, we will create a specific table (INTERFACE)


that will contain all the forms to be used for print jobs or specific
displays (note: you cannot inherit a project form).
1 Add a table named Interface.
We will now create a new form associated with this table.
2 Display the Explorer and choose Forms.
3 Choose the Interface table and then click + .
4 Name it INHERITANCE and then click OK.
A blank form appears.
5 Trace a button in the upper left of the form.
6 Save your form (Ctrl+S).

The parent exists. We will now give it children:


7 Open the form “LIST” of the TECHNICIANS table.

110 4D v11 - Self-training


Getting it Done

INTERFACE
8 Display the Property list.

9 Select the Interface table in the property:

10 Select the INHERITANCE form in the property:

You’ll immediately see appear the content of the parent form in the
background.

If you modify the location of the button in the parent form then save
it (without closing it), you’ll see the change made on the open children
form(s). It’s also made to children forms that aren’t open, too, but you
just can’t see it. :=))

Import details:
■ Theoretically, there is no limit to inheritance; a parent can have a
parent, who has a parent, but be careful - you know how families
can be, especially among generations! The more you inherit, the
house (as well as your memory) starts to quickly fill up!
■ A parent form est a completely different form. It can contain several
pages and have a page 0. When using inheritance, only pages 0 and
1 of the parent are visible (inheritable).

4D v11 - Self-training 111


Inheriting Forms
INTERFACE

Now that you know all about inheritance, you can set one up!

Create at least one inherited form for your list forms, another
for your input forms and another for your information or

TIP
settings forms. Your imagination and user necessity will take
care of the rest...

EXERCISE
Transfer the set of buttons of list forms on a form and then make it
inheritable.

Do the same thing for input forms.

See key on page 237.

COMMENTS
In certain cases, you’ll need a parent form object to be invisible or
inaccessible depending on the context or relevant table.

If we’re talking about a button, you can disable it using the DISABLE
BUTTON command. If we’re talking about an object to hide, use the
SET VISIBLE command.

You can also use the MOVE OBJECT command.

We’ll see a case a little later in this guide where we’ll optimize
programming using generic methods and pointers.

112 4D v11 - Self-training


INTERFACE
17 Printing Forms

Create forms to be used for printing, List printing, and Detailed


Objective
printing
Estimated time 15 minutes
Creation wizard
What we’ll use
Simple changes (objects, blocks, properties)

GETTING IT DONE
In 4D, any form can be printed. There is no conceptual difference
between a report (printed) and a form (displayed on-screen).

In certain cases, you can have a single form for both entry and
printing. In other cases, especially when dealing with different sizes
and features, entry and printing are done using different forms.

It’s not uncommon to have several forms for a single table (you can
create up to 32,000!). You can set which form to use either
programmatically or using interface tools in the Design environment.

❿ To create a print form:


1 Use the wizard like in the form for on-screen display.

4D v11 - Self-training 113


Printing Forms
INTERFACE

2 In “Form type”, choose the type that best suits your needs:

or

3 Choose the fields to print.

4 Click Advanced...
5 Click Options to set print settings.
6 Click OK.
7 Click Edit (do not save the module for now).

114 4D v11 - Self-training


Getting it Done

INTERFACE
The form appears with the selected objects. At this point, the form can
be modified as necessary.

Note: Black lines divide the form in to quadrants, indicating the size of
the print area based on the defined print settings.

4D v11 - Self-training 115


Printing Forms
INTERFACE

We’ll explore how to improve the appearance of our forms, as well as


its features, in the next two chapters.

❿ To use the form for printing:


1 Display the HELP_REQUESTS table to which this form is attached.
2 Select several records.
3 Select Print from the File menu.
4 Select the print form.

5 Click OK; the print dialog boxes appear.

EXERCISE
Set up List print forms and Detailed forms in each of the tables.

Perform several print runs to make sure the feature works.

In a print form, you can also include a subform. For example, you will
create a form that allows printing the technician record as well as the
set of interventions.

116 4D v11 - Self-training


Comments

INTERFACE
COMMENTS
Be careful! Inheritance is strictly for display and not printing. This
option is disabled when working with printing.

Take advantage in this chapter to study all the possiblities that the
Form creation wizard provides, especially the part accessible using the
Advanced button.

To finish up this chapter, I recommend that you check out the


following subjects in the 4D documentation:
Printing with breaks
Going further Print by area (Print row)
Sizing objects during printing
Programmed moving of blocks
Automatic adjustment of object sizes

4D v11 - Self-training 117


Printing Forms
INTERFACE

118 4D v11 - Self-training


INTERFACE
18 Working with Form
Objects

Objective Save time when working with objects


Estimated time 10 minutes
Creation wizard
What we’ll use
Simple modifications (objects, tab stops, properties)

GETTING IT DONE
As a developer, you certainly know that ergonomics, aesthetics and
setting up the user interface are the most time-consuming aspects of
your development.

We’ve already used several ways to help you save time. Now I want to
give you the keys to optimizing your application, especially
concerning selecting, moving, and navigating your forms.

The keyboard-mouse combination is the best way to get that done.

4D v11 - Self-training 119


Working with Form Objects
INTERFACE

There’s more to this combination than “copy”, “paste”, and “select


all”; let’s take a look at others you’ll need to know if you want to work
efficiently:

Right-click on one of several objects

Select all objects of the


same type in the same
page of the form

Right-click a single object

Define object properties


that will be the standard
for all following objects of
the same type.
(Note: you can define a
template for each object
type)

120 4D v11 - Self-training


Getting it Done

INTERFACE
Alt+click an object or Right-click an object +

Get the method of an


object. This shortcut
opens the method if it
exists or creates and
opens it.

Select / deselect severalClick on the first then Shift+click the other


objects objects
Draw a selection rectangle. All objects that are
entirely or partially covered by the rectangle
are selected.
Select with the mouse
Note: If you push the Alt key before drawing
your rectangle, only objects completely
covered by the rectangle are selected.
Move an object one pixel Direction arrows

4D v11 - Self-training 121


Working with Form Objects
INTERFACE

Move an objects a grid Shift + direction arrows


square
Note: the size of the grid
is defined in Preferences.

Increase/decrease the size Ctrl + direction arrows


of an object by one pixel (Ctrl = Command key on Mac OS)
Increase/decrease the size
of an object by one grid Ctrl + Shift + direction arrows
square
Alt + click an object on page 0 when you are on
another page.
Directly access page 0
Remember: This shortcut is also used to display
the method of the clicked object.

122 4D v11 - Self-training


Getting it Done

INTERFACE
Access tools using T = Text tool
shortcuts. Touching the F(ield) = Field or variable
following keys at any time L = ListBox, scroll areas
provokes... P = Popup menus, combo box
B = Button
R = Radio button
C = Checkbox
I = Thermometers, dials,
S(quare) = Rectangle, line, …
D = Separator, tab
X = plug-in

For the horizontal bar:


Z = zoom
H = main (Hand)

Note: Place the tools to find these shortcuts

There’s also a separate tool: the order entry . It draws the order of
object of order focus on the screen when the user passes from one field
to another using the Tab key.

Note: Click another tool to deselect this tool.

You can change this order by clicking and dragging a field towards
another... but that can quickly grow tiresome. The easiest way to do
this is to:
■ position your objects,
■ draw a selection rectangle around a group of objects (or all objects,
if necessary).

4D redefines the input order starting with the highest object and then
from left to right and top to bottom.

4D v11 - Self-training 123


Working with Form Objects
INTERFACE

In the following example, the input order is standard:

If we re-organize the form, the initial order is kept, but not very
ergonomic:

Draw a selection rectangle that includes a piece of each object:

124 4D v11 - Self-training


Exercise

INTERFACE
A more logical input order is displayed:

If you prefer a column input, draw a rectangle on the two left fields,
then another on the two right fields.

EXERCISE
Set up shortcuts, especially:
■ moving and enlarging objects
■ selecting with Alt

COMMENTS
Shortcuts are an investment. Losing time to learn how to use them
helps you save a lot of time in the long run.

Saving time and seeking ways to optimize are also possible by drag-
and-drop between two databases, or from the object library to a form.
You’ll also save yourself from performing a number of procedures!

Also think about duplicating forms, tables, and fields.

• View the list of shortcuts (PDF file in the 4D documentation)


Going further • Display and modify the list of shortcuts (see the Contents\4D
Extensions\4DShortcuts.xml file)

4D v11 - Self-training 125


Working with Form Objects
INTERFACE

126 4D v11 - Self-training


INTERFACE
19 Object Properties

Objective Discover and set primary properties for form objects


Estimated time 10 minutes
What we’ll use Add an object and set certain properties

GETTING IT DONE
Each object has properties. Some are unique to that object, others are
part of all objects (object name, coordinates, height, width, resizing,
etc.)

When you select several objects, only shared properties appears. Any
change to one of these properties affects the set of selected objects.

If no object is displayed, form properties are displayed.

4D v11 - Self-training 127


Object Properties
INTERFACE

Properties are separated by theme and are visible all at once or by


theme:

Form properties:

128 4D v11 - Self-training


Getting it Done

INTERFACE
Text area properties:

To open or close the set of types, click a type while pressing


the Ctrl key (Windows) or Command (MacOS).
TIP

When the list of events is displayed, click a checkbox while pressing


the Ctrl key (Windows) or Command (MacOS) at the same time to
place all events in the same quick report.

Let’s try an exercise right now: when working with forms, you create or
duplicate several objects (fields or variables) and want to deselect the
set of events because none require executing the method.

Select your objects:

4D v11 - Self-training 129


Object Properties
INTERFACE

Display the Property List:

130 4D v11 - Self-training


Exercise

INTERFACE
Keep pressing the Ctrl/Command key and then click a single event:

This very simple procedure will prove to be very useful when


converting old databases from previous versions of 4D.

We’re now going to test several object properties (for detailed


information about each object and its properties, please refer to 4D
documentation).

EXERCISE
In the “Navigation” project form, make it so that all navigation
buttons (at the top) only have the “On click” event selected.
■ Select the Find button then also select “On load”.
■ Save the form then execute it... Question 1: what happens?

4D v11 - Self-training 131


Object Properties
INTERFACE

■ Organize the programming of this button as follows:

Question 2: What happens now to the display of the form?

See key on page 238.

COMMENTS
By default (for ease of maintenance and optimization purposes), I
recommend deselecting the set of object and form events, and then to
only select those you need and those associated with programming. In
fact, if you organized your programming with tests on the events you
use, the method is still loaded and executed each time a checked event
every time it occurs, even if you don’t want to use the event... very
tiring!

Forms also have properties and methods (form method). You may
be tempted to program in any one of these methods (object or
form). But which to choose?
In any case, what matters is that the code is executed when
necessary. So, any method will suffice to start. At first, we won’t
Going further optimize at all costs. You should still keep the order that methods
are executed when an event occurs:
1) Method objects are executed first (in the order of object depth =
levels of map = input order)
2) Once all object methods are executed, the form method takes
over.

132 4D v11 - Self-training


PROGRAMMING
20 Formulas and Calculations

Objective Automating processes and calculations


Estimated time 20 minutes
What we’ll use Variables, simple programming

Other than recording “raw” information, our database must provide us


with quantitative information (volumes, prices, totals) and on-the-fly
calculations depending on our needs.

The goal is to automate processes for more reliability. Certain data


must be kept and stored in a database field; this is the case, for
example, of an estimate’s total price. Others will only serve during the
work session (they are “lost” at the end of the session when you quit
4D). We will use “variable” objects for these cases. The most frequent
example concerns the number of records present in the list after a
search.

GETTING IT DONE
To start, we will put the number of records in the MATERIALS table
from a search inside a variable.

The question to consider when programming is “at what exact point


should the calculation start?” In our case, we consider that it should
happen when the user clicks one of the following buttons:
■ All
■ Find
■ Selection

4D v11 - Self-training 133


PROGRAMMING

Formulas and Calculations

In all other cases (order by, print, previous, etc.), the number of records
doesn’t vary, so there is no reason to recalculate.

We must add an object to view the number of records. So.... field or


variable?

We’ll use a variable because there’s really no interest in keeping the


number of records of a selection of a given moment in your database.
Where should we put the variable? In the navigation form, of course,
but on what page?

Since we want to have this result for each of the displayed tables, we’ll
place the variable on page 0.
1 Click the Field/Variable object:

2 Draw the object just below the row of buttons:

The properties list is displayed.


3 Modify the properties as follows:
■ Variable Name:

134 4D v11 - Self-training


PROGRAMMING
Exercise

■ Non-enterable:

The other properties don’t concern us for the time being. Then, we’ll
put in place a calculation method in the All button as follows:

EXERCISE
Finalize this code on the Query and All buttons, taking into account
the table (in other words, the page) on which you’re working.

See key on page 238.

COMMENTS
For learning purposes, we’ll keep the methods in objects for the
moment. Later, we’ll move them into generic methods to facilitate
maintenance and getting started with new functionalities.

Going further Object methods, form methods, trigger, and database methods

4D v11 - Self-training 135


PROGRAMMING

Formulas and Calculations

136 4D v11 - Self-training


PROGRAMMING
21 Variables Overview

Understanding the different types of variables and their


Objective
purpose (local, process, interprocess)
Estimated time 15 minutes
• Compilation instructions for defining variable type
What we’ll use • Code associated with using variables (variable life cycle: creation,
use, destruction)

GETTING IT DONE
Throughout the previous lessons, we regularly used variables
(vRecNum...). Let’s now take a look at what they’re made of, how they
work, and, depending on how they are defined, the limits of their
usage.

If we compare how 4D works to a company, we can sum it up like this:


■ There are several departments in a company that handle a specific
task, often independently of other departments.
■ Each department is designed to handle a certain number of tasks in
a specific order. A task can be interrupted because it depends on the
result of another process.
■ This new process will likely use information coming from the previ-
ous process, but also information unique to it.

4D v11 - Self-training 137


PROGRAMMING

Variables Overview

Now let’s translate that into a practical example:


■ The company has a production factory, a sales department and a HR
department.
■ The Payment department centralized the hours worked by the other
departments and handles pay, calculates the number of holiday,
etc.
■ Pay processing implies knowledge of overtime rates as well as differ-
ent withholding rates. This information is provided by the legal
department, which keeps this information up-to-date.

And now let’s see the parallel with 4D:


■ 4D can manage several processes (print, viewing, tool palettes,
imports, Web server, Web service response, etc.)
■ The executed method in each process can contain several phases.
■ It can call other methods within the same process (colleagues in the
same department), or request information from another process
(colleague in another department)

For each of the necessary communications, we have appropriate


variables:
■ To make information (in read-write) for all processes, we will use
interprocess variables. So that 4D considers them as is, these vari-
ables must be prefixed with the <> symbols for Windows and ◊ for
Macintosh (Ex: <>CurrentDate, <>HourlyRateArray, etc.)n
■ When a method is executed in a process, it might need information
unique to it. In that case, we’ll use a local variable, which is pre-
fixed in 4D with a $ symbol (for example: $Counter, $StampArea,
etc.)
■ All other variables (process variables, without prefix) can be used by
several methods in a single process.

The last comment concerning the need for information coming from
the legal department introduces the concept of interprocess
communication. In fact, it’s possible in 4D to order reading or writing
variables of one process to another (and even from a client machine to
the server.)

138 4D v11 - Self-training


PROGRAMMING
Getting it Done

To sum up, in a school:


■ the local variable is the student notebook (or its scratch sheet),
■ the process variable is the blackboard, usable and visible for all stu-
dents in a single class,
■ the interprocess variable is the billboard at the entrance of the
school that displays test results.

Interprocess communication for a teacher consists of coming to read


what is written (or write) on the classroom board (process variable) of
his or her colleague or on the billboard of the school (interprocess
variable).

Now that you understand the purpose of variables, we can learn how
they are used.

There are two kinds of variables in 4D: simple variables (a single


value) and arrays (several values).
You can define your simple variables with the same kinds as fields
(Text, Integer, Date, Time, BLOB, etc.) + Pointer.
The arrays accept the same kind if variables, with the exceptions of
BLOB and Time.

The life cycle of a variable is as follows:

Stage Simple variable Array Comments


In Unicode, Alpha
Birth =
C_LONGINT(NoDays) ARRAY TEXT(ArrayDates;0) mode Unicode, Alpha
Initialization
and Text are identical.
INSERT
ELEMENT(ArrayDates;1)
ArrayDates{1}:=!06/05/2007
Growth = Value !
NoDays:=25
assignment OR
APPEND TO
ARRAY(ArrayDates;!06/05/20
07!)
“Development” For($i;1;NoDays)
$StartDate:= Variables are in
public service =
ArrayDates{1}+18 read/write.
Usage End for
Death = Erased
The variable still exists,
from memory and
CLEAR VARIABLE(NoDays) CLEAR VARIABLE(ArrayDates) its content is re-
freed memory
initialized.
space

4D v11 - Self-training 139


PROGRAMMING

Variables Overview

EXERCISE
In a project method named “ARRAYS”, create 3 arrays of 26 elements:
■ The first contains letters of the alphabet.
■ The second contains dates starting from today.
■ The third contains values from 1 to 26.

See key on page 239.

To name a variable, you really need to respect a single


ADVICE

rule. Either you use a “dry” naming system, or you use


“conversational” variables that are easier to read. To
start, I recommend using names that are clear and
readable. You can always rename variables later using
the global replace feature in 4D.

COMMENTS
As with any language, variables are an integral part of 4D. They can be
used and be abused.

Be careful though, the very nature of certain variables means that they
cannot be viewed in a form (two-dimensional arrays, BLOBs, etc.)

Generic programming
Pointers
Going further
Two-dimensional arrays
BLOBs

140 4D v11 - Self-training


PROGRAMMING
22 Trace Mode and
Debugging

Objective Master displaying and using the debugger


Estimated time 10 minutes
What we’ll use Debugger, break points

GETTING IT DONE
Even though we’re perfect programmers who never make mistakes :=))
it’s still a good idea to “check up” on our code every now and then to
make sure everything is working as it should.

This lesson is all about displaying and using the debugger.

4D v11 - Self-training 141


PROGRAMMING

Trace Mode and Debugging

To display the debugger, you can use any one of the five following
ways:
■ Insert the TRACE command in the code (and NO TRACE to stop it):

This is the most frequent way that you’ll display the debugger (unless
you are tracing the server machine.).
■ Add a break point: this is a red dot that you add by clicking in the row
number column where you want 4D to go in to Trace mode:

■ When using your program (in the Application environment), use the
following keyboard shortcuts to start Trace mode:
■ Windows: Alt + Shift + right-click
■ Macintosh: Command + Alt + Ctrl + click

At this stage of our lessons, choose the Primary Process because we


haven’t yet learned how to create and use other processes.

142 4D v11 - Self-training


PROGRAMMING
Getting it Done

■ In the Design environment, click the Execution button of the method


by selected “Execute and Debug”.
■ The final way is to display the Runtime Explorer (Ctrl + Shift + F9) then
select the process to trace and click Trace:

Once you’ve used one about the above choices, 4D displays the
following window, at the execution of the next line of code.

4D v11 - Self-training 143


PROGRAMMING

Trace Mode and Debugging

These five options are voluntary options for going to Trace mode, but
4D certainly has its say in the matter! When it notices a syntax error in
your code, the following message is displayed, which also allows you
to start Trace mode:

In this example, the : symbol is missing in front of the =


We should have written $PageNum:=$2

The debugger appears as follows:

5
4

144 4D v11 - Self-training


PROGRAMMING
Getting it Done

I numbered the areas in the order that you typically use them:

The method area:


You know that this area represents the method
being executed.
You can perform a number of tasks in this area: 1
- put/remove break points
- drag the yellow cursor to the top or the bottom
(the cursor indicates the new line to execute)
- mouse-over a field, variable, or table to see the
corresponding information bubble
- click an object (wait 1 second with the mouse
button pressed) and drag it to the 3 area.
Browse buttons. If you place your mouse over a
button, a bubble appears explaining its purpose. 2

Continue execution by stopping Trace mode.

Stop the method.

Stop and switch to the Design environment to make


changes to the method.
Remain in Trace mode, but display the method in
the Design environment.
Save the settings (window size, expressions, area
widths, etc.)
Execute the line “step by step”: If the line is method
call, the method is executed without showing the
details of the execution.
Execute the line in “detailed step by step”: If the line
is a method call, we enter in the method and see
the execution details and then return to the calling
method.
Execute the line as “step by step new process”.

Execute the entire displayed method in Trace mode


in the method that called it.

4D v11 - Self-training 145


PROGRAMMING

Trace Mode and Debugging

EXERCISE
Place a break point in the “On Startup” database method and then re-
start. Watch what happens during this process.

Continual exercises during programming and tests.

COMMENTS
The two ways most frequently used to go to Trace mode are:
■ the break point
■ the keyboard shortcuts

Note: Only users defined as developers (belonging to a group with


access to the Design environment) can start Trace mode.

Using the Debugger, you can perform other tasks and functions,
such as:
• modifying field data and variables being executed
• executing code (careful, this can be risky!... but very helpful :=)
• displaying table and field numbers
Going further
• deleting all expressions
• choosing information that must appear in each area of the editor
• adding temporary break points, conditional break points, etc.
Most of the above features can be performed using the contextual
menu (right-click).

146 4D v11 - Self-training


PROGRAMMING
23 Basic Programming
(Without Pointers)

Optimizing development for clarity, ease of maintenance and


Objective
portability.
Estimated time 15 minutes
Calling methods, passing parameters and getting parameters in the
What we’ll use
called method

GETTING IT DONE
In the first lessons in programming, we saw how to set parameters for
buttons depending on the selected page.

Now we’re going to optimize programming to keep only a single


method that all navigational buttons (Query, Order by, etc.) will call.
Let’s call this method NAVIGATION_FUNCTIONS. It will receive two
parameters:
■ The first is related to the action to perform as text.
■ The second corresponds to the page on which we’re located.

You can call the method as follows for the “Add” button:

4D v11 - Self-training 147


PROGRAMMING

Basic Programming (Without Pointers)

The type of parameters are set in the called method:

A method can receive up to 32 parameters labelled $1 to $32. (Note:


using more than 7 or 8 parameters is rare).

For legibility reasons, I recommend creating local


ADVICE variables with explicit names to which you assign
parameter values. The best way to write this is:

The rest of the method is an adaptation of what we already coded in


previous chapters. We just need to adapt the action to the request and
the setting depending on the selected page (in other words, the table):

148 4D v11 - Self-training


PROGRAMMING
Exercise

The code isn’t yet optimized, but it’s already greatly improved because
we will concentrate the set of actions in a single method, which
simplifies reading, and, by extension, maintenance.

EXERCISE
Exercise 1: Set up the behavior for the query button and order by
button. Don’t do it for the other buttons because in the following
chapter, we will see how to make the set more “generic” using
pointers.

Exercise 2: Also set up page changing from the buttons on the left side
of the form. Create a method called NAVIGATION_TABLES to which
you can pass the page number as a parameter.

Then, you can take into account an eventual action depending on the
page and put in place the list query on page 8.

The add, query... buttons are useless when we’re on pages 7 or 8.


Disable them depending on the displayed page.

To enable or disable buttons, you can do it either one by one or in a


group. To be able to do this as a group (as you'll see in the key), you
must set an "object name" for each of the buttons.
I chose the names bNav... (bNavAdd, bNavFind, etc.).

See key on page 241.

COMMENTS
Programming is truly a subjective work of art. After all, doesn’t the
legal aspect of software cover both the program “author” and “author
rights”?

The manner in which these exercises are put in place shows you one
way of doing things. Depending on your habits, development
standards in your company, you’ll find different ways of organizing
things, a nomenclature system of fields and variables, an order for
settings parameters, etc.

4D v11 - Self-training 149


PROGRAMMING

Basic Programming (Without Pointers)

If you find a particular manner of doing things that feels right to you,
go for it and compare the advantages and disadvantages of each
solution. It’s also a great way to increase your experience.

Use and abuse generic programming. The next step to think about
is using pointers, which is a complement to what we’ve just
learned.
Generic programming also allows you to reduce the size of your
code by concentrating an entire series of functions in a single
method to which you will pass several text parameters.
To truly get started working with generic methods, keep this in
Going further mind:
- As soon as I write similar lines of code for the second time... there
is certainly a generic solution to consider.
- (Later) when you hesitate about creating a generic method: create
it, you’ll never regret it.
- Not everything can be made generic. Sometimes, trying to make
something too generic can lead to a decrease in productivity (loss
of legibility, difficulty in maintenance and upkeep).

150 4D v11 - Self-training


PROGRAMMING
24 Pointers

Objective Introduction to using pointers


Estimated time 20 minutes
What we’ll use Pointer concepts, optimizing programming and making it generic.

GETTING IT DONE
As we saw in the previous exercise, setting options for each action
(query, order by, etc.) in the NAVIGATION_FUNCTIONS method can
quickly become fastidious. So, we need to set the action towards the
table corresponding to the selected page.

In that case, it’s easier to indicate this just one time at the beginning of
the table to process. This directive is stored in a variable than used in
commands.

Logically speaking, we can’t say that a variable is equal to a table; these


objects are completely different and have completely different content
as well. We’ve already learned that a variable can be an integer,
numeric, text, picture, etc. It contains a value of the relevant type. A
table isn’t “content” like a numeric value is.

So, we’re going to use something called a pointer. The concept of a


pointer is a simple one that we use everyday in speaking. Don’t believe
me? Let’s find out!

4D v11 - Self-training 151


PROGRAMMING

Pointers

In the sentence “my dog is at home”, we use two pointers or


indirections. In fact, “my dog” doesn’t define the name or breed of the
dog. You would need to know who is speaking to define what dog
we’re talking about. That also goes for the house.
If Paul says “put it in the drawer” - what drawer is he talking about?
The drawer Paul indicated with his finger. He pointed to a drawer that
the other person will “de-point” (look towards which drawer Paul’s
finger is pointing).

This simple notion works well in 4D and allows replacing drawers with
tables, fields, or variables.

If I ask 4D to perform a query in this table, I first need to define which


table to query by pointing to it as follows:

In the rest of the method, we will use the $Table pointer in a phrase
like “I will query in the table that you showed me”; this bold text is
translated as follows:

As you can see, using a pointer is pretty easy. The advantage of its use
is to make programming even more generic and adaptable.

152 4D v11 - Self-training


PROGRAMMING
Exercise

Let’s take the example from the previous chapter in which you had to
indicate the table to process for each process depending on the page of
the form. We can now write the method as follows:

EXERCISE
Exercise 1: Finish programming this method by replacing the [table]
in the commands by a pointer towards the table.

Exercise 2: To complete what we just saw, and to complete what we’ve


learned, we’re going modify the Input inheritance form as follows:

You should touch up your input forms a bit. Each of these buttons are
available as a graphics file in the import file.
Put in place a generic method with pointers that allows navigating
filling in the set of functions.

See key on page 242.

4D v11 - Self-training 153


PROGRAMMING

Pointers

COMMENTS
At first, you might have a little trouble with pointers, but you’ll
quickly learn that not only are they very easy to set up, but they’re also
very powerful!

Pointers are often used as parameters during calls to methods. I


recommend that you spend a little time on this theme because it will
help you as soon as you start to say “I am going to duplicate this
button” or “I need to copy and modify this method.”

When you need to manage the list of pointers, it will be time to


start thinking about array pointers.
Going further So, you may also want to think about the “Get pointer” command
that allows you to define the name of pointers from a string of
characters. For example: Get pointer(“MyVariable”+String($i))

154 4D v11 - Self-training


PROGRAMMING
25 Events

Objective Managing events


Estimated time 35 minutes
What we’ll use Taking in to account and programming events

Do you pick up the telephone when its not ringing?

Do you pick up a colleague’s telephone without permission?

I’m going to guess that the answer is probably ‘no’ to both. Similarly,
4D also respects these same principals. This means that different
methods will be executed only if certain pre-defined events occur. Our
mission is to define the situations and behaviors, a little as if we tell a
child to only cross the street if the light is green and to only open the
door to people he or she recognizes.

Let’s become 4D’s air traffic control!

GETTING IT DONE
Let’s first learn to tell the difference between “form” events from
“database” events.

Form events only kick in if a form is used (on screen or when printing),
when the interface is manipulated by a user (click, drag-and-drop,
mouse-over, menu selection, keyboard stroke, etc.)

Database events only concern the four actions for data: creation,
modification, deletion, and loading. These four events are managed
by the data engine. This is important because in client/server, the data
engine turns on the server.You will never see a database event created
on your client machine. You cannot trace it on a client machine either.

4D v11 - Self-training 155


PROGRAMMING

Events

We’ll come back to database events later. First, let’s have a little fun
creating a “special” button.
1 Draw a standard button on page 7 of the Navigation form:

2 Modify its properties as follows:


■ Name: bSpecial
■ Only the event “On Mouse Enter” remains checked
3 Edit its method and input the following code:

You can copy the code in the method X_BUTTON_UNCLICKABLE

All that’s left to do is to view the form in use, display the preferences
page and try to click the button.

So, how did it go? Did it work? If the button falls off the screen, shut
the form and start again, the button will re-appear in its initial
location.

This exercise proves three things:


1) I’m quite the joker.
2) We can have fun discovering 4D and prepare for April Fool’s Day on
April 1.

156 4D v11 - Self-training


PROGRAMMING
Getting it Done

3) The method is only executed when the checked event occurs.

Only the third point really interests us in this exercise! Come on, be
serious! :=)

Let’s now detail the primary form events that you will use in the short-
term while giving an example of its use for each. Objects don’t all have
the same events; it’s impossible, for example, to check “On Data
Change” for a button object because you can’t “input” its content (its
title).

Event Starts Comments


On Mouse Enter When the mouse enters an objects We saw this in the previous example. The
“air space” two other linked events: On Mouse Move
and On Mouse Leave.
On Data Change At the exit of a field or variable This is primarily used for checks on input,
whose content changed formatting (capitals, lower case), queries,
re-calculations.
On Clicked When an object is clicked (mainly Can also be used on enterable objects.
buttons, popups, menus, etc.)
On Getting Focus The object just received focus This event is executed before the On
(from On Clicked, used with the Clicked event but after the On Mouse
tab key or with programming) Enter event.
For a button, events are executed in the
following order:
- On Mouse Enter
- On Mouse Move
- On Getting Focus
- On Clicked
- On Mouse Leave
- On Losing Focus
A field or a variable on which you click:
- On Mouse Enter
- On Mouse Move
- On Getting Focus
- On Data Change
- On Losing Focus
- On Mouse Leave
On Load Just before a form is displayed on During this events initialization are
the screen or used to print generally performed.
On Printing Detail During record printing Allows, for example, setting a value for
total, concatenation variables.

4D v11 - Self-training 157


PROGRAMMING

Events

This list helps you understand events. I’d like to recommend you
consult 4D documentation for a complete description of events.

There’s one important detail that new users always ask: “Do I need to
check form events or object events?” The response is simple:
everything depends on where you are going to create your method.

You’re probably going to say “of course, but why should I code in the
form method instead of the object method or vice-versa?”

That’s the second great question; good job!

The form method, in theory, should only contain what is relevant to


processing the entire form (resizing, outside call, display/hiding
objects, etc.). Methods specific to an object (button, field, etc.) that are
located on an object.

It does happen where we move certain processes on the form method.


For example, you must re-calculate a value depending on 10 enterable
parameters. For each modified parameter, you must re-perform the
calculation. Rather than put the formula (or method call) in each of
the 10 parameter fields, it is possible to move this calculation in the
form method. In that case, it’s easier and centralized; however, it is
highly likely that the re-calculation will be done more often than
necessary - especially when modifying an area that doesn’t figure in
the final calculation.

Location Advantages Disadvantages


Form method Centralized, global processing, easy to Risks being executed more often than
maintain needed
Object method Specific, adapted, executed only when Requires duplicating the method of
necessary. It easily allows porting an calling the method in each object
object using copy-paste (especially if
using pointers)

158 4D v11 - Self-training


PROGRAMMING
Exercise

To save time when writing your code and to make it more


reliable, think to setting macros (“macros.xml” file). For
TIP

example, you can create one that write the following code
for you when typing #$evt” in your method:
$evt:=Form event
Case of
: ($evt=On data change)

: ($evt=On load)

End case

EXERCISE
Organize the Help Requests page as shown in the screenshot below.
You’ll notice a ruler from 0 to 100 at the bottom right of the screen
(drawn using ). Its purpose is to visually and quantitatively
indicate the progress of the service from 0% to 100%:

4D v11 - Self-training 159


PROGRAMMING

Events

Set the ruler using the following template:

Next, and this is your mission (if you choose to accept it): the value of
this ruler must match the value of the field when you open a Help
request record. Then, if we update the rule by sliding from left to write,
you must update the field with the ruler value.

See key on page 244.

COMMENTS
I recommend that you start off by putting your methods in your
objects; you’ll have more flexibility for updating. Then, start by using
generic method calls and finally, when everything works properly, see
what you can move from your object methods to your form method.

Take a good look at how events work because they will allow you to
precisely understand exactly when to execute your programming.
You'll also a number of ideas for powerful first steps by using events:
Going further
on drag, on drop, on selection change, the three “on mouse”
events and, of course, the oldies but goodies, like on clicked, on
double clicked, on long click, etc.

160 4D v11 - Self-training


PROGRAMMING
26 Arrays, Pop-ups, ListBox

Objective Using array and associating them with form objects


Estimated time 30 minutes
What we’ll use Programming, variables, and interface objects

Arrays are one of the indispensable features in 4D. Practical, unlimited,


dynamic, one- or two-dimensional, they are a “space” in memory that
can be displayed in forms using objects (pop-ups, combo boxes, list
boxes, scroll areas, etc.)

GETTING IT DONE
We’ve already discussed the concept and use of single-value variables.
An array is a multi-valued variable that we can read or write each of its
elements. Like a simple variable, an array must be declared and then
applied a value before being used.

We define an array by setting the number of lines it contains and its


type. Here’s a chart showing the different stages of a variable and an
array’s life cycle:

Step Simple variable Array variable


Initialization C_TEXT(vText) ARRAY TEXT(ArrayText;10) `10 rows
Valorization vText:="Tascher de la Pagerie" ArrayText{1}:="De Beauharnais" `row 1
ArrayText{2}:="Barras" `row 2
ArrayText{3}:="Bonaparte" `row 3
...
Usage $NumChar:=Length(vText) $Amant:=ArrayText{1}

4D v11 - Self-training 161


PROGRAMMING

Arrays, Pop-ups, ListBox

Erase content CLEAR VARIABLE(vText) ARRAY TEXT(ArrayText;0)


(behavior is different between an
interpreted and compiled
application, refer to 4D
documentation)
View on a form Give the variable name to a variable Give the name of the variable to a
type object scroll area/pop-up menu type object.

Types Integer, Long integer, Numeric, Identical to variable types except Time
Alpha, Text, Boolean, Date, Time, and BLOB
Picture, BLOB, pointers

As you can see, there are a number of similarities between the two.

Since you already know quite a bit about arrays, all that’s left is to try
and create our first array in the Input form of the HELP_REQUESTS
table.

To do that, we must:

1˚) Create the array in memory (array of service “objects”).


2˚) Put an object in the form capable of representing the array in
memory.
3˚) Make sure that the array contains the right information.
4˚) Select a value and transfer this value to the OBJECT field.

To make the first steps easier, we will put all of the code in the object
defined in step number 2. That allows us to revise the event idea.
1 Select the popup/drop-down list object then draw it to right of
the OBJECT field.

2 Name it TabObjectRequest.

162 4D v11 - Self-training


PROGRAMMING
Getting it Done

In the pop-up method, we should plan on two events (make sure that
they are both selected):
■ On load: we will initialize the array and apply values just before the
form appears on the screen.
■ On click: when the user selects a value, we transfer its choice in the
Object field.

Here is the method to write:

You undoubtedly noticed that the name of the array is sometimes used
with braces { }, sometimes by itself (rows 11 and 12). In this case, it’s a
variable (long integer) automatically created by 4D. This variable,
associated to the array, serves as an array index (row number). It’s
through this variable that we can learn which row the user selected or
force selection of a specific row in the pop-up menu.

This is what you’ll often see this concise syntax written in database
examples or in other developers’ applications:

that we can decrypt as follows:


"Object := array content {at the chosen row}"

You’ll also find, though more concise and a lot more generic, this
syntax that uses the Self command (pointer towards the object whose
method is being executed):

4D v11 - Self-training 163


PROGRAMMING

Arrays, Pop-ups, ListBox

Regardless of the syntax used, the behavior is the same. You must then
input the following:

and once you’ve selected a value, this value is transferred to the Object
field:

Here’s another example with a new array that allows entering the time
the service starts by using a 12-hour window (6:00 AM to 6:00 PM) in
sets of 30 minutes.

To create the pop-up/drop down list, you can do as detailed above and
then create the method. For example, you could write:

However, you’ll see in the next database that I’ve set up the time arrays
in a slightly different way. A time array (interprocess) is initialized
when the database is opened (INIT_ARRAYS method called by the
Initializations method). To use within the context of services, copy the
array when the object method is loaded, which optimized
programming and prevents you from having to recalculate the array
each time, especially when used in several locations (start time, end
time, etc.)

164 4D v11 - Self-training


PROGRAMMING
Getting it Done

Here’s the third and final example: setting up a tab. A tab is an unique
object with several titles (values). In 4D, its an example of an object
that can represent an array.

We are going to reorganize the Input form of the Help_requests table


by moving the information that should appear on every page to page
0, then detailed information to page 1, and then the service log to page
2. Here’s a quick look at the re-organized pages:

Note that the upper part is identical. We’ll put in on page 0. The tab
helps us to browse, regardless of the displayed page, so we’ll need to
put it on page 0. We’ll now take a look at the content of the 2nd page.

Let’s take the following steps:


1 Display the form in the Design environment.
2 Cut the information out of page 1 (7 fields + text and Popup Object)
3 Go to page 0 and paste the content cut in the previous step.
4 Select the Tab Control object and draw it in the form.

5 Name it <>Tab_Requests (variable name).

4D v11 - Self-training 165


PROGRAMMING

Arrays, Pop-ups, ListBox

6 Open its method and copy the following code:

7 Create the second page of your form (leave it empty for now, we’ll
fill it up next).
You can test browsing and moving from page to page with your tab.
This works, yet we didn’t have to code the tab’s behavior when clicking
it anywhere! You were probably just thinking that, weren’t you? :=)

No, Harry Potter didn’t use his magical powers on our application. :-)
Quite simply, 4D defines the standard action for a tab as “Go to page”
by default:

Of course, we can always disable this standard action and manage tab
behavior programmatically!

166 4D v11 - Self-training


PROGRAMMING
Exercise

EXERCISE
Create a popup/drop down list that indicates the time the service is
completed.

See key on page 245.

COMMENTS
As you’ve learned, arrays become useful quite quickly; in fact, they
quickly become a necessity!

In 4D, an array only contains items of the same type. You cannot have
an array with an Alpha element, a Date element and then a third Time
element. In that case, you can use an array of pointers that could point
to variables of different types.

As mentioned in the lesson on pointers, you can combine pointers


and arrays to get “pointer arrays”.
Going further
You can also consider a ListBox to be a series of connected arrays
(of the same X dimension).

4D v11 - Self-training 167


PROGRAMMING

Arrays, Pop-ups, ListBox

168 4D v11 - Self-training


PLUG-INS
27 4D Write

Objective Installing, configuring and using the 4D Write plug-in


Estimated time 15 minutes
What we’ll use Plug-ins folder, form editor

4D lets you add plug-ins very easily. Plug-ins are provided by both 4D
SAS, other developers, or even yourself!

In this lesson, we will discuss the installation configuration phases of


the 4D Write plug-in. This will give you the know-how to use word
processing functions within a 4D application.

GETTING IT DONE
Let’s start by installing the plug-in.
1 Quit your application.
2 Create a folder named “Plugins” at the same level as your structure file
(on Mac OS, put the new folder in the Content:plugins package).
3 Drag the 4D Write plug-in to the Plugins folder.
4 Re-launch your application (if you don’t have a license, a message
appears indicating that you can use it for up to 30 minutes).

Your plug-in is now installed. To make sure it is working properly, you


can:
■ Choose “Display the current table” in the Records menu.
■ Select 4D Write in the Tools menu.

4D v11 - Self-training 169


4D Write
PLUG-INS

The following window is displayed:

Your plug-in is now active, so you can close the window. For more
information on using 4D Write, as well as its features and
programming with it, check out the documentation.

I told you there was nothing easier than installed a plug-in! :=) Now,
we will associate a 4D Write area with a field, which provides us with a
word processor that we can use directly in our input form.

In the previous exercise, we added a page to the Input form in the


HELP_REQUESTS table. We’re going to install the plug-in in the second
page:
1 Open the Input form.
2 Go to page 2.
3 Click the Plug-in area tool .
4 Draw an area in the bottom part of your form (in the tab area.)

170 4D v11 - Self-training


Getting it Done

PLUG-INS
Your form will look as follows:

We now need to set parameters for this area (it’s actually a variable) so
that it contains the 4D Write plug-in:
5 In the “Type” property, scroll through the list and choose 4D Write:

4D v11 - Self-training 171


4D Write
PLUG-INS

6 Name the variable "Report”:

At this point, we have a word processor area that can be used in the
form. If we look at the message (in red) displayed at the top of the area,
we understand that to associate (automatically) the content of this area
to a table field, we should have a field named “Report_” (the “_” is
important here):

7 Create the field Report_ as a BLOB in the HELP_REQUESTS table.


Back in the form, the following message appears automatically:

And that’s all she wrote! Now, every time we create or modify a report
in a HELP_REQUESTS record, 4D automatically saves it in the Report_
field and released when the record is opened. All that and zero
programming!

172 4D v11 - Self-training


Exercise

PLUG-INS
You can test it by adding and modifying Help Requests records:

EXERCISE
Perform the same installation with the 4D View (spreadsheet) plug-in
by creating a third page in the Input form of the HELP_REQUESTS
table.

In the tab, name this third page NUMBERING.

See key on page 246.

4D v11 - Self-training 173


4D Write
PLUG-INS

COMMENTS
Some plug-ins are available with 4D by default (4D Internet
commands, 4D Pack, etc.) I recommend that you install them for your
project. These days, it’s rare that you develop an application without
having to take into consideration FTP flows, sending/receiving e-mail
or programmed startup of other applications.

It’s also possible to develop your own plug-ins using the “Plug-in
SDK”. This tool lets you set your input points, input and output
variables, as well as numerous parameters linked to generating code.
You can then generate your project. The library call code is
automatically generated. All that’s left is to write your specific code.

Plug-ins bring flexibility and power to your application. I recommend


that you check out the list of available plug-ins provided by 4D SAS, as
well as third-party plug-ins. In most cases, you’ll save a lot of time by
taking advantage of someone else’s work - where not only is it already
done, but also maintained, by others who had exactly the same
problems as you!

See 4D Chart, 4D Internet commands, 4D Pack, etc. and how the


Going further
work, as well as their available options.

174 4D v11 - Self-training


PROGRAMMING
28 Windows and Navigation

• Understanding the possible interaction between


Objective programming and interface management.
• Using automatic sizing properties for objects.
Estimated time 30 minutes
Form editor, Properties palette
What we’ll use
Method editor (on load events)

Creating the interface of an application is probably one of the most


time-consuming aspects of development. In fact, it can represent up to
70% of a project’s workload! So, it’s important to understand the
primary aspects of interface development so you don’t have to
reinvent what 4D already allows you to do easily. For example, this
includes resizing, enlarging objects, managing the close box.

GETTING IT DONE
In our Input form in the Help Requests table, we want to include a
send e-mail button. This e-mail will be sent to the technician in charge
of the intervention.

To do that, we need to add this button and the input e-mail interface.
Then, we need to send the e-mail (this will be the goal of the next
lesson.)
1 Create the input e-mail form using the project form.

4D v11 - Self-teach 175


PROGRAMMING

Windows and Navigation

To start, we plan on using this form in other circumstance. All areas of


the form are variables that we can feed the content of fields from one
table or another.

Let’s make the areas auto-adjustable. Their width and/or height will
adapt to the size of the window in case of resizing.
2 Select all variables and then modify the “Horizontal sizing” property.

3 Then, and only for the vContent, add also “Grow” in the “Vertical
sizing” property:

With these Size properties, you start to see the inner workings of 4D
whose objects adapt to your desires, while sticking to the size of the
form.

We now need to indicate the type for these variables.


4 Place this line of code in the form method for the on load event.

176 4D v11 - Self-teach


PROGRAMMING
Getting it Done

This is the ideal location for this type of processing.

5 Add a button to send the e-mail (we will program it in the next
lesson.)
You can add it to the picture library. It is the “Mail” file in the
“Images_png” folder. Then drag the button from the library to your
form.

The dialog box is ready. We can create the call button for this dialog
box at the bottom of the Help Requests INPUT form:

The method of the button that allows displaying the dialog box is as
follows:

4D v11 - Self-teach 177


PROGRAMMING

Windows and Navigation

Let’s test the dialog box’s behavior. You should get this screen:

If you resize the window, all of the fields should enlarge and the send
e-mail button should move, as well as the associated text.

All that’s left for us to do is transfer the useful information in the Help
requests table’s fields to the form variables (e-mail recipient, subject,
and content). Here is one way of adapting the call e-mail dialog box
button:

178 4D v11 - Self-teach


PROGRAMMING
Exercise

When inputting a service, you can send an e-mail to the technician


with the relevant information:

EXERCISE
4D uses the ALERT command to display messages. You’ll quickly
notice that it is often necessary to update messages with additional
information. Keeping in mind future application, you will put in place
a customizable form that will replace the ALERT command and display
more personalized messages.

4D v11 - Self-teach 179


PROGRAMMING

Windows and Navigation

Here is the form template to create:

Then, the dialog box is called using a method that you must create.
This method, DIALOG_ALERT, receives three text parameters:
■ the title of the window,
■ the alert message
■ a complement (if necessary)

You need to be able to display a message similar to the following


message in case of error:

180 4D v11 - Self-teach


PROGRAMMING
Comments

See key on page 247.

COMMENTS
Keep in mind that the alert dialog box is a completely separate form. It
can contain several pages, a tab, buttons, arrays, and anything else you
deem necessary. You could even suggest automatic sending of e-mail
to customer service with information about the user, the computer,
the date, the time, the error message, etc. or, simply, the record with
this information in a log file that customer service can access.

You can also set the form so that it displays or hides a given button,
adds a clickable URL that allows accessing online help, select the
language in which you display messages, set messages from a table
selected by the user, etc. Once you get the hang of it, the sky is the
limit.

Going further Types of windows, managing the close box.

4D v11 - Self-teach 181


PROGRAMMING

Windows and Navigation

182 4D v11 - Self-teach


PLUG-INS
29 4D Internet Commands

Two ways to send an e-mail:


• the easy, efficient way that isn’t very customizable
Objective
• the less easy way, but has more features, including SMTP
authentication and file attachments
Estimated time 45 minutes
What we’ll use 4D Internet Commands (SMTP commands) plug-in, Method editor

I bet you’re dreaming of sending e-mails easily from your database. In


the previous lesson, we set up the interface to do just that. The 4D
Internet Commands plug-in offers two distinct methods for sending e-
mails. One is simple and efficient, but it doesn’t really let you
customize it. The other is a lot more flexible, but it’s also a bit longer to
code.

We’re not planning on keeping sent e-mail. However, if you want to


do that, you can either create a table with the necessary fields, or store
the information in a BLOB in the table from which the e-mail was sent,
or simply CC: the e-mail to another e-mail address.

GETTING IT DONE
To start, we need the 4D Internet Commands plug-in commands.

Install it like you did with 4D Write and 4D View then re-start your
database.
1 Open the MAIL project form and then display the method for the send
e-mail button (in the upper right).

4D v11 - Self-training 183


4D Internet Commands
PLUG-INS

The quickest way is to use the SMTP_Quicksend as follows:

You’ll notice that this command doesn’t allow adding carbon copies,
blind carbon copies, and/or documents. However, it is very practical
and quickly set up.

The second available solution is to use a series of unit commands that


define each parameter of the e-mail. Here’s a simplified version:

This version, although function, isn’t truly satisfying because it doesn’t


take in to account any potential errors returned.

Here is a more complete method, which still has room for


improvement. For example, it allows adding only a single file

184 4D v11 - Self-training


Getting it Done

PLUG-INS
attachment and doesn’t take into account blind carbon copies or the
reply-to:

4D v11 - Self-training 185


4D Internet Commands
PLUG-INS

Put in place this send e-mail method (you can copy the text in the
Send_Email method in the adjusted database).

You may have noticed the use of the <>SMTP_Server


variable that can set once the database is opened. If you

TIP
don’t set parameters for it, the 4D Internet Commands
plug-in cannot send e-mails and an error message is
returned.

EXERCISE
Put in place a method that allows sending an e-mail to an e-mail
address defined when an error message is displayed (exercise related to
the previous lesson).

See key on page 248.

COMMENTS
With 4D Internet Commands, you can create a full-service e-mail
application. However, that’s not our goal here. What is of interest to us
is that all the functions necessary for working with the Internet (e-
mail, FTP, SMTP, HTTP, TCP/IP, etc.) are available in 4D.

Sending e-mail is a very good exercise for starting to programming


Web exchanges. You can go one step further by adding HTML tags in
your messages that allow using bold and italics in your text. If you do
that, think of setting your headers so that e-mail using HTML is
recognizable by most web browsers.

Going further Managing TCP, FTP flows with 4D Internet Commands

186 4D v11 - Self-training


SECURITY
30 Passwords and Groups

How to manage groups and users, set permissions and assure


Objective
that they remain unchanged during updates.
Estimated time 10 minutes
Password editor, users and groups
What we’ll use
Method properties

4D allows you to manage both groups and users; it also allows limiting
access to specific objects or actions:
■ Tables: load (see), create, edit, delete
■ Executing methods
■ Displaying forms
■ Selecting menu items
■ Accessing plug-ins
■ Accessing the Design environment

It is also possible to manage group membership, password checks, etc.


programmatically.

GETTING IT DONE
In any 4D database, there are at least two users:
■ the Designer, who has full read/write privileges
■ the Administrator, who is usually a client user that administrates
the database and sets permissions.

The database opens freely as long as the Designer account is not


password protected.

4D v11 - Self-training 187


Passwords and Groups
SECURITY

To display the list of users, display the toolbox:

The list of users is selected by default:

Simply click Designer then “Edit” to set a password for the account.

ATTENTION: The password accepts both upper and lower case letters.
Like with any password, guard it with your life because you cannot get
it back if you forget it!

You can then add users. Careful, users created by the Designer cannot
be modified by the Administrator and vice-versa. That’s to be expected
since one is supposed to be responsible for developers while the other
the client-side administrator. It’s important that they not interfere
with permissions.

Currently, since no password has been defined, the database opens


using the Designer account.

188 4D v11 - Self-training


Getting it Done

SECURITY
To create groups, click and then .

Enter the name of the group then check the users who should belong
to the group, as well as plug-in access permissions.
A group can be a member of another group. If that’s the case, the child
group inherits permissions from the parent group.

Once you create your groups and users, and assign users to groups, you
can indicate how you want to use your groups.

The point is to indicate which group has the right to perform a given
procedure. For a method, you can indicate which group is owner (in
other words, which group is allowed to modify it in the design

4D v11 - Self-training 189


Passwords and Groups
SECURITY

environment) and which group of users has access to the method and
can execute it:

If an unauthorized user tries to execute the method, an information


message kindly explains that the user doesn’t have the appropriate
permissions.

Use can use the Current user and User in group commands
programmatically to intervene in access to a specific part of your
application.

190 4D v11 - Self-training


Exercise

SECURITY
EXERCISE
Create several users (it is possible to not set a password for them right
away during testing). When you will restart your database, you should
get a dialog box such as the following:

Check out the documentation for the syntax of the Current user and
User in group commands and then prohibit access to pages 7 and 8 of
the NAVIGATION form to all users not in the “SETTINGS” group. You
must also create this group and give it users (including Administrator).

See key on page 249.

COMMENTS
Users and groups are stored in the 4D structure. This behavior implies
several precautions when updating the product site because any
changes made by the administrator (setting a user in a group, etc.) risks
being overwritten by your new structure (the one where you made
modifications).

4D v11 - Self-training 191


Passwords and Groups
SECURITY

The administrator is able to export and then re-import the set of


parameters (users, groups, associations) of the old database in to the
new database. This option is available in password management.

You can (re)create or modify the set of passwords and permissions


programmatically.
You can also manage your own password system. If you do that,
Going further
you should manage any and all implications of permissions for a
user. Like always, it’s a more flexible solution, but it also requires
additional programming to replace what 4D already has done.

192 4D v11 - Self-training


PROGRAMMING
31 Triggers

• Setting the events engine


Objective
• Taking database events into account in programming
Estimated time 10 minutes
What we’ll use Event engines, optimizing processes through centralization

A trigger (table method) is used to check on actions performed by the


database engine on data (creation, modification, deletion, loading). In
that sense, a trigger is a method like any other. Its simply the context
in which it is executed that changes.

In fact, triggers are started during ENGINE events and no longer form
events as we’ve seen up through now. By calling an ENGINE event,
there’s an important precision to note: triggers are executed on the
database engine.

In single-user, it’s the 4D program that contains both the database


event and the return event (displays, etc.) In client/server, data is
stored on the server and sent to client machines using the 4D Server
engine. In that case, triggers are executed on the server and not locally
on the client machines.

4D v11 - Self-training 193


PROGRAMMING

Triggers

GETTING IT DONE
Like form events, database events must be checked so that 4D gives
control to the trigger to execute. We can enable any database event in
the Table inspector, as you can see in the following screen:

You’ll find the “Edit” button at the bottom right, which allows
creating the method to create when the checked events occur. The
method is generally structured in the following manner:

Unlike a form method that is only executed during a display (or print),
a trigger is executed regardless of how you access records (display in a
form, programming, import/export, ODBC, etc.) The trigger has the
advantage of being a mandatory passage point.

Knowing that a trigger blocks the other processes during execution,


the main rules to follow in a trigger are:
■ speed of execution
■ no interface (alerts, messages, etc.)

194 4D v11 - Self-training


PROGRAMMING
Exercise

EXERCISE
Add a Duration field in the Help Requests table and make it so that it
automatically calculates when the end of the service is noted.

See key on page 250.

COMMENTS
Generally speaking, get used to creating project methods that take care
of your processes, calculations, etc. and call these “generic” methods
from specific methods such as triggers. We saw how to pass
parameters, so take advantage! It’s a lot easier to maintain and you
save a considerable amount of time developing as well as bug fixing.
Your code will be a lot more concise, reliable, and readable.

You can execute cascading triggers. In that case, 4D has commands


that allow finding out the trigger properties and its cascade level.
A trigger can also serve to "accept" or "reject" any operation
Going further
attempt on the record. This is a way to allow you to ensure the
integrity of your database regardless of how information is
processed (ODBC, plug-in, input, import, etc.).

4D v11 - Self-training 195


PROGRAMMING

Triggers

196 4D v11 - Self-training


PROGRAMMING
32 Current Selection

• What’s a selection?
• How to put a selection together and browse from record to
Objective
record
• Interaction between selections and arrays
Estimated time 45 minutes
What we’ll use Method editor, Arrays, Form editor, ListBox, Object properties

Now that the interface and its primary features are in place, we’re now
going to work with records and see what 4D has in store for us.

Before we do anything else, let’s talk about the concept of the current
selection. This is one of the fundamentals of 4D that is a little different
than the usual concepts, especially SQL. We’ll talk about the SQL part
of 4D later in the lessons.

A current selection is a list of records obtained by querying the table.


In 4D, we continually have a current selection per table. This selection
can contain anywhere from 0 to X records. The current selection
consists of the list of records on which we’ll perform processes. You
can change the current selection between two processes.

Let’s take a look at an example: if I want to print all services for the
month of May 2007, I first need to query (I create a current selection)
then I print these records by using, for example, an output form
containing several fields from the services table (Date, Object, etc.)

4D v11 - Self-training 197


PROGRAMMING

Current Selection

The following schema illustrates how 4D works, in other words the


SELECTION-ACTION mode:
CREATING AND USING A CURRENT SELECTION

SCAN RELATE ONE RELATE ONE RELATE RELATE MANY


INDEX SELECTION MANY SELECTION

REDUCE USE SET


SELECTION

IMPORT USE NAMED


SELECTION

QUERY CREATE SELECTION


SELECTION FROM ARRAY

QUERY QUERY WITH


ARRAY

ALL RECORDS ...

CURRENT SELECTION
(1 per table and per process)

Records found Processing

Once on the On each record


selection

ORDER ...
BY

For Repeat
DELETE EXPORT ... ...
SELECTION End for Until

PRINT APPLY TO While


SELECTION SELECTION ...
End while

GETTING IT DONE
As indicated in the above schema, the QUERY command is one of the
ways to obtain a current selection.

198 4D v11 - Self-training


PROGRAMMING
Getting it Done

We’re going to get it going by creating a statistic array presented in a


ListBox. It will obtain the number of services per technician for a given
period.

The processing order is as follows (once you’ve determine the desired


time period):
1˚) query all technicians (1 current selection in the Technicians table)
2˚) make a loop on the current selection and take each record one after
the other
3˚) for each technician, query his services (1 current selection in the
Services table)
4˚) query in this selection the services for the desired period
5˚) store the result in an array
6˚) add the technician’s name in a second array
7˚) display the two arrays in a dialog box

Note: We will use a second method to obtain the same result and will
re-do this exercise including SQL commands in 4D so that you see the
different possibilities.

In the meantime, back to work! Let’s start from the top:

Before you begin: You must determine the desired period. In this
exercise, we’ll limit ourselves to the current year from January 1 to
December 31. Then, you can improve the system to present a choice of
periods to the user.
1 Create a method named STATISTICS that integrates two variables for
the period of dates:

2 Query all technicians (1 current selection in the Technicians table):

4D v11 - Self-training 199


PROGRAMMING

Current Selection

3 Make a loop on the current selection and take each record one after
the other:

4 For each technician, find his or her services (1 current selection in the
Help requests table):

5 Query the help requests for the desired period in this selection:

6 Store the result in an array.

200 4D v11 - Self-training


PROGRAMMING
Getting it Done

But wait, did you declare your array? Let’s do it before the loop.

7 Add the technician’s name in the second array.


Wait! It’s not declared either...

You must display the two arrays in a dialog.

4D v11 - Self-training 201


PROGRAMMING

Current Selection

8 Create a Project dialog:

9 Choose the tool and draw it in the lower right hand side of
the form:

Remember: a List Box is an object that gathers and synchronizes from


1 to X arrays. In a List Box, you can set the List Box itself, each column
header and each column. In all, if you List Box contains X columns,
you have 2X+1 objects (X columns, X headers, 1 ListBox).

The List Box allows inputting data, the order by and moving rows and
columns, the display of alternate colors. It can be synchronized with
arrays like we do here or with the fields of the table’s current selection.

Knowing that the List Box synchronizes its columns, it takes the
smallest number of rows of the arrays that comprise it. This is
important because you will have a situation where you have filled
arrays and an empty List Box because a single array is empty.

Let’s get back to setting the List Box.

202 4D v11 - Self-training


PROGRAMMING
Getting it Done

10 Modify the properties as follows:

You will get:

4D v11 - Self-training 203


PROGRAMMING

Current Selection

11 Click Header1 and change its name to “Technician”. Do the same for
the second header and call it “Help Request Number”:

12 Click the first column (below the header) and give it the name of the
technicians array as a variable name (TechniciansStatsArray). Do the
same for the second column and the array for the number of help
requests (HelpRequestsStatsArray).

Our form is complete. We can finalize the Statistics method by


displaying the form:

204 4D v11 - Self-training


PROGRAMMING
Exercise

And there you go! You just created a simple statistics module!

EXERCISE
Modify the programming of this exercise so that it takes into account a
third column corresponding to the average time per service. In this
case, you only need to use completed services (where an end time is
set).

See key on page 251.

COMMENTS
To optimize several rows, from the start we could have created an array
starting from the selection of technicians with the DISTINCT VALUES
command, then put a loop on the array.

We can perform other optimizations with the command, which avoids


having to change the selection. This is identical to SELECT COUNT in
SQL.

4D v11 - Self-training 205


PROGRAMMING

Current Selection

206 4D v11 - Self-training


PROGRAMMING
33 Sets and Named
Selections

• Keep a selection
Objective
• Perform crosses (intersection, union. etc.)
Estimated time 20 minutes
Method editor, programming, and use of temporary selections and
What we’ll use
sets

Sets are a simple way to perform functions (union, intersection,


difference) on records of a single table. They are one of the ways that
allow putting a selection on hold so that it can be re-used later.

By performing an operation on two sets, we get a set containing the


result of the performed operation.

Sets are composed of a series of bits. A set contains as many bits as


there are records in the table. Each bit of a set corresponds to a quick
report “included in the selection” or “not included” for the Xth record
of the table at the moment the set is composed.

GETTING IT DONE
Don’t worry, setting up sets is a lot easier than the explanation! :=)

To compose a set, simply use the CREATE SET command in the current
selection. Let’s take the case of services started before 09:00:00.

4D v11 - Self-training 207


PROGRAMMING

Sets and Named Selections

In this command, we set the name of the relevant table as the first
parameter, then the name for the set.

We are going to create a second set for all help questions in progress
(advancements < 100%).

We now have two sets that we can compare so that we get:


■ morning services + interventions in progress

■ morning interventions still in progress

■ completed morning interventions

4D automatically creates the “HelpRequests_Result” set and associates


it to the [HELP_REQUESTS] table. If we want the records of the result
set to become the current selection, simply use this set:

I know that you code cleanly and like to take care of the amount of
memory available, so when your sets are no longer needed, you can
erase them:

Named selections Now that you understand how sets are used, we will learn the second
solution for keeping a selection: named selections.

208 4D v11 - Self-training


PROGRAMMING
Getting it Done

The idea behind using them it simple; simply use (at least) the two
following commands:
■ COPY NAMED SELECTION where you want to create a named selec-
tion from your current selection.
■ USE NAMED SELECTION where you want to regenerate your current
selection from the named selection.

Of course, when selections are no longer necessary, you can free up


memory by erasing them. Here is the creation, use, and deletion of a
named selection (in a nutshell):

In terms of memory, a selection needs 4 bytes per selection record,


regardless of the number of records in the table (unlike sets).

The table below sums up the all of possibilities for sets and temporary
selections:

Theme Set Named Selection


Memory space for a record 1 bit 4 bytes
Keep order by No Yes
Keep the current record No Yes
Union Yes No
Intersection Yes No
Difference Yes No
Save to disk Yes No
Memory size of a selection of 10 records
20,000 bits or 2500 bytes 10 x 4 bytes = 40 bytes
out of 20,000
Scope Local, Process, Interprocess Process, Interprocess

4D v11 - Self-training 209


PROGRAMMING

Sets and Named Selections

EXERCISE
To improve the interface provided for your users (their happiness has
no price), you want to set up the following system: starting from a
selection of records, they must be able to add new records. When a
user completes additions, he or she must find the increased initial list
of newly created records.

Put your programming on the add button and use the following
commands (among others):
■ Create set

■ Add to set

■ Union

■ Use set

See key on page 253.

COMMENTS
As you might have guessed, we can only compare sets of a single table.
Be careful! The behavior of a set implies during a limited time and
eventually using semaphores (see 4D documentation for more informa-
tion). In fact, a set makes a bit correspond to the physical position of
each table record. In case of deleting and then adding records, the
former content of a physical record could be replaced by the new con-
tent that is no longer in line with what the set is supposed to represent.
Be methodical in the use of sets, which remain an efficient and fast
way to compare selections.
To keep a selection, there’s a third solution that involves
using an array that contains your identification using the
TIP

SELECTION TO ARRAY command. You can use a fourth


solution using stored clusters; for example, in BLOBs.

Now that you understand how sets are used, look in the 4D
Going further
documentation to find out about other commands used with sets.

210 4D v11 - Self-training


PROGRAMMING
34 Process

• Programming a process’ life cycle: Birth, life, death


Objective
• Managing an interface specific to a process
Estimated time 20 minutes
What we’ll use Multi-process programming

Processes are often assimilated in to multi task jobs. They allow


creating several jobs simultaneously, without having to complete the
first process before starting the second.

A process is an environment that possesses its own memory space, its


current selections (one per table), its own variables (process variables),
and eventually its own interface, etc. Processes can communicate
between themselves in different ways (interprocess variables, reading
or writing variables, etc.). They can be put to sleep (sleep process) or
even hibernation (suspended procesS) until another process wakes
them up. A process only dies when the method it executes is
completed. You cannot for a process to die programmatically, even
though you can program it to die in certain conditions.

Processes generally serve the following purposes:


■ create particular processes (batches, “submarine” checks),
■ create tool palettes (independent windows with specific functions),
■ display input/view dialogs so that the user can work with multiple
windows.

4D directly generates certain processes.

4D v11 - Self-training 211


PROGRAMMING

Process

GETTING IT DONE
Let’s say that you want to access the statistic module that we set up in
a previous lesson. You want it to remain active while you do
something else.

To do that, we will start the method in a process and allow the user to
refresh its statistics by clicking a button that we’ll add in the form.

Let’s start the last step, which means preparing the interface.

During the exercise of the chapter 32, the following changes have been
made to the database:
■ You created a button calling the method that fills arrays:

212 4D v11 - Self-training


PROGRAMMING
Getting it Done

■ You moved the recalculation method to the button:

■ In the Statistics method, you directly displayed the statistics form


without having previously performed calculations:

Note: In this example, I suggest keeping the arrays initialization in the


method displaying the form. This initialization would be completely
appropriate in the method on form load.

Now, we must create the process; in other words, we must create the
execution environment for this method:

A process is creating using the New process command:


vProcessNumber:=New process(Method;Stack;Processname;Settings;...)

4D v11 - Self-training 213


PROGRAMMING

Process

This command line must be in the method. I recommend using the


concept shown below, you’ll save time and clarity.

The method calls itself (it create a second instance of the method in
the new process) and passes itself a parameter:

When calling the method (without parameter), 4D creates a process in


which it executes a method. The first method ends while the method
executed by the process continues along and presents the statistics
array.

As such, you can continue to work while having the statistics window
at your fingertips.
To trace the execution of a process (when you execute the
New Process line), use the “step-by-step new process”
TIP

button. This button executes the line and opens a second


trace window in which you can follow the progress of the
executed method in the process, independently of the calling
method.

EXERCISE
Create a process that displays the time and elapsed time since the new
process started. This exercise will give you the basics of setting up a
time counter.

See key on page 253.

214 4D v11 - Self-training


PROGRAMMING
Comments

COMMENTS
This simple example allows you to consider quick evolutions in your
programming. You can conceptualize your processes, test them in
several lines of code, and set them for independent execution in a
process.

There are numerous examples of using processes. Here’s one more: you
have updates to perform on an important database; however, these
updates can be staggered by several seconds or even minutes without
having an impact on your company’s performance.

You can plan on having a table where you save a to-do list of tasks to
perform. For each of these tasks, you specify a date, a time, and
eventually a priority level and a description of the task to perform
(what? on what table? what record? etc.)

Then, set in motion a process whose sole mission is to consult this


table and perform the set of tasks for it. When it finishes this, it is
suspended until a new task is recorded and the process is re-enabled.

Going further Interprocess communication, locking records, semaphores

4D v11 - Self-training 215


PROGRAMMING

Process

216 4D v11 - Self-training


PROGRAMMING
35 SQL

Objective Performing SQL requests in 4D


Estimated time 40 minutes
Set up simple SQL commands integrated into 4D programming in
two forms:
What we’ll use • several SQL command lines inserted in a SQL processing block.
• a single command line that executes the list of commands stored
in a text variable

In addition to the native 4D language, you can used SQL commands in


4D like you do in other tools. These commands can be integrated into
existing development projects quite easily.

Let’s again work with the statistics example to create the same array
from the SQL commands.

GETTING IT DONE
Create a new method that you’ll call SQL_STATISTICS.

We can break down the step (filling statistic arrays) in two parts:
■ getting the list of technicians
■ for each technician, calculate statistics

4D v11 - Self-training 217


PROGRAMMING

SQL

Here is the part of the method that allows creating the first array:

Note the syntax that indicates that 4D transferred the result to the
arrays. We use the variable name proceeded by the “:” symbol (colon).

At this point, we have two filled (and synchronized) arrays.

The rest of the method (sizing arrays) is structured overall in the same
way:

Now, we’ll again use SQL commands to apply values to the arrays:

218 4D v11 - Self-training


PROGRAMMING
Getting it Done

This first example allows getting the total number of services


performed by each technician. To limit the number of services to a
desired period, we can code it as follows:

In order to confusion surrounding field names, you can code the


request by prefixing the table name fields:

4D v11 - Self-training 219


PROGRAMMING

SQL

Another way of executing the SQL command is to put together a text


containing all of the request then executing the text as follows:

We can’t use pointers and array rows in a SQL request; the


interpretor doesn’t take them into account. To use them, it’s
TIP

usually better to put together the request as a text and to


execute it using the EXECUTE IMMEDIATE command.

EXERCISE
Exercise 1: To complete the statistic array, you will create a summary
array presenting the number of records contained in the set of tables.
The results (numbers) may vary from the corrected report, depending
on the number of records you created.

Exercise 2: Create a requestor that allows inputting your own SQL


commands and to execute them while using the database.

See key on page 256.

220 4D v11 - Self-training


PROGRAMMING
Comments

COMMENTS
The two languages bring both flexibility and possibilities. If you start a
new development project, you can decide to access the database
engine solely using SQL and keep the 4D language for other purposes
(interface, managing user context, etc.).

If you use an existing development projects, you can


ADVICE
gradually replace part of the code using SQL commands,
which is great practice. To that end, I recommend that
you encapsulate your code in a simple test, like this:

Going further Discover the four ways of using SQL in your development projects

4D v11 - Self-training 221


PROGRAMMING

SQL

222 4D v11 - Self-training


PROGRAMMING
36 BLOBS

• Understanding and programming BLOBs


Objective • Interaction of BLOBs with variables
• Saving and reading a BLOB in a document
Estimated time 15 minutes
What we’ll use BLOBS, variables, debugging

BLOBs allow storing and getting back all kinds of information.

When starting out, we always ask the same questions:


■ What good can this serve and in what circumstances?
■ I’m fine with putting “things” inside, but how? and in what order
will I get them back out?

Let’s start by tackling the second question: even though we can access
any byte of the BLOB, in most cases we’ll use what we call FIFO (First
In First Out). This means that you recuperate the content of the BLOB
in the order in which you put it into the BLOB.

To make a simple analogy, let’s take a bookshelf where you put away
books from left to right. You start by putting away a small book on the
left and then a large book next to the first one, and then another big
book and then a picture of your mother-in-law and a knick-knack from
last summer’s vacations, etc. When its time to dust the bookshelf, you
don’t think about how many inches from the left side a book is
located. You take them in the order they are and you adjust your gaze
(and hands) depending on the size of the last object picked.

It’s the same thing in a BLOB, especially because you know what you
put away in the BLOB. If you put away an integer, it’s 2 bytes. A long
integer is 4 bytes, while a date is 6 bytes long. For text, you indicate
how you want it put away and how is expressed in the length of the

4D v11 - Self-training 223


PROGRAMMING

BLOBS

text (C string, Pascal string, etc.) During re-read, you will re-take the
information in the same order and put them away in variables that are
adapted to the expected content (typed correctly). As such, reading the
BLOB is done in a coherent manner.

Here’s the response to the first question (what is the purpose of a


BLOB?) You can use it, for example, in the following cases:
■ Store variables, hierarchical lists, arrays
■ Exchange documents between client and server
■ Protect confidential data in an encrypted BLOB
■ Process documents or text greater than 32K
■ Save variables containing plug-ins
■ Send pictures, texts, or documents to a Web browser
■ Communicate with a web service

Now that you feel better, but still doubtful, let’s put the simplicity of
BLOBs to the test!

GETTING IT DONE
Let’s use a simple example, say, storing variables. We are going to
apply values to three variables, then store them in a BLOB and then
recuperate them in three other variables of the same type. We will
perform checks on how the BLOB and variables are filled using Trace
mode as necessary.
1 Create the BLOB_MANAGEMENT method as follows:

224 4D v11 - Self-training


PROGRAMMING
Getting it Done

The VARIABLE TO BLOB command stores the data in a format internal


to 4D. That’s why the required space is slightly greater than the raw
data size. The advantage of this command is that it prevents you from
having to manage Byte Swapping (position of the heavyweight byte)
when working cross-platform.

Once row 16 is executed, the BLOB contains the following


information:

Storing the date adds the following bytes to the BLOB:

4D v11 - Self-training 225


PROGRAMMING

BLOBS

At the end of the third addition, the BLOB contains 53 bytes. Now, we
can extract the data from this BLOB and transfer it to output variables:

Once the first two rows are executed, you can see that variable
recuperation is in progress.

You can see that using BLOBs is really very simple, even if this example
is a very limited sample of how to use one.
When you fill a BLOB, you can use the * character instead
of the $PositionInBlob variable that we used. 4D
TIP

understands, using this parameter, that it must store the


variable at the end of the BLOB and increase its size as a
result.

EXERCISE
Let’s now imagine that you have a number of parameters in your
database that must be taken into account for each your user (or each
site where your application is installed): the startup screen, the
background color, the font and size of characters, etc. It’s really just
user preferences.

226 4D v11 - Self-training


PROGRAMMING
Comments

To keep them, there are several solutions (create a table, a text file, an
XML file, etc.). In our case, we will keep these preferences in a BLOB,
which is stored in a file on your disk (the read and write commands for
BLOBs are BLOB TO DOCUMENT and DOCUMENT TO BLOB).

Create and write the project method BLOB_PREFERENCES which


processes reading and writing variables in the BLOB as well as reading
and writing the BLOB on your disk.

See key on page 258.

COMMENTS
Now that you master BLOBs, you are going to be able to use them in
the different scenarios mentioned at the beginning of this chapter.
You can also refine their behavior by using other read/write commands
for variables in BLOBs. However, be sure to take byteswapping into
account (the position of the heavy byte is different between Macintosh
and Windows). For example, if you store a long integer on Windows
and recuperate it on Macintosh, the bytes order is reversed. Talk about
surprises! Think about indicating the desired order when putting away
using the “ByteOrder” parameter.

To save place and/or transfer time, you may also want to consider
compressing your BLOBs. Watch out, 4D only compresses BLOBs if
Going further their size is greater than 255 bytes. When decompressing BLOBs,
think about testing to see if the BLOB is compressed. Otherwise,
the decompression attempt will generate an error.

4D v11 - Self-training 227


PROGRAMMING

BLOBS

228 4D v11 - Self-training


37

KEY
Key

Throughout this guide, exercises were provided that were designed to


help you take what you learned in the lesson one step further. In most
cases, you probably need to make sure your work is correct and that
what you created matches what was requested.

This section gathered all of the “keys” for the exercises in this manual.
Each exercise is identified by the name of the lesson and the page
number of the exercise.

EXERCISE: “FORMS AND BUTTONS”, PAGE 26


In each button, the method displays the same alert. You should only
change the alert text to adapt it to the relevant button.

You can modify the button name by clicking twice on its title (be
careful, I didn’t say double-click!). Then, enter the title and then
validate the change by pressing Enter on the keypad.

Position the buttons: when you drag buttons, a magnetic grid (with
pointed red lines) indicates the position relative to other objects, as
well as the optimal distance compared to other objects or window
sides. This feature adapts to the Design environment.

EXERCISE: “STARTUP DISPLAY”, PAGE 34


You undoubtedly created a “Close_Message” method containing the
following line of code:
ALERT("See you later...").

Next, you called the “Close_Message” method in the “On Exit”


database method.

4D v11 - Self-training 229


Key
KEY

On the following screen, you can see the code needed to make it
happen:

To quickly access a method whose name is in another


method, select its name (for example, by double-clicking it)
TIP

then use the Ctrl+K shortcut to open it directly.

EXERCISE: “NAVIGATION AND FORM PAGES”, PAGE 49


The first button must contain the code GOTO PAGE(1), the second
GOTO PAGE(2), the third GOTO PAGE(3), etc.

EXERCISE: “TABLES AND FIELDS”, PAGE 54


You must now have three primary tables:
■ Technicians

■ Help Requests

■ Materials

230 4D v11 - Self-training


Exercise: “Entering and Modifying Records”, page 60

KEY
EXERCISE: “ENTERING AND MODIFYING RECORDS”, PAGE 60
You must obtain the following result:

EXERCISE: “RELATIONS”, PAGE 66


Your structure should look like this:

EXERCISE: “INPUT AND DELETION”, PAGE 71


You shouldn’t have anymore records in the database.

EXERCISE: “IMPORTING”, PAGE 75


The number of records that must be in your tables after import:
■ Lists: 27
■ Materials: 72
■ Software: 104
■ Help Requests: 203
■ Technicians: 7

4D v11 - Self-training 231


Key
KEY

EXERCISE: “OUTPUT FORMS”, PAGE 83


When navigating from page to page, you should see appear the
different forms that you positions and notice that the record selection
are working (recall the records set).

EXERCISE: “QUERY AND ORDER BY”, PAGE 89


To save time, type “caseof” (no spaces); the info-bubble indicates that
the word is recognized.

Then click Tab: 4D automatically writes the below text and positions
the cursor in the right place:

Start typing “Current form ”: 4D displays the name of the command(s)


that it recognizes:

Select the appropriate command and press Tab: the text writes itself.

All that’s left is to add “=1”:

232 4D v11 - Self-training


Exercise: “Quick Reports and Exports”, page 99

KEY
EXERCISE: “QUICK REPORTS AND EXPORTS”, PAGE 99
■ List of help requests per technician:

4D v11 - Self-training 233


Key
KEY

■ Number of help requests per technician:

234 4D v11 - Self-training


Exercise: “Quick Reports and Exports”, page 99

KEY
■ Number of help requests by request type and technician:

4D v11 - Self-training 235


Key
KEY

■ Number of help requests by object and technician:

236 4D v11 - Self-training


Exercise: “Query and Order by Using Formulas, Applying a Formula”, page 106

KEY
EXERCISE: “QUERY AND ORDER BY USING FORMULAS, APPLYING
A FORMULA”, PAGE 106
Exercise 1: You have two options:
■ The easiest way to start:
■ you first pass a formula that passes all first names in lowercase:

■ then you only apply uppercase to the first character:

You’ll notice the use of “string indexes” that allow addressing a


particular character in the string.

Note: On MacOS, you can use the same string index [[n]], il will
convert to ≤n≥ on its own (see the following example).
■ Slightly more complicated method, but you’ll get it in no time! Write a
single formula:
Windows:

MacOS:

If you prefer passing the set of parameters of the function “Substring”,


you can write the line of code as follows:

EXERCISE: “INHERITING FORMS”, PAGE 112


1 Display one of the Input forms.
2 Select the associated buttons and texts and cut them.
3 Display the form INHERITANCE_INPUT.
4 Paste the buttons.
5 Return to the Input form.
6 Modify the inheritance properties (table + form).
Your buttons will reappear.

On the other input forms, you simply need to delete the buttons and
set the inheritance properties.

4D v11 - Self-training 237


Key
KEY

EXERCISE: “OBJECT PROPERTIES”, PAGE 132


■ Response 1: When the On load event is checked, the method associated
to the object also executed when the form is loaded. This example
allows you to understand the importance of events as well as the “test”
solution that I propose in the following line.
■ Response 2: The fact that you limited execution of the query to only the
On mouse click event allows maintaining the On load event checked
by maintaining logical functionality.

EXERCISE: “FORMULAS AND CALCULATIONS”, PAGE 135


Query button:

238 4D v11 - Self-training


Exercise: “Variables Overview”, page 140

KEY
All button:

Reminder: To quickly display the method of an object


(button, variable, field, etc.), simply hold down the Alt key
TIP

and click the object. If the method exists, it will open; if it


doesn’t exist, 4D creates it and then opens it.

EXERCISE: “VARIABLES OVERVIEW”, PAGE 140


An initial method consists of defining the array row by row as shown:

4D v11 - Self-training 239


Key
KEY

A more optimized method consists of using a loop to fill in arrays.

240 4D v11 - Self-training


Exercise: “Basic Programming (Without Pointers)”, page 149

KEY
EXERCISE: “BASIC PROGRAMMING (WITHOUT POINTERS)”,
PAGE 149

4D v11 - Self-training 241


Key
KEY

EXERCISE: “POINTERS”, PAGE 153

(end of the method next page)

242 4D v11 - Self-training


Exercise: “Pointers”, page 153

KEY

4D v11 - Self-training 243


Key
KEY

Advanced programming: To avoid defining the related


table each time we call the method, we can use an array

TIP
pointer that will contain a pointer to the table
[technicians] on the first line, a pointer to the [services]
table on the second line, etc.

In this case, note the page number for addressing the


rowns of the array. Each array line
(◊ArrayPointerTables{$PageNum}) is a pointer that must
be de-pointed (->) :

EXERCISE: “EVENTS”, PAGE 160


You can also write it using the optimized way by using the Self pointer
which designates the object on which it is working.

Note that we de-point Self because its a pointer. We should write Self-
> when we want to address the pointed object.

244 4D v11 - Self-training


Exercise: “Arrays, Pop-ups, ListBox”, page 167

KEY
It is important to take into consideration the order of
method execution during debugging. If you put code in the
TIP

On load event of your form method AND in certain objects,


the object methods are executed and then the form method.
Object methods are executed in the order of entry (which
matches the depth order of the object plan).

EXERCISE: “ARRAYS, POP-UPS, LISTBOX”, PAGE 167


The programming is identical to the start time array.
For questions of optimization (avoid recreeating the array
each time a record is open), you can create the array just
TIP

once when the database is opened by calling the


INIT_ARRAYS method (you must create it). In this method,
you create an interprocess array <>TimeArray then copy the
content in your array when it is loaded as shown below.

4D v11 - Self-training 245


Key
KEY

EXERCISE: “4D WRITE”, PAGE 173


You have:
■ quit 4D,
■ add the 4D View plug-in in the Plugins folder,
■ restarted your database,
■ added a page to your form.

Of course, you didn’t forget to add a line to the array that manages the
tab so that you can access the third page:

Next, you added a BLOB field named Numbering_:

246 4D v11 - Self-training


Exercise: “Windows and Navigation”, page 181

KEY
Finally, you created the plug-in area in the form, set its type (4D View)
and named it “Numbering” so that you get:

To work in full screen with your plug-ins, reqest “Display in


full screen” in the File menu. To quit full screen, select the
TIP

same command, which is now called “Return to form”.

EXERCISE: “WINDOWS AND NAVIGATION”, PAGE 181


ALERT_DIALOG method:

4D v11 - Self-training 247


Key
KEY

Call the method from another method (object, project, etc.):

We left enterable texts, which allows the user to copy-paste


the message rather than to manually copy information.
TIP

EXERCISE: “4D INTERNET COMMANDS”, PAGE 186


You should add a button to the project form MESSAGE (the form that
displays alert messages):

Set the method for the button so that it takes into account message
information and sends it to an address that you’ve set:

248 4D v11 - Self-training


Exercise: “Passwords and Groups”, page 191

KEY
EXERCISE: “PASSWORDS AND GROUPS”, PAGE 191
Here is a way to program limited access (add this code to the
TABLES_NAVIGATION method):

In the sample database, I created three users as indicated in the below


figure, but I’ve only attributed two to the Settings group:

I also added the password “A” to the Designer so that 4D displays the
users window at startup. In the following sample databases, I removed
the password.

4D v11 - Self-training 249


Key
KEY

EXERCISE: “TRIGGERS”, PAGE 195


The same method must be applied when we modify a record or when
we create on because we can enter a past service for which we know
the start and end time:

So that programming is taken into account, I selected the event


engines as shown:

I also added breakpoints to follow what happens. The Duration field


was added to the Input form to make sure that everything works
properly.

250 4D v11 - Self-training


Exercise: “Current Selection”, page 205

KEY
We can optimize this trigger by creating a method called
REQUEST_MANAGEMENT to which we pass the Duration parameter:

Then, we modify the trigger as follows:

The advantage is only have a single instance of a calculation that is


coherent for the database and to be able to call this method from other
methods in the database.
To open the trigger of a table, you can use the following
shortcut in the Structure window: Alt+Double click the
TIP

table name

EXERCISE: “CURRENT SELECTION”, PAGE 205


In the sample database, I added a button that calls the statistic
calculation and allows directly executing it from the form. I edited the
STATISTICS method so that it initializes the arrays and displays for
form and I moved the rest of the code to the method object of the
button. You’re really starting to navigate methods and forms well now,
so let’s see how I set up the set. That will help you plan your solutions
and understand how others were able to organize their programming.

4D v11 - Self-training 251


Key
KEY

Note 1: The third array that you create is a “Long integer”. The “Time”
array doesn’t exist in 4D. Instead, it uses long integer arrays. Think of
indicating it in the properties of the third column of your ListBox.

Note 2: So that the average durations are calculated, durations


obviously need to be added... it’s your turn now! Don’t forget the
triggers!

Add a column in the ListBox:

Method of the button:‘

252 4D v11 - Self-training


Exercise: “Sets and Named Selections”, page 210

KEY
To combine multiple queries, simply end each (except the
last one) with the two characters ;* and to relate queries
TIP

using the conjunctions:


• & (and)
• | (or) (this is a pipe = a vertical line obtained using
AltGr+6 on Windows and Alt+Maj+L on MacOS.
• # (except)

EXERCISE: “SETS AND NAMED SELECTIONS”, PAGE 210


In the NAVIGATION_FUNCTIONS method, modify the lines of code
related to the “Add” action as follows:

... and once you decide to code “cleanly”, let’s clear the memory once
we no longer need the sets:

EXERCISE: “PROCESS”, PAGE 214


1 Create the following form:

4D v11 - Self-training 253


Key
KEY

2 Modify the form method as follows:

3 In the form properties, select the events that you use in the method.
4 Write the process creation method:

By executing this method, you should get the time counter on screen
be able to continue working on something else.

254 4D v11 - Self-training


Exercise: “Process”, page 214

KEY
The star at the end of the NEW PROCESS command allows
you to avoid recreating a process if a process of the same
TIP

name is already being executed. If you wish to start several


time counters, remove the ;* and execute the same method
several times.

You can then set up a button that allows stopping the elapsed time
calculation, add an enterable text to indicate what the elapsed time
means and, for example, when closing the counter, save the elapsed
time and the reason in a table. You’ll also have a trace of the passed
time.

For easier maneuvering, all started time counters are displayed in a


single ListBox updated using interprocess communication (using the
GET VARIABLE PROCESS or SET VARIABLE PROCESS commands).

To start your time counter, you can use a button, a menu item, an
automatic launch when a form opens, etc.

4D v11 - Self-training 255


Key
KEY

EXERCISE: “SQL”, PAGE 220


Exercise 1:

Once the two arrays are filled, you can integrate them into a form and
present them in a dialog box.

For example, you can integrate these arrays in your Navigation form
on an existing page (for example, Preferences) or create a new
“Statistics” page that gathers the set of statistics that you created.

256 4D v11 - Self-training


Exercise: “SQL”, page 220

KEY
Exercise 2: Create a form like this one:

To create it quickly, I took advantage by inheriting the


INHERIT_DIALOG form. The method for the “Execute request” button
is written as follows:

During execution, you can write your SQL request in the form and
execute it:

Once you understand these concepts, you can improve your system by
making the list of tables, the list of fields, SQL commands, etc.
available for your users.

4D v11 - Self-training 257


Key
KEY

EXERCISE: “BLOBS”, PAGE 227


The method BLOB_PREFERENCES can be written as follows:

Calling the method is done at launch, in the INITIALIZATIONS


method, as follows:

At close, like this (I used the project method named Close_Message that
is called in the On Exit database method):

258 4D v11 - Self-training


Exercise: “BLOBS”, page 227

KEY
As you probably noticed, no access path is set in the method. In this
case, 4D stores the file directly in the folder of the structure (your .4DB
database).

4D v11 - Self-training 259


Key
KEY

260 4D v11 - Self-training


CONCLUSION
Conclusion

Well, here we are at the end of our lesson plan! Even though there are
still more themes to discover, I think you’ve learned enough to get
started with your own development projects in the proper conditions.

My goal was to make you aware of the enormous potential that 4D


offers and to give you the tools to quickly take advantage.

To complement this guide, which never claimed to be exhaustive,


you’ll find considerable amounts of information both on online
forums as well as in training classes that will answer your questions.

Thanks a lot for having paid such close attention during these lessons

Here’s a small list of feature that we didn’t touch on - just to whet your
appetite!
■ Managing pictures
■ Compiling and generating applications
■ Web publishing
■ Web Services
■ XML
■ Enumerations
■ Styles
■ Help bubbles
■ Help bubbles as variables

4D v11 - Self-training 261


Conclusion
CONCLUSION

Going Further
Here are a few links and information sources that can help you to
complete your 4D training:
■ 4D Technical tips: http://www.4d.com/support/techtips.html

■ 4D official web site: http://www.4d.com

■ 4D documentation: http://www.4d.com/support/docs.html

■ 4D official technical forum: http://forums.4d.fr

262 4D v11 - Self-training

Vous aimerez peut-être aussi