WordPress block transforms with InnerBlocks template

1.2k Views Asked by At

My plugin has a custom block that contains an innerblock template, defined in edit() like so...

const HEADING = [
    [
        "core/heading",
        {
            level: 2,
            placeholder: __("Enter a title", "myplugin"),
        },
    ],
];

...and later...

<div className="title">
    <InnerBlocks template={HEADING} templateLock="all" />
</div>

I want to allow existing core/heading blocks to be transformed into a myplugin/my-heading block, so I have the following code in registerBlockType to begin with...

transforms: {
    from: [
        {
            type: "block",
            blocks: ["core/heading"],
            transform: ({ content }) => {
                console.log(content);
                return wp.blocks.createBlock("myplugin/my-heading");
            },
        },
    ],
}

This works insofar as it replaces a core/heading with a myplugin/my-heading block.

The problem is that I cannot figure out how to take the content and insert it into the innerblock template.

The createBlock documentation is pretty basic and I can't find any example of how this might work when the content doesn't map onto any existing attributes.

UPDATE: Here's the full solution. I needed to create a block that matched my template and pass it as an array to the innerblocks parameter:

transforms: {
    from: [
        {
            type: "block",
            blocks: ["core/heading"],
            transform: ({ content }) => {
                const innerBlocks = wp.blocks.createBlock("core/heading", {
                    content: content,
                    placeholder: __("Enter a title", "myplugin"),
                    level: 2,
                });
                return wp.blocks.createBlock("myplugin/my-heading", {}, [
                    innerBlocks,
                ]);
            },
        },
    ],
},
1

There are 1 best solutions below

5
On BEST ANSWER

The example from the WordPress Docs on Block Transforms, shows how you can pass in content as the second parameter to createBlock():

transforms: {
    from: [
        {
            type: "block",
            blocks: ["core/heading"],
            transform: ({ content }) => {
                console.log(content);
                return wp.blocks.createBlock("myplugin/my-heading", {
                    content, // content is inserted here
                });
            },
        },
    ],
}

Example for your block with inner blocks:

transforms: {
    from: [
        {
            type: "block",
            blocks: ["core/heading"],
            transform: ( attributes, innerBlocks ) => {
                return wp.blocks.createBlock(
                    'myplugin/my-heading',
                    attributes,
                    innerBlocks
                );
            },
        },
    ],
}