My goal is for a dynamic Gutenberg Block to work. To find where I go wrong, I reverted it to a static block to check that the attributes save properly, and it works just fine. I also commented out the php side of things so that won’t affect anything.
Second step in my testing: I turn the block to dynamic by returning null from the save function. My goal is only to see if the editor stores the attributes, I don’t care about the front end yet. Result: It doesn’t and I have no idea why not.
The documentation says: “For many dynamic blocks, the save callback function should be returned as null, which tells the editor to save only the block attributes to the database.” So it should save them? I don’t get it.
Here’s the static code that’s working perfectly:
registerBlockType( 'slp/signup', {
title: __( 'Sign Up' ),
icon: 'email',
category: 'layout',
keywords: [
__( 'sign up' ),
__( 'form' )
],
attributes: {
title: {
type: 'array',
source: 'children',
selector: 'h2',
},
},
edit( props ) {
function setTitle( content ) {
props.setAttributes( { title: content } );
}
return (
<RichText
tagName="h2"
value={ props.attributes.title }
formattingControls={ [ 'bold', 'italic' ] }
onChange={ setTitle }
placeholder={ __( 'Heading...' ) }
/>
);
},
save( props ) {
return <h2>{props.attributes.title}</h2>;
}
} );
Here’s the only thing I change to try to turn it dynamic:
save( props ) {
return null;
}
At this point no attributes are stored, and when I update my editor, everything is empty. (And when I do try to output it with php, it returns an empty array.)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can’t use attributes that source data from the HTML markup of your block when using Dynamic Blocks. The attribute selector looks at the Save function’s HTML for the attribute, not the Edit function.
You can simply use a type: ‘string’ instead. Hope this helps!
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0