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

Hide the Page Title in the Hello Elementor Theme

Hiding the page title in the Hello Elementor theme allows you to create a cleaner and more customized page layout, free from default headings that may not fit your design. This is particularly useful for landing pages or custom content layouts where the default page...

How to Hide a Divi Module When Scrolling Up or Down

In this quick tutorial, I’ll show you how to hide a Divi module when scrolling in a specific direction (up or down), so that the module only shows when you want it to. This is especially useful when using Divi’s Scroll Effects feature and you have a effect you want to...

Fade a Divi Image Module Edge into the Background

Want to create a stylish fade effect on your Divi image module—where one side fades smoothly into the background? With a bit of CSS, you can make any edge (or corner) of the image fade out: top, bottom, left, right, or even diagonally.Fade a Divi Image Module Edge...

Hide the Header and Footer in the Hello Elementor Theme

Removing the default header and footer from your Hello Elementor theme allows for a streamlined and distraction-free website design. This is especially useful when creating unique landing pages, full-width layouts, or custom headers and footers with a page builder. In...

Setting up the Divi Password Box Module

Setting up password protection on a page can help you control access to sensitive or private content in WordPress, allowing only authorized visitors to view certain sections. With the Divi Password Box module, you can replace the plain Divi password form with a fully...

Random Posts