AI-generated Key Takeaways
-
To extend an existing Blockly field, subclass a built-in field like
FieldTextInput
orFieldColour
and modify its editor, on-block display, or displayed text. -
For custom fields with unique behaviors, subclass the base
Field
class instead of extending an existing field. -
Common field extensions involve customizing text input (
FieldTextInput
), numbers (FieldNumber
), or dropdowns (FieldDropdown
) to meet specific needs. -
When subclassing, ensure your constructor matches the super-constructor's signature and register the field with
Blockly.fieldRegistry.register
. -
Implement the
fromJson
method in your custom field class to enable compatibility with the Blockly JSON format for serialization and deserialization.
In order to extend an existing field you must subclass a built in field (e.g
FieldTextInput
, FieldColour
) and then modify part of it to fit your needs.
Some parts of a field you can modify are:
- Its editor.
- Its on-block display.
- The text it displays.
If you want to create a
custom field
that does not need behaviour from any built-in field you should subclass Field
.
Common extensions
Most custom fields extend one of these three types:
- Text Input: If you want your users to type into your field, you should extend
FieldTextInput
. - Number: If you want to store a number, you should extend
FieldNumber
. - Dropdown: If you want to create a dropdown, but you want it to store a different model
than the default string or image model, you should extend
FieldDropdown
.- Caution: Before extending
FieldDropdown
, check that the dropdown field's customization options cannot fulfill your needs.
- Caution: Before extending
Under certain circumstances you may wish to extend a different field type. For
example FieldLabelSerializable
extends FieldLabel
.
Subclassing
import * as Blockly from 'blockly';
export class MyCustomTextField extends Blockly.FieldTextInput {
constructor(value, validator, config) {
super(value, validator, config);
}
}
The constructor for a field's subclass looks very similar to the constructor for a custom field. The signature of the sub-constructor should generally match the signature of the super-constructor.
JSON and registration
You should also register the field once:
Blockly.fieldRegistry.register('my_custom_text_field', MyCustomTextField);
and provide an implementation of fromJson
in the class so that it works with
the JSON format:
static fromJson(options) {
const value = Blockly.utils.parsing.replaceMessageReferences(options.value);
return new MyCustomTextField(value);
}
For more information about registering a field see the JSON and registration section in Creating a Custom Field.