Multiple checkboxes Gutenberg control

Question

I am trying to create a similar Group Checkbox Control like the WordPress categories listing but have not been able to save my values. I am not convinced I am taking the best direction, but seem to be close to the answer.

enter image description here

I’d like these checkbox values to save to a single attribute as an array, but I am fine with saving the selections as a string (value1,value3,value4,etc).

Below is an example of the edit() method I have created and I’ve taken notes from a similar question here, but am not able to get my selections to save:

attributes: {
    myCheckbox: {
        type: 'array',
        default: []
    }
},
edit: function ( props ) {
    var checkboxes = [];
    var data = [
        {
            label: 'Checkbox 1',
            value: 'checkbox1'
        },
        {
            label: 'Checkbox 2',
            value: 'checkbox2'
        }
    ];
    $.each( data, function ( c, fields ) {
        checkboxes.push(
            el( CheckboxControl, {
                key: fields.value,
                label: fields.label,
                name: 'myCheckbox[]',
                onChange: function( val ) {
                    props.setAttributes({ myCheckbox : myCheckbox[fields.value] });
                }
            })
        )
    });
    return [
        el(
            InspectorControls, {
                key: 'inspector'
            },
            el(
                PanelBody, {
                    title: __( 'Settings' )
                },
                checkboxes
            )
        ),
        el( ServerSideRender, {
            block: 'block/name',
            attributes: props.attributes
        } )
    ]
},

0
Alex Mangini 4 years 2020-02-15T08:39:16-05:00 0 Answers 303 views 0

Leave an answer

Browse
Browse