How do I get the value in the `onchange` event of a block block?
I am making a custom block for Blockly and have to validate the input. In an event, onchange
I want to alert the user if they enter an invalid value for input.
Here is my block:
Blockly.Blocks['motor'] = {
init: function() {
this.setHelpUrl('http://www.example.com/');
this.setColour(65);
this.appendDummyInput()
.appendField("motor( ");
this.appendValueInput("port_number")
.setCheck("Number");
this.appendDummyInput()
.appendField(");");
this.setInputsInline(true);
this.setPreviousStatement(true);
this.setNextStatement(true);
this.setTooltip('');
},
onchange: function(ev) {
if (this.getFieldValue('port_number') > '3') {
this.setWarningText('Port must be 0 - 3.');
} else {
this.setWarningText(null);
}
}
};
On the Blocking Developers page , it has a basic example of getting an input value. However, I keep returning undefined
every time it fires onchange
.
How can I handle the validation for these inputs? I don't want to create a dropdown for input because I need to be able to input variables, int blocks, etc.
source to share
Not sure if this is the best way to handle this, but it works for me. I am just accessing the input value with a method valueToCode
. Then I can check the input value.
Note. The handler context
onchange
is a block, so passthis
as the first argumentBlockly.C.valueToCode
will get the value from the correct block.
Blockly.Blocks['motor'] = {
init: function() {
this.setHelpUrl('http://www.example.com/');
this.setColour(65);
this.appendDummyInput()
.appendField("motor( ");
this.appendValueInput("port_number")
.setCheck("Number");
this.appendDummyInput()
.appendField(");");
this.setInputsInline(true);
this.setPreviousStatement(true);
this.setNextStatement(true);
this.setTooltip('');
},
onchange: function(ev) {
var port_number = Blockly.C.valueToCode(this, 'port_number', Blockly.C.ORDER_ATOMIC);
var valid = VALIDATE.motor_port_number(port_number);
if (!valid)
alert("WARNING: The value for the motor port must be 0, 1, 2 or 3.");
}
}
};
source to share
Try the following:
this.getInputTargetBlock('port_number').toString()
Or:
this.getInputTargetBlock('port_number').getFieldValue(/*field_name*/)
Example:
Blockly.Blocks['stop_actions'] = {
init: function() {
var actions_descriptors = [
['HOLD', 'hold'],
['COAST', 'coast']
];
this.appendDummyInput()
.appendField(new Blockly.FieldDropdown(actions_descriptors), 'action')
.setAlign(Blockly.ALIGN_RIGHT);
this.setOutput(true, 'String');
this.setColour(60);
this.setTooltip('Select the stop action');
}
};
Blockly.Blocks['motor'] = {
init: function() {
this.appendValueInput('arg_stop_action')
.appendField('Stop action')
.setAlign(Blockly.ALIGN_RIGHT);
},
onchange: function(e) {
this.getInputTargetBlock('arg_stop_action').getFieldValue('action')
}
};
source to share