Set block id

284 views
Skip to first unread message

Computer Scratch

unread,
Dec 16, 2022, 12:23:01 AM12/16/22
to Blockly
Hello,
I want to set a particular block with some Id.
I have tried this,
 workspace.setBlockById(''Id, 'blockName').

And then workspace.getBlockById, now it is not returning me the block with the Id I have set. But the Id of blockly is present in it.

Please help, I want to set a block Id and get that block using the Id I created.

Beka Westberg

unread,
Dec 17, 2022, 12:09:48 PM12/17/22
to blo...@googlegroups.com
Hello!

Block IDs are meant to be constant (meaning they aren't changed after the block is created). You can set the ID when you instantiate the block via JSON:

```
{
  'type': 'blockName',
  'id': 'blockID',
}
```

Via XML:
```
<block type="blockName" id="blockId"></block>
```

Or when you instantiate a block programmatically:
```
workspace.newBlock('blockName', 'blockId');
```

I hope that helps! If you have any further questions please reply!
--Beka

--
You received this message because you are subscribed to the Google Groups "Blockly" group.
To unsubscribe from this group and stop receiving emails from it, send an email to blockly+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/blockly/ba98fee4-fe11-4b1a-9f30-2312acc957f3n%40googlegroups.com.

Computer Scratch

unread,
Dec 19, 2022, 12:14:35 AM12/19/22
to Blockly
Hello,
I have set block id using below json block definition
{
  'type': 'blockName',
  'id': '123',
}

but when I look that block id in console.log, it is showing id with values - P#rYmclj8m|v6pU7]^`E.
Please clarify!!

Computer Scratch

unread,
Dec 19, 2022, 2:18:28 AM12/19/22
to Blockly
Suppose I want to add text blocks onto workspace and id of each block has to be incremented by 1 as I add them onto workspace.

for example:
Add text block and its id should start with 1.
and when I add another block, it should increment by 1 i.e, now this block will have id - 2.

Beka Westberg

unread,
Dec 19, 2022, 11:46:04 AM12/19/22
to blo...@googlegroups.com
Hello! Thank you for the question :D

Could you explain a bit more about why you want to use incrementing numbers for Block IDs? Generally that's not a great way to maintain UIDs :/ For example, how do you want to handle blocks getting deleted? Do you want those gaps in the ID chain to exist forever, or do you want to try to fill it back in? Either option adds complexity to serialization, because when you load a save into a workspace you'll need to figure out what your next ID should be.

If you tell us a bit more about your use case, someone on here might be able to give you an alternative solution that works better with Blockly's existing ID system. 

Best wishes,
--Beka

Reply all
Reply to author
Forward
0 new messages