SFDocuments. Service Form

Le service Form fournit des méthodes et des propriétés pour gérer les formulaires dans les documents LibreOffice. Ce service prend en charge les formulaires dans les documents Base, Calc et Writer et permet de :

tip

Le service SFDocuments.Form est disponible à partir de LibreOffice 7.2.


Les formulaires sont généralement utilisés dans les documents LibreOffice pour créer des interfaces utilisateur connectées à des bases de données relationnelles. Par conséquent, le service Form fournit un accès rapide à la base de données liée via le service SFDatabases.Database.

tip

Le service SFDocuments.Form est étroitement lié au service SFDocuments.FormControl.


Définitions

FormDocument

Les formulaires sont généralement créés dans les documents Base, mais ils peuvent également être ajoutés aux documents Writer et Calc.

Dans Base, chaque formulaire que vous créez à l'aide de la fonctionnalité Insérer - Formulaire ou via l'Assistant de formulaire est en fait un FormDocument qui peut être géré avec le service Form. Les documents de base peuvent contenir un nombre illimité de documents de formulaire.

Ci-dessous, un exemple montrant la hiérarchie de tous les éléments impliqués dans l'accès aux formulaires et sous-formulaires dans un document Base. Supposons que vous ayez un fichier Base nommé Employees.odb et qu'à l'intérieur vous ayez créé un document de formulaire pour ajouter de nouveaux employés à la base de données. Le document de formulaire contient un formulaire principal nommé EmployeeData qui donne accès à une table. Il existe également un sous-formulaire WorksAtPlant qui permet d'associer le nouvel employé à l'une des usines de l'entreprise.


    Employees.odb (document Base)
     |
     |-- AddEmployee (FormDocument)
          |
          |-- EmployeeData (formulaire principal)
               |
               |-- WorksAtPlant (SubForm)
  
note

Un FormDocument peut être considéré comme un ensemble de formulaires permettant d'accéder à des ensembles de données tels que des tables de base de données et des requêtes à partir de documents LibreOffice. Les noms des formulaires et des sous-formulaires à l'intérieur d'un FormDocument sont accessibles à l'aide du Navigateur de formulaires.


Formulaires et sous-formulaires

Un document de formulaire est composé d'un ou plusieurs formulaires qui, à leur tour, peuvent également contenir n'importe quel nombre de sous-formulaires. Un formulaire est un ensemble abstrait de contrôles liés à une source de données spécifiée, qui peut être une table de base de données, une requête ou une instruction SQL SELECT.

Dans les documents Calc et Writer, chaque formulaire peut être lié à des ensembles de données situés dans différentes bases de données. En revanche, dans les documents Base, la base de données contenue dans le document est commune à tous les formulaires.

tip

Pour invoquer le service SFDocuments.Form reportez-vous aux méthodes Forms(), FormDocuments() et OpenFormDocument() du service SFDocuments.Document


Invocation du service

Avant d'utiliser le service Form, la bibliothèque ScriptForge doit être chargée ou importée :

note

• Les macros Basic nécessitent de charger la bibliothèque ScriptForge à l'aide de l'instruction suivante :
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Les scripts Python nécessitent un import depuis le module scriptforge :
from scriptforge import CreateScriptService


Dans les documents Writer

L'extrait de code ci-dessous montre comment accéder au formulaire nommé Form1 qui se trouve dans un fichier Writer :


      Dim oDoc As Object, myForm As Object, ui as Object
      Set ui = CreateScriptService("UI")
      Set oDoc = ui.OpenDocument("/home/user/Documents/MyForm.odt")
      Set myForm = oDoc.Forms("Form1")
   
En Python

     from scriptforge import CreateScriptService
     ui = CreateScriptService('UI') 
     doc = ui.OpenDocument('/home/user/Documents/MyForm.odt')
     my_form = doc.Forms('Form1')
   

Les formulaires sont accessibles par leurs noms ou par leurs indices, comme indiqué ci-dessous :


     Set myForm = oDoc.Forms(0)
   
En Python

     my_form = doc.Forms(0)
   
warning

Si vous essayez d'accéder à un FormDocument qui est actuellement ouvert en Mode Ébauche une exception sera déclenchée.


Dans les documents Calc

Un formulaire dans un fichier Calc doit avoir un nom unique dans sa feuille. Par conséquent, la méthode Forms nécessite deux arguments, le premier indiquant le nom de la feuille et le second spécifiant le nom du formulaire.


      Dim oDoc As Object, myForm As Object, ui as Object
      Set ui = CreateScriptService("UI")
      Set oDoc = ui.OpenDocument("/home/user/Documents/MyForms.ods")
      Set myForm = oDoc.Forms("Sheet1", "Form1")
   

Ceci est réalisé de manière identique en utilisant Python :


     ui = CreateScriptService('UI')
     doc = ui.OpenDocument('/home/user/Documents/MyForms.ods')
     my_form = doc.Forms('Sheet1', 'Form1')
   

Dans les documents Base

Un FormDocument à l'intérieur d'un document Base est accessible par son nom. L'exemple suivant ouvre le document de formulaire nommé thisFormDocument et accède au formulaire MainForm :


      Dim oDb As Object, myForm As Object
      Set oDb = CreateScriptService("SFDocuments.Document", ThisDatabaseDocument)
      ' L'instruction ci-dessous n'est nécessaire que si le formulaire n'a pas encore été ouvert
      oDb.OpenFormDocument("thisFormDocument")
      Set myForm = oDoc.Forms("thisFormDocument", "MainForm")
      ' Ou, alternativement, pour accéder au formulaire par son index...
      Set myForm = oDb.Forms("thisFormDocument", 0)
   
note

To perform any action on a form using the Form service, the FormDocument must have been opened either manually by the user or programmatically in a user script. The latter can be done by calling the OpenFormDocument method of the Base service.


To access a given subform of a form use the SubForms method. Note that in the example below mySubForm is a new instance of the Form service.


     Dim mySubForm As Object
     Set mySubForm = myForm.SubForms("mySubForm")
   

Previous examples translate in Python as:


     db = CreateScriptService('SFDocuments.Document', XSCRIPTCONTEXT.getDocument())
     #  The statement below is necessary only if the form hasn't been opened yet
     form_doc = db.OpenFormDocument('thisFormDocument')
     form = form_doc.Forms('thisFormDocument', 'MainForm')
     #  Or, alternatively, to access the form by its index ...
     form = form_doc.Forms('thisFormDocument', 0)
     sub_form = form.SubForms('mySubForm')
   

In Form events

To invoke the Form service when a form event takes place:


      Sub OnEvent(ByRef poEvent As Object)
          Dim myForm As Object
          Set myForm = CreateScriptService("SFDocuments.FormEvent", poEvent)
          '(...)
      End sub
   
En Python

     def OnEvent(event: uno):
         form = CreateScriptService('SFDocuments.FormEvent', event)
         pass
   
note

The FormEvent service is used exclusively to create instances of the SFDocuments.Form and SFDocuments.FormControl services when a form or control event takes place.


It is recommended to free resources after use of the Form service.


     myForm.Dispose() ' Basic
   

     form.Dispose()  # Python
   

This operation is done implicitly when a form document is closed with the CloseFormDocument() method described below.

Properties

Name

Readonly

Type

Description

AllowDeletes

No

Boolean

Specifies if the form allows to delete records.

AllowInserts

No

Boolean

Specifies if the form allows to add records.

AllowUpdates

No

Boolean

Specifies if the form allows to update records.

BaseForm

Yes

String

Specifies the hierarchical name of the Base Form containing the actual form.

Bookmark

No

Variant

Specifies uniquely the current record of the form's underlying table, query or SQL statement.

CurrentRecord

No

Long

Identifies the current record in the dataset being viewed on a form. If the row number is positive, the cursor moves to the given row number with respect to the beginning of the result set. Row count starts at 1. If the given row number is negative, the cursor moves to an absolute row position with respect to the end of the result set. Row -1 refers to the last row in the result set.

Filter

No

String

Specifies a subset of records to be displayed as a SQL WHERE-clause without the WHERE keyword.

LinkChildFields

Yes

String

Specifies how records in a child subform are linked to records in its parent form.

LinkParentFields

Yes

String

Specifies how records in a child subform are linked to records in its parent form.

Name

Yes

String

The name of the current form.

OrderBy

No

String

Specifies in which order the records should be displayed as a SQL ORDER BY clause without the ORDER BY keywords.

Parent

Oui

Object

The parent of the current form. It can be either a SFDocuments.Form or a SFDocuments.Document object.

RecordSource

No

String

Specifies the source of the data, as a table name, a query name or a SQL statement.

XForm

Yes

UNO
object

The UNO object representing interactions with the form. Refer to XForm and DataForm in the API documentation for detailed information.


Event properties

The properties below return or set URI strings that define the script triggered by the event.

Name

ReadOnly

Basic IDE Description

OnApproveCursorMove

No

Before record change

OnApproveParameter

No

Fill parameters

OnApproveReset

No

Prior to reset

OnApproveRowChange

No

Before record action

OnApproveSubmit

No

Before submitting

OnConfirmDelete

No

Confirm deletion

OnCursorMoved

No

After record change

OnErrorOccurred

No

Error occurred

OnLoaded

No

When loading

OnReloaded

No

When reloading

OnReloading

No

Before reloading

OnResetted

No

After resetting

OnRowChanged

No

After record action

OnUnloaded

No

When unloading

OnUnloading

No

Before unloading


tip

To learn more about URI strings, refer to the Scripting Framework URI Specification.


List of methods in the Form service

Activate
CloseFormDocument
Controls
GetDatabase

MoveFirst
MoveLast
MoveNext
MoveNew

MovePrevious
Requery
SubForms


Activate

Sets the focus on the current Form instance. Returns True if focusing was successful.

The behavior of the Activate method depends on the type of document where the form is located:

Syntaxe :

svc.Activate(): bool

Exemple :

The following example assumes you want to activate the form named FormA located in Sheet1 of the currently open Calc file. It first gets access to the document using the Document service and ThisComponent and then activates the form.


     'Gets hold of the form that will be activated
     Dim oDoc as Object, myForm as Object
     Set oDoc = CreateScriptService("Document", ThisComponent)
     

Set myForm = oDoc.Forms("Sheet1", "FormA")

'Activates the form myForm.Activate()
En Python

     doc = CreateScriptService('Document', XSCRIPTCONTEXT.getDocument())
     form = doc.Forms('Sheet1', 'FormA')
     form.Activate()
   
note

ThisComponent applies to Calc and Writer documents. For Base documents use ThisDataBaseDocument.


CloseFormDocument

Closes the form document containing the actual Form instance. The Form instance is disposed.

Syntaxe :

svc.CloseFormDocument(): bool

Exemple :


      myForm.CloseFormDocument() ' Basic
   
En Python

      form.CloseFormDocument()  # Python
   
note

This method only closes form documents located in Base documents. If the form is stored in a Writer or Calc document, calling CloseFormDocument will have no effect.


Controls

The value returned by the Controls method depends on the arguments provided:

Syntaxe :

svc.Controls(opt controlname: str): any

Paramètres :

controlname : A valid control name as a case-sensitive string. If absent, the list of control names is returned as a zero-based array.

Exemple :


      Dim myForm As Object, myList As Variant, myControl As Object
      Set myForm = myDoc.Forms("myForm")
      myList = myform.Controls()
      Set myControl = myform.Controls("myTextBox") ' SFDocuments.FormControl
   
En Python

      form = doc.Forms('myForm')
      form_names = form.Controls()
      form_control = form.Controls('myTextBox')  # SFDocuments.FormControl
   

GetDatabase

Return a SFDatabases.Database instance giving access to the execution of SQL commands on the database the current form is connected to and/or that is stored in the current Base document.

Each form has its own database connection, except in Base documents where they all share the same connection.

Syntaxe :

svc.GetDatabase(opt user: str, opt password: str): svc

Paramètres :

user, password: The login optional parameters (Default = "").

Exemple :


      Dim myDb As Object ' SFDatabases.Database
      Set myDb = oForm.GetDatabase()
   
En Python

      db = form.GetDatabase()  # SFDatabases.Database
   

MoveFirst

The form cursor is positioned on the first record. Returns True if successful.

Syntaxe :

svc.MoveFirst(): bool

Exemple :


      myForm.MoveFirst() ' Basic
   
En Python

      form.MoveFirst()  # Python
   

MoveLast

The form cursor is positioned on the last record. Returns True if successful.

Syntaxe :

svc.MoveLast(): bool

Exemple :


      myForm.MoveLast() ' Basic
   
En Python

      form.MoveLast()  # Python
   

MoveNew

The form cursor is positioned on the new record area. Returns True if successful.

Syntaxe :

svc.MoveNew(): bool

Exemple :


      myForm.MoveNew() ' Basic
   
En Python

      form.MoveNew()  # Python
   

MoveNext

The form cursor is positioned on the next record. Returns True if successful.

Syntaxe :

svc.MoveNext(opt offset: int): bool

Paramètres :

offset: The number of records to go forward (Default = 1).

Exemple :


      myForm.MoveNext() ' Basic
   
En Python

      form.MoveNext()  # Python
   

MovePrevious

The form cursor is positioned on the previous record. Returns True if successful.

Syntaxe :

svc.MovePrevious(opt offset: int): bool

Paramètres :

offset: The number of records to go backwards (Default = 1).

Exemple :


      myForm.MovePrevious() ' Basic
   

      form.MovePrevious()  # Python
   

Requery

Reloads the current data from the database and refreshes the form. The cursor is positioned on the first record. Returns True if successful.

Syntaxe :

svc.Requery(): bool

Exemple :


      myForm.Requery() ' Basic
   
En Python

      form.Requery()  # Python
   

Subforms

The value returned by the Subforms method depends on the arguments provided:

Syntaxe :

svc.Subforms(): str[0..*]

svc.Subforms(subform: str): svc

svc.Subforms(subform: int): svc

Paramètres :

subform: A subform stored in the current Form class instance given by its name or index.

When this argument is absent, the method returns a list of available subforms as a zero-based array. If the form has a single subform, you can set subform = 0 to get access to it.

Exemple :


      Dim myForm As Object, myList As Variant, mySubform As Object
      myList = myform.Subforms()
      Set mySubform = myForm.Subforms("mySubform") ' SFDocuments.Form
   
En Python

      subform_names = form.Subforms()
     subform = form.Subforms('mySubform')  # SFDocuments.Form
   
warning

Toutes les routines ou identifiants de base ScriptForge qui sont préfixés par un caractère de soulignement "_" sont réservés à un usage interne. Ils ne sont pas destinés à être utilisés dans des macros de base ou des scripts Python.