Lista desplegable
Drop-down lists are form objects that allow the user to select from a list. You manage the items displayed in the drop-down list using an object, an array, a choice list, or a standard action.
En macOS, las listas desplegables también se denominan a veces "menú emergente". Ambos nombres se refieren a los mismos objetos. Como muestra el siguiente ejemplo, el aspecto de estos objetos puede variar ligeramente según la plataforma:
Tipos de listas desplegables
You can create different types of drop-down lists with different features. To define a type, select the appropriate Expression Type and Data Type values in the Property list, or use their JSON equivalent.
Tipo | Funcionalidades | Tipo de expresión | Tipos de datos | Definición JSON |
---|---|---|---|---|
Objeto | Built upon a collection | Objeto | Numeric, Text, Date, or Time | dataSourceTypeHint: object + numberFormat: <format> or textFormat: <format> or dateFormat: <format> or timeFormat: <format> |
Array | Basado en un array | Array | Numeric, Text, Date, or Time | dataSourceTypeHint: arrayNumber or arrayText or arrayDate or arrayTime |
Choice list saved as value | Built upon a choice list (standard) | Lista | Valor del elemento seleccionado | dataSourceTypeHint: text + saveAs: value |
Choice list saved as reference | Built upon a choice list. Item position is saved | Lista | Selected item reference | dataSourceTypeHint: integer + saveAs: reference |
Hierarchical choice list | Can display hierarchical contents | Lista | List reference | dataSourceTypeHint: integer |
Acción estándar | Automatically built by the action | any | any except List reference | any definition + action: <action> (+ focusable: false for actions applying to other areas) |
Handling drop-down lists
Using an object
This feature is only available in 4D projects.
An object encapsulating a collection can be used as the data source of a drop-down list. The object must contain the following properties:
Propiedad | Tipo | Descripción |
---|---|---|
values | Collection | Mandatory - Collection of scalar values. All values must be of the same type. Tipos soportados: |
index | number | Index of the currently selected item (value between 0 and collection.length-1 ). If you set -1, currentValue is displayed as a placeholder string |
currentValue | igual que Collection | Currently selected item (used as placeholder value if set by code) |
If the object contains other properties, they are ignored.
To initialize the object associated to the drop-down list, you can:
Introduzca una lista de valores por defecto en las propiedades del objeto seleccionando "<Static List>" en el tema Fuente de datos de la lista de propiedades. The default values are loaded into an object automatically.
Execute code that creates the object and its properties. For example, if "myList" is the variable associated to the drop-down list, you can write in the On Load form event:
// Form.myDrop is the datasource of the form object
Form.myDrop:=New object
Form.myDrop.values:=New collection("apples"; "nuts"; "pears"; "oranges"; "carrots")
Form.myDrop.index:=-1 //currentValue is a placeholder
Form.myDrop.currentValue:="Select a fruit"
The drop-down list is displayed with the placeholder string:
After the user selects a value:
Form.myDrop.values // ["apples","nuts","pears","oranges","carrots"]
Form.myDrop.currentValue //"oranges"
Form.myDrop.index //3
Utilizar un array
Un array es una lista de valores en memoria a la que se hace referencia por el nombre del array. Una lista desplegable puede mostrar un array como una lista de valores cuando se hace clic en ella.
To initialize the array associated to the drop-down list, you can:
Introduzca una lista de valores por defecto en las propiedades del objeto seleccionando "<Static List>" en el tema Fuente de datos de la lista de propiedades. Los valores por defecto se cargan en un array automáticamente. Puede referirse al array utilizando el nombre de la variable asociada al objeto.
Antes de mostrar el objeto, ejecute el código que asigna valores a los elementos del array. Por ejemplo:
ARRAY TEXT(aCities;6)
aCities{1}:="Philadelphia"
aCities{2}:="Pittsburg"
aCities{3}:="Grand Blanc"
aCities{4}:="Bad Axe"
aCities{5}:="Frostbite Falls"
aCities{6}:="Green Bay"
In this case, the name of the variable associated with the object in the form must be aCities
. Este código podría colocarse en el método formulario y ejecutarse cuando se ejecute el evento formulario On Load
.
- Before the object is displayed, load the values of a list into the array using the LIST TO ARRAY command. Por ejemplo:
LIST TO ARRAY("Cities";aCities)
In this case also, the name of the variable associated with the object in the form must be aCities
. Este código puede ejecutarse en lugar de las sentencias de asignación mostradas anteriormente.
Si necesita guardar la elección del usuario en un campo, deberá utilizar una sentencia de asignación que se ejecute después de aceptar el registro. El código podría ser así:
Case of
:(Form event=On Load)
LIST TO ARRAY("Cities";aCities)
If(Record number([People])<0) `nuevo registro
aCities:=3 `mostrar un valor por defecto
Else `registro existente, mostrar valor almacenado
aCities:=Find in array(aCities;City)
End if
:(Form event=On Clicked) `el usuario modifica la selección
City:=aCities{aCities} `el campo obtiene un nuevo valor
:(Form event=On Validate)
City:=aCities{aCities}
:(Form event=On Unload)
CLEAR VARIABLE(aCities)
End case
You must select each event that you test for in your Case statement. Los arrays siempre contienen un número finito de elementos. La lista de elementos es dinámica y puede ser modificada por un método. Los elementos de un array pueden modificarse, ordenarse y añadirse.
Utilizar una lista de selección
If you want to use a drop-down list to manage the values of an input area (listed field or variable), 4D lets you reference the field or variable directly as the drop-down list's data source. Esto facilita la gestión de los campos/variables listados.
For example, in the case of a "Color" field that can only contain the values "White", "Blue", "Green" or "Red", it is possible to create a list containing these values and associate it with a drop-down list that references the 4D "Color" field. 4D se encarga entonces de gestionar automáticamente la entrada y la visualización del valor actual en el formulario.
Si utiliza una lista jerárquica, sólo se muestra el primer nivel y se puede seleccionar. If you want to display hierarchical contents, you need to use a hierarchical choice list.
To associate a drop-down list with a field or variable, enter the name of the field or variable directly as the Variable or Expression field of the drop-down list in the Property List.
It is not possible to use this feature with an object or an array drop-down list. If you enter a field name in the "Variable or Expression" area, then you must use a choice list.
When the form is executed, 4D automatically manages the drop-down list during input or display: when a user chooses a value, it is saved in the field; this field value is shown in the drop-down list when the form is displayed:
Selected item value or Selected item reference
When you have associated a drop-down list with a choice list and with a field or a variable, you can set the Data Type property to Selected item value or Selected item reference. Esta opción permite optimizar el tamaño de los datos guardados.
Using a hierarchical choice list
A hierarchical drop-down list has a sublist associated with each item in the list. Here is an example of a hierarchical drop-down list:
In forms, hierarchical drop-down lists are limited to two levels.
You can assign the hierarchical choice list to the drop-down list object using the Choice List field of the Property List.
You manage hierarchical drop-down lists using the Hierarchical Lists commands of the 4D Language. All commands that support the (*; "name")
syntax can be used with hierarchical drop-down lists, e.g. List item parent
.
Utilizar una acción estándar
You can build automatically a drop-down list using a standard action. This feature is supported in the following contexts:
Use of the
gotoPage
standard action. In this case, 4D will automatically display the page of the form that corresponds to the number of the item that is selected. For example, if the user selects the 3rd item, 4D will display the third page of the current form (if it exists). At runtime, by default the drop-down list displays the page numbers (1, 2...).Use of a standard action that displays a sublist of items, for example
backgroundColor
. This feature requires that:- a styled text area (4D Write Pro area or input with multistyle property) is present in the form as the standard action target.
- the focusable property is not set to the drop-down list. At runtime the drop-down list will display an automatic list of values, e.g. background colors. You can override this automatic list by assigning in addition a choice list in which each item has been assigned a custom standard action.
This feature cannot be used with a hierarchical drop-down list.
Propiedades soportadas
Alpha Format - Bold - Bottom - Button Style - Choice List - Class - Data Type (expression type) - Data Type (list) - Date Format - Expression Type - Focusable - Font - Font Color - Font Size - Height - Help Tip - Horizontal Sizing - Italic - Left - Not rendered - Object Name - Right - Standard action - Save value - Time Format - Top - Type - Underline - Variable or Expression - Vertical Sizing - Visibility - Width