Divi Custom Field Type: Multi-checkboxes with IDs

Written by Dan Mossop

If you develop custom Divi modules, you may be aware of the "multiple_checkbox" field type. It lets you add settings into your Divi modules which consist of a list of checkboxes, like this:

One issue you may encounter with this field type is that it doesn't handle changes to the set of checkboxes (e.g. "Phone", "Tablet" and "Desktop" in the example above) well. When the module settings are saved, the setting is stored as a list of the checkbox states, e.g. "on|off|off". That's fine as long as the list of checkboxes remains static. But suppose we wanted to change the list above to "Smartwatch", "Phone", "Desktop". Now when a module previously saved with "Phone" checked is loaded, the "on|off|off" state will cause "Smartwatch" to be checked, rather than "Phone".

One way to resolve this is to create a custom Divi module field type which resembles the "multiple_checkbox" type but stores the actual ids associated with the checked checkbox options, rather than the on / off state. Here's an example of a JSX component that will add such a field type: 

// Like the built-in multiple checkboxes field, but preserves the IDs of the checkboxes in the value.

import React, { Component } from 'react';
import $ from 'jquery';

class DBC_Multiple_Checkboxes_With_IDs extends Component {

    static slug = 'dbc_multiple_checkboxes_with_ids';

    state = {
        checkedBoxes: [],
    };

    constructor(props) {
        super(props);
        this.state = {
            checkedBoxes: this.props.value ? this.props.value.split(',') : [],
        };
    }

    _onCheckboxChange = (event) => {
        const { value, checked } = event.target;
        this.setState(prevState => {
            if (checked) {
                return { checkedBoxes: [...prevState.checkedBoxes, value] };
            } else {
                return { checkedBoxes: prevState.checkedBoxes.filter(box => box !== value) };
            }
        }, () => {
            this.props._onChange(this.props.name, this.state.checkedBoxes.join(','))
        });
    }

    render() {
        let checkboxes_data = this.props.fieldDefinition.options;
        const checkboxes = Object.keys(checkboxes_data).map((id, index) => {
            return (
                <p className="et-fb-multiple-checkbox" key={index}>
                    <label htmlFor={`${this.constructor.slug}-${this.props.name}-checkbox-${id}`}>
                        <input 
                        type="checkbox" 
                        id={`${this.constructor.slug}-${this.props.name}-checkbox-${id}`}
                        name={`${this.constructor.slug}-${this.props.name}-checkbox`} 
                        value={id} 
                        data-text={checkboxes_data[id]}
                        onChange={this._onCheckboxChange}
                        checked={this.state.checkedBoxes.includes(id.toString())}  
                        />{checkboxes_data[id]}
                    </label>
                </p>
            );
        });

        return (
            <div className={`${this.constructor.slug}-wrap et-fb-multiple-checkboxes-wrap`}>
                {checkboxes}
                <input
                    id={`${this.constructor.slug}-${this.props.name}`}
                    name={this.props.name}
                    value={this.props.value}
                    type='hidden'
                />
            </div>
        );
    }
}
export default DBC_Multiple_Checkboxes_With_IDs;

$(window).on('et_builder_api_ready', (event, API) => {
    API.registerModalFields([DBC_Multiple_Checkboxes_With_IDs]);
});

Replace the DBC / dbc prefixes throughout with your own. Then compile and load the JSX component via your preferred method. I've designed it to work as a standalone component that can be manually enqueued using the 'et_fb_enqueue_assets' action. You may need to modify it slightly if using the create-divi-extension tool. 

Now you can use it in your module definition like so:

'your_field_key' => array(
    'label' => esc_html__( 'Multiple Checkbox Example', 'et_builder' ),
    'type' => 'dbc_multiple_checkboxes_with_ids',
    'options' => array(
        123 => esc_html__('Item 1', 'et_builder'),
        456 => esc_html__('Item 2', 'et_builder'),
    ),
)

Then the 'your_field_key' prop should get populated with a comma-separated list representing the IDs selected in the module setting, e.g.:

123,456

With that in place you should be able to dynamically modify the list of checkboxes displayed – as long as you keep a consistent ID for each item you can freely add, delete and reorder the items.

Do More with Divi Dynamic Content!

Enhance your site's flexibility with the Divi Dynamic Content Extended plugin. Unlock dynamic content on more module fields and access data from ACF, Meta Box, and Pods settings pages, making your Divi designs smarter and more efficient.

About Dan Mossop

Dan is a Scottish-born web developer, now living in Brisbane with his wife and son. He has been sharing tips and helping users with Divi since 2014. He created Divi Booster, the first Divi plugin, and continues to develop it along with 20+ other Divi plugins. Dan has a PhD in Computer Science, a background in web security and likes a lot of stuff, 

0 Comments

Submit a Comment

Comments are manually moderated and approved at the time they are answered. A preview is shown while pending but may disappear if your are cookies cleared - don't worry though, the comment is still in the queue.

Your email address will not be published. Required fields are marked *.

We may earn a commission when you visit links on our website.

Latest Posts

Set Custom CSS IDs for Individual Divi Accordion Items

Assigning unique CSS IDs to specific Divi Accordion items allows for precise control over styling, targeting, and linking within your page content. This ability is particularly useful when you want to apply custom designs or create anchor links to particular accordion...

Enable Swipe Navigation in the Divi Gallery Lightbox

Enabling swipe navigation in the Divi Gallery module's lightbox allows users to seamlessly browse through gallery images by swiping left or right, creating a more interactive and mobile-friendly experience. This functionality can significantly improve user engagement...

Disable Slide-In Animation for Divi Gallery Grid Images

Control how images appear in your Divi Gallery module by toggling the slide-in animation effect for grid layouts. Disabling the slide-in animation allows gallery images to load instantly and appear statically, providing a faster and distraction-free browsing...

Control Image Count Display in Divi Gallery Lightbox

Displaying or hiding the image count in the Divi Gallery module’s lightbox can help customize the user experience, depending on whether you want to give visitors an indication of gallery progress or prefer a cleaner, distraction-free view. The ability to toggle this...

Hide Gallery Image Titles in the Divi Lightbox Overlay

Displaying image titles in the lightbox overlay of the Divi Gallery module can sometimes be distracting or unnecessary, depending on your website’s design and user experience goals. Hiding these titles creates a cleaner and more focused viewing experience for visitors...

Random Posts