1

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.)

1 Answer 1

2

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!

2
  • Thank you so much! I've tried so many other things but this solved it. I barely grasp the concept, but I'll look deeper into what the "children" selector really means. In my code that was only copied from someone else, with too little comprehension. Thank you so much again! Dec 20, 2020 at 21:54
  • You're welcome! Dec 22, 2020 at 18:15

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.