WordPress / gutenberg

The Block Editor project for WordPress and beyond. Plugin is available from the official repository.
https://wordpress.org/gutenberg/
Other
10.48k stars 4.18k forks source link

Boolean block attribute with source «attribute» should allow «true»/«false» values #13949

Open davilera opened 5 years ago

davilera commented 5 years ago

So I created a block with an attribute that looks like this:

attributes: {
  showZoomButton: {
    type: 'boolean',
    source: 'attribute',
    selector: 'div',
    attribute: 'data-show-zoom-button',
    default: true,
  },
}

and I'm trying to save this value as follows:

save: props => {
  const { showZoomButton } = props.attributes;
  const attributes = {
    'data-show-zoom-button': showZoomButton ? 'true' : 'false',
  };
  return (
    <div { ...attributes }></div>
  );
}

The problem is: it doesn't matter what the actual value of data-show-zoom-button is, Gutenberg always expects it to be set to true. Why? Is it because it's assuming that a non-empty HTML attribute value like "false" should be translated to true?

One possible solution could be: if data-show-zoom-button is false, then don't include that attribute in the save method. But then a different problem would arise: I want to know the attribute is false and I want to use that attribute; otherwise, Gutenberg would pull the default value (which, in this case, is set to true).

Any ideas on how to overcome this issue?

davilera commented 5 years ago

Do we need an extra option here? https://github.com/WordPress/gutenberg/blob/master/packages/blocks/src/api/parser.js#L51

strarsis commented 1 year ago

That only the presence or absence of the matching html attribute of a boolean attribute determines whether it is true or false introduces another issue with the current behavior of Gutenberg: When the block is initially inserted, the default value of the boolean attribute is used. When the default is true, the attribute will be true, even if it is absent in the newly created block. When a block is loaded from a post though, only the presence of the boolean attribute determines its value, and then its value is false as the matching html attribute is absent. This results in inconsistent behavior.