I thought I had it. I added an attribute “max_level” and a SelectControl element “SelectMaxLevel”. Everything works according to plan: I can set the max level and it is saved in the block. When I save the post and display the post see that the php part uses the “maximum level” variable. But when I edit the post the blocks loads it’s default value. Why does this happen?
registerBlockType('simpletoc/toc', {
title: __('SimpleTOC', 'simpletoc'),
icon: simpletocicon,
category: 'layout',
attributes: {
no_title: {
type: 'boolean',
default: false,
},
},
attributes: {
max_level: {
type: 'integer',
default: 6,
},
},
edit: function(props) {
const SelectMaxLevel = withState( {
level: props.attributes.max_level,
} )( ( { level, setState } ) => (
<SelectControl
label={__("Maximum Level", 'simpletoc')}
help={__('Maximum depth of the headings.', 'simpletoc')}
value= { props.attributes.max_level }
options={ (
{ label: __('Including', 'simpletoc') + ' H6 (' + __('Show all', 'simpletoc') + ')' , value: '6' },
{ label: __('Including', 'simpletoc') + ' H5', value: '5' },
{ label: __('Including', 'simpletoc') + ' H4', value: '4' },
{ label: __('Including', 'simpletoc') + ' H3', value: '3' },
{ label: __('Including', 'simpletoc') + ' H2', value: '2' },
) }
onChange={ ( level ) => { setState( props.setAttributes( { max_level: level } )) } }
/>
) );
return (
<span>
<InspectorControls>
<Panel>
<PanelBody>
<PanelRow>
<ToggleControl
label={__("Disable heading", 'simpletoc')}
help={__('Remove "Table of contents" block heading.', 'simpletoc')}
checked={ props.attributes.no_title }
onChange={ () => props.setAttributes( { no_title: ! props.attributes.no_title } ) }
/>
</PanelRow>
<PanelRow>
<SelectMaxLevel />
</PanelRow>
</PanelBody>
</Panel>
</InspectorControls>
<BlockControls>
<ToolbarGroup>
<ToolbarButton
className="components-icon-button components-toolbar__control"
label={__('Update table of contents', 'simpletoc')}
onClick={function() {
sendfakeAttribute(props)
}}
icon="update"
/>
</ToolbarGroup>
</BlockControls>
<p>
<ServerSideRender block={props.name} attributes={props.attributes} />
</p>
</span>
)
},
save: props => {
return null;
},
});
The relevant php part:
register_block_type('simpletoc/toc', (
'editor_script' => 'simpletoc-js',
'editor_style' => 'simpletoc-editor',
'attributes' => array(
'no_title' => array(
'type' => 'boolean',
'default' => false,
),
'max_level' => array(
'type' => 'integer',
'default' => 6,
),
'updated' => array(
'type' => 'number',
'default' => 0,
'_builtIn' => true,
),
),
'render_callback' => __NAMESPACE__ . '\render_callback'
));