phpwordpresscontact-form-7

Converting dynamic Contact form 7 checkbox to hidden field or to uncheckable checkbox


In a Contact Form 7 form, I need some dynamic checkboxes.

The data associated with the checkboxes comes from user meta.

I got the checkbox working this way.

In the contact form I have:

[checkbox* checkbox_options]

In a plugin:

add_action( 'wpcf7_init', function(){  remove_action( 'wpcf7_swv_create_schema', 'wpcf7_swv_add_checkbox_enum_rules', 20, 2 );  });

function dynamic_options($tag){

    if ( $tag['name'] != 'checkbox_options' )
        return $tag;
    
    $current_user = wp_get_current_user();
    $s = get_user_meta( $current_user->ID, 'my_user_data', true );
    $f1 = $s['my_user_data']['f1'];
    $f2 = $s['my_user_data']['f2'];

    // hard coded 1 for testing purposes
    for ($i=0; $i<1; $i++) {

        $tag['raw_values'][] = rand();
        $tag['values'][] = $f1[$i];
        $tag['labels'][] = $f2[$i];

    }

    // attempt 1
    /*if(count($tag['values'])==1){
        $tag['type'] = 'hidden';
        $tag["basetype"] = 'hidden';
    }*/

    //echo "<pre>";
    //var_dump($tag);
    //echo "</pre>";

    return $tag;

};

add_filter( 'wpcf7_form_tag', 'dynamic_options', 10, 2);

This could be ok, but sometimes, my_user_data arrays can eventually contain only one item.

This means that the code would end up printing a unique unchecked checkbox.

I'd prefer one of the following:

  1. the checkbox is converted to an hidden field with same id and name;
  2. the checkbox is visible, but it is checked and uncheckable;

I tried the first option by overriding type and basetype, but it half worked: the generated HTML is still compatible with a list of checkboxes, even if the hidden field is eventually created. This solution, at least the way I tried to implement it, is not feasible because it ends up adding unwanted, apparently unremovable, HTML code (e.g., you still see value printed).

Is there any way to implement the first or the second solution?


Solution

  • You can implement the second solution (the checkbox is visible, but it is checked and uncheckable) this way-

    if (!empty($user_data) && count($user_data['f1']) === 1) {
        // For single item, make it checked and disabled
        $tag['raw_values'][] = $user_data['f1'][0];
        $tag['values'][] = $user_data['f1'][0];
        $tag['labels'][] = $user_data['f2'][0];
        $tag['options'][] = 'checked';
        $tag['options'][] = 'disabled';
    } else {
        // Populate the checkbox options dynamically for multiple items
        foreach ($user_data['f1'] as $index => $value) {
            $tag['raw_values'][] = $value;
            $tag['values'][] = $value;
            $tag['labels'][] = isset($user_data['f2'][$index]) ? $user_data['f2'][$index] : '';
        }
    }