Limiting Option Availability in Kali Forms Based on Submissions

Kali Forms is a powerful and easy-to-use form builder for WordPress websites. Sometimes, you might need to limit the availability of certain options in your form based on the number of submissions made with each option. This blog post will guide you through the process of achieving this by customizing your form using PHP and JavaScript.

Step 1: Add PHP code to retrieve submission data To get started, you’ll need to add some PHP code in your WordPress theme’s functions.php file. This code will retrieve the number of submissions made with each option in your form. You can access the functions.php file by going to your WordPress Admin Panel > Appearance > Theme Editor > Theme functions.

Copy and paste the following code into your functions.php file:

add_action( 'wp_ajax_kaliforms_get_data_from_db', 'kaliforms_get_data_from_db' );

function kaliforms_get_data_from_db() {
    if ( ! isset( $_POST['action'], $_POST['nonce'] ) ) {
        wp_die( wp_json_encode( [
                                    'success' => false,
                                    'message' => esc_html__( 'Denied' ),
                                ] ) );
    }
    if ( ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'kaliforms_nonce' ) ) {
        wp_die( wp_json_encode( [
                                    'success' => false,
                                    'message' => esc_html__( 'Denied' ),
                                ] ) );
    }

    function getArgs( $formId, $key, $metakey ) {
        return [
            'post_type'      => 'kaliforms_submitted',
            'posts_per_page' => - 1,
            'order'          => 'ASC',
            'meta_query'     => [
                [
                    [
                        'key'     => 'formId',
                        'value'   => $formId,
                        'compare' => '=',
                    ],
                    [
                        'key'     => $metakey,
                        'value'   => $key,
                        'compare' => '='
                    ]
                ]
            ]
        ];
    }

    $A = new \WP_Query( getArgs( 1308, "A", "dropdown-name" ) );
    $B = new \WP_Query( getArgs( 1308, "B", "dropdown-name" ) );
    $C = new \WP_Query( getArgs( 1308, "C", "dropdown-name" ) );
    $D = new \WP_Query( getArgs( 1308, "D", "dropdown-name" ) );

    $result = [
        "A" => 10 - $A->post_count,
        "B" => 10 - $B->post_count,
        "C" => 10 - $C->post_count,
        "D" => 10 - $D->post_count,
    ];
    wp_die( wp_json_encode( $result ) );
}

Make sure to replace 1308 with the actual ID of your form and A, B, C, and D with the actual values from your dropdown field and it’s name.

Step 2: Add JavaScript code to disable options and show the remaining count After adding the PHP code, you need to include some JavaScript in the Custom JS section of your form. This code will disable options in your dropdown field once they reach their limit and show the number of remaining submissions for each option.

Copy and paste the following code into the Custom JS section of your form:

document.addEventListener('kaliFormProcessConstructed', function(event){
    let disableOption = function(data) {
        let dropdownEl = event.detail.form.querySelector('#course');
        for(let key in data){
            const option = dropdownEl.querySelector(`option[value=${key}]`);
            if(data[key] <= 0){
                option.setAttribute('disabled', true);
                option.innerHTML = `${option.innerHTML} - filled`;
            } else {
                option.innerHTML = `${option.innerHTML} - ${data[key]} left`
            }
        }
    }
    
    jQuery.ajax({
        type: 'POST',
        data: {
            action: 'kaliforms_get_data_from_db',
            nonce: KaliFormsObject.ajax_nonce
        },
        url: KaliFormsObject.ajaxurl,
        success: function(res){
            let data = [];
            try {
                data = JSON.parse(res);
            } catch (err) {
                console.warn(err);
            }            if(data.length === 0){
                return;
            }            disableOption(data);
        },
    });
});

With this JavaScript code, the form will fetch the submission data from the server and update the dropdown field accordingly.

Step 3: Verify and test your form Once you’ve added the PHP and JavaScript code, save your changes and test your form on the front-end of your website. You should see the options in the dropdown field updated with the remaining count. If an option has reached its limit, it should be disabled and marked as “filled.”

By following these steps, you’ve successfully customized your Kali Form to limit the availability of options based on the number of submissions made with each option. This functionality can be useful in various scenarios, such as event registration, limited product sales, or any other use case where you want to restrict the number of submissions for specific options. With Kali Forms, you can easily extend the functionality of your forms to meet your unique requirements.

Cosmin
Cosmin