Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Un champ de variable stocke une chaîne comme valeur et une chaîne comme texte. La valeur est un ID de variable, tandis que le texte est le nom d'une variable.
Le constructeur de variables accepte un nom de variable facultatif, un validateur facultatif, un tableau facultatif de types de variables et un type par défaut facultatif.
Le nom de la variable doit être une chaîne. Il s'agit du nom de la variable initiale contenue dans le champ. Si la valeur est nulle ou indéfinie, un nom unique est généré.
Les types de variables doivent être un tableau de chaînes. Cela indique au champ les types de variables qu'il peut contenir (c'est-à-dire les types de variables à ajouter au menu déroulant). Si elle est nulle ou indéfinie, tous les types de variables seront acceptés (et ajoutés au menu déroulant).
Le type par défaut doit être une chaîne. Cette valeur sera utilisée lors de la création du modèle de variable initial du champ. Si cette valeur est définie, elle doit être incluse dans le tableau des types de variables. Si cette valeur est nulle ou indéfinie, elle est définie par défaut sur une chaîne vide, ce qui signifie que la variable initiale sera de type flexible.
Où FIELDNAME est une chaîne faisant référence à un champ de variable, et la valeur est l'ID de la variable à laquelle le champ fait référence.
Si vous utilisez ce champ dans la boîte à outils, vous pouvez également spécifier directement le nom et le type (facultatif), car aucune variable ne sera disponible pour la référence.
L'attribut name du nœud contient une chaîne faisant référence à un champ de variable.
L'attribut id du nœud contient l'ID de la variable à laquelle le champ fait référence.
L'attribut variabletype du nœud contient le type de la variable.
variabletype suit les mêmes règles que le paramètre de type par défaut du constructeur.
Le texte interne du nœud correspond au nom de la variable. La valeur du texte interne suit les mêmes règles que le paramètre de nom de variable du constructeur.
Créer un validateur de variable
La valeur d'un champ de variable est une chaîne. Par conséquent, tous les validateurs doivent accepter une chaîne et renvoyer une chaîne, null ou undefined.
Voici un exemple de validateur qui n'accepte que certaines variables prédéfinies comme options. Ces variables devront être définies avec la fonction Workspace.getVariableMap().createVariable lorsque l'espace de travail est chargé.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/08/05 (UTC).
[null,null,["Dernière mise à jour le 2025/08/05 (UTC)."],[[["\u003cp\u003eVariable fields store a variable's ID as its value and the variable's name as its text, enabling blocks to interact with variables.\u003c/p\u003e\n"],["\u003cp\u003eYou can specify the variable's name, type, and validation rules during field creation to control its behavior.\u003c/p\u003e\n"],["\u003cp\u003eVariable fields can be serialized to JSON or XML for saving and loading block configurations.\u003c/p\u003e\n"],["\u003cp\u003eValidators can be used to restrict the variables a field can accept, ensuring data integrity.\u003c/p\u003e\n"],["\u003cp\u003eVariable fields can be pre-populated with specific variable names and types within the toolbox.\u003c/p\u003e\n"]]],[],null,["# Variable fields\n\nA variable field stores a string as its value, and a string as its text. The\nvalue is an ID of a variable, while the text is the name of a variable.\n\n#### Variable field\n\n#### Variable field with editor open\n\n#### Variable field on collapsed block\n\nCreation\n--------\n\n### Untyped\n\n### JSON\n\n {\n \"type\": \"example_variable_untyped\",\n \"message0\": \"variable: %1\",\n \"args0\": [\n {\n \"type\": \"field_variable\",\n \"name\": \"FIELDNAME\",\n \"variable\": \"x\"\n }\n ]\n }\n\n### JavaScript\n\n Blockly.Blocks['example_variable_untyped'] = {\n init: function() {\n this.appendDummyInput()\n .appendField('variable:')\n .appendField(new Blockly.FieldVariable('x'), 'FIELDNAME');\n }\n };\n\n### Typed\n\n### JSON\n\n {\n \"type\": \"example_variable_typed\",\n \"message0\": \"variable: %1\",\n \"args0\": [\n {\n \"type\": \"field_variable\",\n \"name\": \"FIELDNAME\",\n \"variable\": \"x\",\n \"variableTypes\": [\"Number\", \"String\"],\n \"defaultType\": \"Number\"\n }\n ]\n }\n\n### JavaScript\n\n Blockly.Blocks['example_variable_typed'] = {\n init: function() {\n this.appendDummyInput()\n .appendField('variable:')\n .appendField(new Blockly.FieldVariable(\n 'X',\n null,\n ['Number', 'String'],\n 'Number'\n ), 'FIELDNAME');\n }\n };\n\nThe variable constructor takes in an optional variable name, an optional\n[validator](#creating_a_variable_validator), an optional array of variable\ntypes, and an optional default type.\n\n- The **variable name** should be a string. This will be the name of the initial variable the field holds. If it is null or undefined a unique name will be generated.\n- The **variable types** should be an array of strings. This tells the field what types of variables the field can hold (i.e. what types of variables to add to the dropdown). If it is null or undefined, all variable types will be accepted (and added to the dropdown).\n- The **default type** should be a string. This will be used when creating the field's initial variable model. If this is defined, its should be included in the variable types array. If it is null or undefined this value defaults to an empty string, meaning the initial variable will be flexibly typed.\n\n→ For more information on strict typing, see\n[Type Checks](/blockly/guides/create-custom-blocks/type-checks).\n\nSerialization\n-------------\n\n### JSON\n\nThe JSON for a variable field looks like so: \n\n {\n \"fields\": {\n \"FIELDNAME\": {\n \"id\": \"QJD^+@[RVIwbLSZoDb:V\"\n }\n }\n }\n\nWhere `FIELDNAME` is a string referencing a variable field, and\nthe value is the ID of the variable the field references.\n\nIf you are using this field in the toolbox, you can also specify the name\nand (optional) type directly, since there will be no variable available to\nreference. \n\n {\n \"fields\": {\n \"FIELDNAME\": {\n \"name\": \"my_variable\",\n \"type\": \"string\"\n }\n }\n }\n\n### XML\n\nThe XML for a variable field looks like so: \n\n \u003cfield name=\"VARIABLE\" id=\"QJD^+@[RVIwbLSZoDb:V\" variabletype=\"\"\u003ename\u003c/field\u003e\n\n- The node's `name` attribute contains a string referencing a variable field.\n- The node's `id` attribute contains the ID of the variable the field references.\n- The node's `variabletype` attribute contains the type of the variable. The `variabletype` follows the same rules as the constructor's default type parameter.\n- The node's inner text is the name of the variable. The inner text value follows the same rules as the constructor's variable name parameter.\n\nCreating a variable validator\n-----------------------------\n\n| **Note:** For information on validators in general see [Validators](/blockly/guides/create-custom-blocks/fields/validators).\n\nA variable field's value is a string, so any validators must accept a string and\nreturn a string, `null`, or `undefined`.\n\nHere's an example of a validator that only accepts some predefined variables as\noptions. These variables would need to be defined with the\n[`Workspace.getVariableMap().createVariable`](/blockly/reference/js/blockly.ivariablemap_interface.createvariable_1_methodsignature)\nfunction when the workspace is loaded. \n\n function(newValue) {\n var validIds = ['Worf', 'Riker', 'Picard'];\n if (validIds.indexOf(newValue) == -1) {\n return null;\n }\n return newValue;\n }"]]