Prefill Kali Forms Fields with Data from the Database

Kali Forms is a versatile form builder plugin for WordPress websites. There may be cases where you want to prefill form fields with data taken from the database, such as when a user returns to edit their previously submitted information. In this blog post, we will guide you through the process of prefilling form fields with data from the database using PHP and JavaScript.

Step 1: Add PHP code to retrieve data from the database First, edit the functions.php file of your chosen theme (Appearance > Theme File Editor) and add the following script:

add_action('wp_ajax_kaliforms_get_data_from_db', 'kaliforms_get_data_from_db');
function kaliforms_get_data_from_db()
{
	function get_data_from_form($formId, $uid)
	{
		$args = [
			'post_type'      => 'kaliforms_submitted',
			'posts_per_page' => 1,
			'meta_query'     => [
				[
					[
						'key'     => 'formId',
						'value'   => $formId,
						'compare' => '=',
					],
					[
						'key'     => 'kf_submitted_user_id',
						'value'   => $uid,
						'compare' => '='
					]
				]
			]
		];

		$data = new \WP_Query($args);
		$meta = get_post_meta($data->post->ID);
		foreach ($meta as $k => $v) {
			$meta[$k] = $v[0];
		}
		return $meta;
	}

	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'),
		]));
	}
	if (!isset($_POST['formId'], $_POST['uid'])) {
		wp_die(wp_json_encode([
			'success' => false,
			'message' => esc_html__('You didnt specified a form or user'),
		]));
	}
	wp_die(wp_json_encode(
		get_data_from_form($_POST['formId'], $_POST['uid'])
	));
}

This PHP code defines a function get_data_from_form that takes a form ID and a user ID and returns the data associated with that user’s submission.

Step 2: Add JavaScript code to prefill form fields Next, add the following script in the Custom JS section of your Kali Forms:

document.addEventListener('kaliFormProcessConstructed', function (event) {
    jQuery.ajax({
        type: 'POST',
        data: {
            action: 'kaliforms_get_data_from_db',
            nonce: KaliFormsObject.ajax_nonce,
            formId: 5,
            uid: window.userSettings.uid
        },
        url: KaliFormsObject.ajaxurl,
        success: function (res) {
            let data = [];
            try {
                data = JSON.parse(res);
            } catch (err) {
                console.warn(err);
            } if (data.length === 0) {
                return;
            }
      
            jQuery('#email').val(data.email)
            console.log(data);
        },
    });
});

This JavaScript code listens for the kaliFormProcessConstructed event and, when triggered, sends an AJAX request to fetch the data associated with the specified form ID and user ID. Once the data is received, it pre-fills the form fields with the corresponding values.

Make sure to adjust the script to include the actual form ID.

Step 3: Verify and test your form

After adding the PHP and JavaScript code, save your changes and test your form on the front-end of your website. The form fields should now be pre-filled with the data from the database for the specified user and form ID.

Keep in mind that you may need to customize the JavaScript code to match the field names and IDs in your form. In the example provided, the email field is pre-filled with the following line of code:

jQuery('#email').val(data.email);

You can add similar lines for other fields in your form by replacing #email with the appropriate field ID and data.email with the corresponding field name from the database.

By following these steps, you have successfully pre-filled your Kali Forms fields with data taken from the database. This feature can be useful in various scenarios, such as allowing users to edit their previously submitted information, auto-filling forms for registered users, or pre-populating forms with default values from the database. With Kali Forms, you can easily customize and extend the functionality of your forms to meet your unique requirements.

Cosmin
Cosmin