3

I am trying to create a custom block for text input field.

I managed to create a simple block that produces the <p> tag. When I change it to produce the <input> tag and refresh I am getting Block validation failed and the only solution is to remove the block and re-insert it.

It is ok if you have few blocks on a page but I am wondering what if I want to update a whole theme with existing content. Seems like even changing a trivial property as colour results in validation error.

  // existing
  save: (props) ->
     el RichText.Content,
        tagName: 'p'
        value: props.attributes.content

  // updated
  save: (props) ->
     el RichText.Content,
        tagName: 'input'
        value: props.attributes.content

What is the correct way of amending and updating existing Gutenberg blocks?

4

You have two choices.

The first one you've discovered: change the block's underlying code, and you will trigger validation errors. The benefit is, you're only including the JS currently required for your block - so it keeps the code as lightweight as possible.

The second option: add deprecated code into your block. In this case, you define not only the block as you want it to be now, but also past (deprecated) versions of the block, so WP recognizes the old and can transform it to the new version every time you edit a post. The benefit is, this won't trigger validation errors (and potentially blank blocks) whenever you update the save() output. The downside is, the more times you change the output and keep the "deprecated" code available, the heavier your plugin gets.

2
  • Is there any way to temporarily disable the validation checker? then it would be possible to save the updated markup. – Maciek Rek Apr 25 '20 at 9:48
  • 1
    No. It's not just a validation checker - it's a problem of the blocks being stored as HTML in the database, and WP not knowing how to pull out the attributes because its structure is different than what it's expecting. Switching between HTML and JS means there has to be a clear definition of where to pull and push attributes. – WebElaine Apr 27 '20 at 18:27
0

After reading through the WP Handbook guide, I found out that the better solution might be using dynamic blocks, at least in the development stage.

[...] Blocks where updates to the code (HTML, CSS, JS) should be immediately shown on the front end of the website. For example, if you update the structure of a block by adding a new class, adding an HTML element, or changing the layout in any other way, using a dynamic block ensures those changes are applied immediately on all occurrences of that block across the site.[...]

https://developer.wordpress.org/block-editor/tutorials/block-tutorial/creating-dynamic-blocks/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.