abu
abu

Reputation: 51

WordPress Contact form 7 form field hiding when data is null

I have using contact form 7 plugin in my website. I want to display the mailed data on WordPress dashboard. for getting this i have using a plugin called "Contact Form CFDB7". My form have drop down fields. its showing with conditions. (example one field is country and another field is states, so if selecting the country as US, then the state field only listing US states. this is taken by using the plugin"contact form 7 conditional fields."). so while sending the mail, its will list out all data in dashboard .its have empty fields as well as filled fields. so my question is any option to only show the filled fields in dashboard.

please help me for resolving the same. Regards

Upvotes: 0

Views: 3443

Answers (1)

Joe Dooley
Joe Dooley

Reputation: 234

I found a filter that you could use to remove empty values before the form data is saved to the database.

The cfdb7_before_save_data filter should do the trick.

This is untested but it should work. You can also swap out the loop and use something like array_filter() to clean up the code a bit. Also, remove the return type hint if your not using PHP 7+.

/**
 * Removes null values and empty strings from form data before it's saved
 * into the database.
 *
 * @link   https://stackoverflow.com/questions/49087192/wordpress-contact-form-7-form-field-hiding-when-data-is-null
 *
 * @param  array $form_data
 *
 * @return array $form_data 
 */
add_filter( 'cfdb7_before_save_data', function ( array $form_data ): array {

    foreach ( $form_data as $key => $value ) {
        if ( null === $value || '' === $value ) {
            unset( $form_data[ $key ] );
        }
    }

    return $form_data;
} );

This snippet will work with older versions of PHP. You can place this at the bottom of your functions.php.

/**
 * Removes null values and empty strings from form data before it's saved
 * into the database.
 *
 * @link   https://stackoverflow.com/questions/49087192/wordpress-contact-form-7-form-field-hiding-when-data-is-null
 *
 * @param  array $form_data
 *
 * @return array $form_data
 */
function prefix_or_namespace_filter_cfdb7_before_save_data( array $form_data ) {

    foreach ( $form_data as $key => $value ) {
        if ( null === $value || '' === $value ) {
            unset( $form_data[ $key ] );
        }
    }

    return $form_data;
}

add_filter( 'cfdb7_before_save_data', 'themeprefix_filter_cfdb7_before_save_data', 999 );

If your still receiving an error with this please provide screenshots of the error message or open your PHP or WordPress error log and copy the error from there.

Upvotes: 0

Related Questions