How to pass dropdown value to parent block and display the corresponding output?

273 views
Skip to first unread message

Himandri Sharma

unread,
May 11, 2021, 5:06:39 AM5/11/21
to Blockly
Hi,
I am trying to use a block which will have statement input and then another block which is just a dropdown. I have defined all the corresponding values in the dropdown such that if user selects any one value they'll get the corresponding output but I need to pass the corresponding value to my parent block and then display the answer. 

The dropdown block :

Blockly.Blocks["append_question"] = {
init: function() {
this.appendDummyInput().appendField('Ask me a question:')
.appendField(new Blockly.FieldDropdown([
['What is the date today?', today],
['What is the time now?', time],
['How are you?', 'I am good. How are you?'],
['What is JavaScript', 'JavaScript is high-level, often just-in-time compiled, and multi-paradigm. It has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions.'],
['What is your name?', 'I am a bot created by Himandri Sharma using blockly.']
]), 'FIELDNAME');
this.setPreviousStatement(true, 'mytype');
this.setColour(230);
}
};
The parent block :
Blockly.Blocks["Question_list"] = {
init: function(block) {
this.appendDummyInput().appendField('Bot');
this.appendStatementInput('FIELDNAME')
.setCheck(['mytype']);
}
};

Screenshot from 2021-05-11 14-35-15.png
Can anyone please help!

Jason Schanker

unread,
May 11, 2021, 4:05:45 PM5/11/21
to Blockly
Hi Himandri,

If parentBlock refers to a "Bot" block present in the workspace:

const parentBlock = Blockly.getMainWorkspace().getAllBlocks().find(block => block.type === "Question_list");

Then you can get its child block attached to the (statement) input that you named FIELDNAME as follows:

const childBlock = parentBlock.getInputTargetBlock("FIELDNAME");

You can then get the field value of the field named FIELDNAME of the child block (i.e., the question text) as follows:

const question = childBlock && childBlock.getFieldValue("FIELDNAME");

(childBlock && is unnecessary if you know parentBlock has an attached child block.)  A couple of notes: Since inputs are different than fields, it may be clearer to use this.appendStatementInput('VALUE') for the parent block in which case you'd change parentBlock.getInputTargetBlock("FIELDNAME") to parentBlock.getInputTargetBlock("VALUE").  Also, the dropdown values (which you use as the answers to the questions) were not intended to be used for human-readable text (e.g., they won't get translated if you support multiple languages).  See: https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/dropdown

Best,
Jason

Reply all
Reply to author
Forward
Message has been deleted
0 new messages