Contenido

# Servicio SFDocuments.Form

The Form service provides methods and properties to manage forms in LibreOffice documents. This service supports forms in Base, Calc and Writer documents and allows to:

- Open and activate forms.

- Navigate through records shown by the form.

- Get access to the controls inside the form.

- Get access to subforms of a parent form.

The SFDocuments.Form service is available from LibreOffice 7.2 onwards.

Forms are usually used in LibreOffice documents to create user interfaces connected to relational databases. Hence, the Form service provides quick access to the linked database through the SFDatabases.Database service.

The SFDocuments.Form service is closely related to the SFDocuments.FormControl service.

## Definiciones

### FormDocument

Los formularios se suelen crear dentro de documentos de Base, pero es posible añadirlos también a documentos de Writer y de Calc.

In Base, each form you create using the Insert - Form functionality or through the Form Wizard is actually a FormDocument that can be handled with the Form service. Base documents can contain an unlimited number of form documents.

Below is an example showing the hierarchy of all the elements involved in accessing forms and subforms in a Base document. Suppose you have a Base file named Employees.odb and inside it you created a form document to add new employees to the database. The form document contains a main form named EmployeeData that gives access to a table. There is also a subform WorksAtPlant that allows you to associate the new employee to one of the plants of the company.

        Employees.odb (Base document)
         |
         |-- AddEmployee (FormDocument)
              |
              |-- EmployeeData (Main Form)
                   |
                   |-- WorksAtPlant (SubForm)

A FormDocument can be seen as a set of forms that provide access to datasets such as database tables and queries from within LibreOffice documents. The names of forms and subforms inside a FormDocument can be accessed using the Form Navigator.

### Formularios y subformularios

A form document is composed of one or more forms which, in turn, may also contain any number of subforms. A Form is an abstract set of controls that are linked to a specified data source, which can be a database table, a query or a SQL SELECT statement.

In Calc and Writer documents, each form can be linked to datasets located in different databases. On the other hand, in Base documents the database contained in the document is common to all forms.

To invoke the SFDocuments.Form service refer to the methods Forms(), FormDocuments() and OpenFormDocument() of the SFDocuments.Document service

## Invocación del servicio

Antes de utilizar el servicio Form, es necesario cargar o importar la biblioteca ScriptForge:

• Para cargar la biblioteca ScriptForge que necesitan las macros de Basic se debe usar la siguiente declaración:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
• Los scripts de Python necesitan importar el módulo scriptforge:
from scriptforge import CreateScriptService

### En documentos de Writer

The code snippet below shows how to access the form named Form1 that is inside a Writer file:

          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')

Forms can be accessed by their names or by their indices, as shown below:

         Set myForm = oDoc.Forms(0)

##### En Python

         my_form = doc.Forms(0)

If you try to access a FormDocument that is currently opened in Design Mode an exception will be raised.

### En documentos de Calc

A form in a Calc file must have a unique name inside its sheet. Hence, the Forms method requires two arguments, the first indicating the sheet name and the second specifying the form name.

          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")

Esto se logra de idéntica manera utilizando Python:

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

### En documentos de Base

Se accede a un FormDocument dentro de un documento de Base mediante su nombre. El ejemplo siguiente abre el documento de formulario denominado thisFormDocument y accede al formulario MainForm:

          Dim oDb As Object, myForm As Object
          Set oDb = CreateScriptService("SFDocuments.Document", ThisDatabaseDocument)
          ' The statement below is necessary only if the form hasn't been opened yet
          oDb.OpenFormDocument("thisFormDocument")
          Set myForm = oDoc.Forms("thisFormDocument", "MainForm")
          ' Or, alternatively, to access the form by its index ...
          Set myForm = oDb.Forms("thisFormDocument", 0)

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")

Los ejemplos anteriores se traducen en Python como:

         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')
         # O, alternativamente, para acceder al formulario por su índice ...
         form = form_doc.Forms('thisFormDocument', 0)
         sub_form = form.SubForms('mySubForm')

### En eventos de formulario

Para invocar el servicio Form cuando acaece un evento de formulario:

          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

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.

Es recomendable liberar recursos después de utilizar el servicio Form.

         myForm.Dispose() ' Basic

         form.Dispose()  # Python

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

## Propiedades

Nombre | De solo lectura | Tipo | Descripción
--- | --- | --- | ---
AllowDeletes | No | Boolean | Especifica si el formulario permite eliminar registros.
AllowInserts | No | Boolean | Especifica si el formulario permite añadir registros.
AllowUpdates | No | Boolean | Especifica si el formulario permite actualizar registros.
BaseForm | Sí | 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 | Identifica el registro actual en el conjunto de datos que se está viendo en un formulario. Si el número de fila es positivo, el cursor se mueve al número de fila dado con respecto al comienzo del conjunto de resultados. El recuento de filas comienza en 1. Si el número de fila dado es negativo, el cursor se mueve a una posición de fila absoluta con respecto al final del conjunto de resultados. La fila -1 se refiere a la última fila del conjunto de resultados.
Filter | No | String | Specifies a subset of records to be displayed as a SQL WHERE-clause without the WHERE keyword.
LinkChildFields | Sí | String | Specifies how records in a child subform are linked to records in its parent form.
LinkParentFields | Sí | String | Specifies how records in a child subform are linked to records in its parent form.
Name | Sí | String | El nombre del formulario actual.
OrderBy | No | String | Specifies in which order the records should be displayed as a SQL ORDER BY clause without the ORDER BY keywords.
Parent | Sí | Object | The parent of the current form. It can be either a SFDocuments.Form or a SFDocuments.Document object.
RecordSource | No | String | Especifica el origen de los datos, como un nombre de tabla, un nombre de consulta o una instrucción SQL.
XForm | Sí | Objeto de UNO | The UNO object representing interactions with the form. Refer to XForm and DataForm in the API documentation for detailed information.

## Propiedades del evento

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

Nombre | De solo lectura | Descripción en el EDI de BASIC
--- | --- | ---
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 | Confirmar la eliminación
OnCursorMoved | No | After record change
OnErrorOccurred | No | Error occurred
OnLoaded | No | Al cargar
OnReloaded | No | Al recargar
OnReloading | No | Antes de recargar
OnResetted | No | Después de restablecer
OnRowChanged | No | After record action
OnUnloaded | No | When unloading
OnUnloading | No | Before unloading

Para conocer más sobre las cadenas de URI, consulte la especificación de URI del marco de programación de secuencias de órdenes (en inglés).

Lista de métodos en el servicio Form
Activate Controls GetDatabase MoveFirst | MoveLast MoveNext MoveNew | MovePrevious Requery SubForms

## Activate

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

El comportamiento del método Activate depende del tipo de documento donde se encuentre el formulario:

- In Writer documents: Sets the focus on that document.

- In Calc documents: Sets the focus on the sheet to which the form belongs.

- In Base documents: Sets the focus on the FormDocument the Form refers to.

### Sintaxis:

svc.Activate(): bool

### Ejemplo:

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")
         'Activa el formulario
         myForm.Activate()

##### En Python

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

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

## CloseFormDocument

This method is deprecated, use ScriptForge.FormDocument.CloseDocument method instead.

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

### Sintaxis:

svc.CloseFormDocument(): bool

### Ejemplo:

          myForm.CloseFormDocument() ' Basic

##### En Python

          form.CloseFormDocument()  # Python

## Controls

El valor que devuelve el método Controls depende de los argumentos que se le proporcionen:

- Si se llama al método sin ningún argumento, este devuelve la lista de los controles contenidos en el formulario. Considere que la lista devuelta no incluye los controles de los subformularios.

- If the optional ControlName argument is provided, the method returns a FormControl class instance referring to the specified control.

### Sintaxis:

svc.Controls(opt controlname: str): any

### Parámetros:

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

### Ejemplo:

          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.

### Sintaxis:

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

### Parámetros:

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

### Ejemplo:

          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.

### Sintaxis:

svc.MoveFirst(): bool

### Ejemplo:

          myForm.MoveFirst() ' Basic

##### En Python

          form.MoveFirst()  # Python

## MoveLast

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

### Sintaxis:

svc.MoveLast(): bool

### Ejemplo:

          myForm.MoveLast() ' Basic

##### En Python

          form.MoveLast()  # Python

## MoveNew

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

### Sintaxis:

svc.MoveNew(): bool

### Ejemplo:

          myForm.MoveNew() ' Basic

##### En Python

          form.MoveNew()  # Python

## MoveNext

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

### Sintaxis:

svc.MoveNext(opt offset: int): bool

### Parámetros:

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

### Ejemplo:

          myForm.MoveNext() ' Basic

##### En Python

          form.MoveNext()  # Python

## MovePrevious

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

### Sintaxis:

svc.MovePrevious(opt offset: int): bool

### Parámetros:

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

### Ejemplo:

          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.

### Sintaxis:

svc.Requery(): bool

### Ejemplo:

          myForm.Requery() ' Basic

##### En Python

          form.Requery()  # Python

## Subforms

El valor que devuelve el método Subforms depende de los argumentos proporcionados:

- Si el método se llama sin argumentos, se devuelve la lista de subformularios contenidos en el formulario u ocurrencia del subformulario actual.

- If the optional subform argument is provided, the method returns a new SFDocuments.Form instance based on the specified form/subform name or index.

### Sintaxis:

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

svc.Subforms(subform: str): svc

svc.Subforms(subform: int): svc

### Parámetros:

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.

### Ejemplo:

          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

Todas las rutinas o identificadores BASIC de ScriptForge precedidas por guion bajo «_» están reservadas para uso interno. No deben utilizarse en macros BASIC o secuencias Python.

Temas relacionados

Servicio SFDatabases.Database

Servicio SFDocuments.Document

Servicio ScriptForge.UI

¡Necesitamos su ayuda!