5

I have this custom post type with two meta fields that I need to show as toggle controls (RestrictControl and SubscribeControl) in the PluginDocumentSettingPanel sidebar in the Gutenberg editor. The thing is that I only want to show SubscribeControl when RestrictControl is set. This is the code I've got currently but it's not working. When I toggle RestrictControl on and off both controls are always displayed.

Any ideas?

let RestrictControl = ({ restrict, onUpdateRestrict }) => (
    <ToggleControl
        label={ __( 'Restrict viewing?' ) }
        checked={ restrict }
        onChange={ restrict => onUpdateRestrict( restrict ) }
    />
);

let SubscribeControl = ({ subscribe, onUpdateSubscribe }) => (
    <ToggleControl
        label={ __( 'Add to newsletter?' ) }
        checked={ subscribe }
        onChange={ subscribe => onUpdateSubscribe( subscribe ) }
    />
);

const OptionsPanel = () => {
    const postType = select( 'core/editor' ).getCurrentPostType();
    if ( 'custom_type' !== postType ) {
        return null;
    }

    return (
        <PluginDocumentSettingPanel
            name='options'
            title={ __( 'Options' ) }
            className='options-panel'
        >
            <RestrictControl />
            { restrict && (
                <SubscribeControl />
            ) }
        </PluginDocumentSettingPanel>
    );
}

registerPlugin( 'options-panel', {
    render: OptionsPanel,
})

1 Answer 1

5
+50

There are 2 main issues in your code:

  1. What is that restrict in your OptionsPanel component? Where and how you defined it?

  2. Both the onUpdateRestrict and onUpdateSubscribe are not functions, so clicking on the toggle controls will result in a JavaScript error.

And if you can show your complete code, I can probably help you fix your code. However, I suggest you to try the compose package to build the OptionsPanel component because doing it that way can greatly help reduce the source and make things quite easy for us.

So with the compose package, the steps are:

Note: I'm using these two meta keys: restrict_viewing and subscribe_to_news, so be sure to change them to the correct ones. (I.e. Use the proper meta keys.)

  1. Load all WordPress dependencies:

    import { PluginDocumentSettingPanel } from '@wordpress/edit-post';
    import { ToggleControl } from '@wordpress/components';
    import { __ } from '@wordpress/i18n';
    import { registerPlugin } from '@wordpress/plugins';
    import { withSelect, withDispatch } from '@wordpress/data';
    import { compose } from '@wordpress/compose';
    
  2. Create the primary component which basically simply renders the plugin/sidebar panel plus the two toggle controls (the RestrictControl & SubscribeControl in the question).

    function OptionsPanelComponent( {
        // These props are passed by applyWithSelect(). (see step #3)
        currentPostType, // current post type
        restrictViewing, // current state of the meta restrict_viewing
        subscribeToNews, // current state of the meta subscribe_to_news
        // And these are passed by applyWithDispatch(). (see step #4)
        onUpdateRestrict,  // function which updates the meta restrict_viewing
        onUpdateSubscribe, // function which updates the meta subscribe_to_news
    } ) {
        if ( 'custom_type' !== currentPostType ) {
            return null;
        }
    
        return (
            <PluginDocumentSettingPanel
                name="options"
                title={ __( 'Options' ) }
                className="options-panel"
            >
                <ToggleControl
                    label={ __( 'Restrict viewing?' ) }
                    checked={ restrictViewing }
                    onChange={ onUpdateRestrict }
                />
                { restrictViewing && (
                    <ToggleControl
                        label={ __( 'Add to newsletter?' ) }
                        checked={ subscribeToNews }
                        onChange={ onUpdateSubscribe }
                    />
                ) }
            </PluginDocumentSettingPanel>
        );
    }
    
  3. Use wp.data.withSelect to 'select'/retrieve data from the current post (that's being edited) and pass the data to the above component (OptionsPanelComponent).

    Note: The select is always passed to the function and that select is equivalent to wp.data.select.

    const applyWithSelect = withSelect( ( select ) => {
        const {
            getEditedPostAttribute,
            getCurrentPostType
        } = select( 'core/editor' );
    
        const meta = getEditedPostAttribute( 'meta' );
    
        return {
            currentPostType: getCurrentPostType(),
            restrictViewing: meta.restrict_viewing,
            subscribeToNews: meta.subscribe_to_news,
        };
    } );
    
  4. Use wp.data.withDispatch to define the functions for updating the post data and pass the functions to the component in step #2 above (OptionsPanelComponent).

    Note: The dispatch is always passed to the function and that dispatch is equivalent to wp.data.dispatch.

    const applyWithDispatch = withDispatch( ( dispatch ) => {
        const { editPost } = dispatch( 'core/editor' );
    
        return {
            onUpdateRestrict( restrict ) {
                const meta = { restrict_viewing: restrict };
                editPost( { meta } );
            },
            onUpdateSubscribe( subscribe ) {
                const meta = { subscribe_to_news: subscribe };
                editPost( { meta } );
            },
        };
    } );
    
  5. Then finally, use wp.compose.compose() to 'compose'/wrap all the three components above (they might be defined using function or const, but they really are components). And this 'composed' component will be the one we pass as the render callback for wp.plugins.registerPlugin.

    const OptionsPanel = compose(
        applyWithSelect,
        applyWithDispatch
    )( OptionsPanelComponent );
    
    registerPlugin( 'options-panel', {
        render: OptionsPanel,
    } );
    

Full Code I used for testing purposes

You can find it here, or you can download the full plugin which I created based on this example.

And I have tried & tested that on WordPress 5.4.1 with the default post post type with the two meta keys mentioned earlier in this answer.

Alternate Solution

If you don't want to use compose(), then you can try this one. But I'm adding that just because I thought it would be useful to myself in the future. :)

3
  • 1
    Sorry, I meant wp.compose.compose and not wp.data.compose. I'll correct that later.
    – Sally CJ
    Commented May 26, 2020 at 11:03
  • 1
    Thank you very much! I'm pretty much a newbie in Gutenberg development and your code and explanation helped me to better understand the inner workings of it.
    – leemon
    Commented May 26, 2020 at 17:43
  • You're welcome! And I'm actually also still learning Gutenberg, so it's good to see useful questions like this on WPSE. :) Btw, I've corrected the typo and also revised the plugin, just in case you're interested in checking what changed. ;)
    – Sally CJ
    Commented May 27, 2020 at 6:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.