简体   繁体   中英

contact form 7 conditional required checkbox

I have a conditional form ( Contact Form 7 on Wordpress) which will hide or show fields according to the boxes checked on the first question.

Only the questions showing up are required (ie their categories were checked in the first question). In order to do that, I need to set the all the checkboxes as required and then perform the magic at the validation code below

function wpcf7_checkbox_validation_filter( $result, $tag ) {
$tag = new WPCF7_Shortcode( $tag );


$type = $tag->type;
$name = $tag->name;

$value = isset( $_POST[$name] ) ? (array) $_POST[$name] : array();

if ( $tag->is_required() && empty( $value ) ) {
    $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
}

return $result;
}

for this particular line if ( $tag->is_required() && empty( $value ) ) I need to change it to check:

  1. $tag->required() AND
  2. empty( $value ) AND
  3. whether the checkbox's main category has been checked

Only then will it be invalidated.

How can the 3rd point be coded? Also I have about 5-10 questions for each category.

I found the answer after much effort

function example_checkbox_validation_filter( $result, $tag ) {
$tag = new WPCF7_Shortcode( $tag );

$arr1 = array('project', 'property', 'budget', 'spaces', 'physical-limitations', 'achieve', 'control', 'lighting', 'climate', 'security');
$arr2 = array('pc_room', 'pc_display', 'pc_audio', 'pc_source', 'pc_seat', 'pc_control');

$type = $tag->type;
$name = $tag->name;

$value = isset( $_POST[$name] ) ? (array) $_POST[$name] : array();

foreach($_POST['choice'] as $selected){
    if ( $selected == 'Example' ) {
        if ( $tag->is_required() && empty( $value ) ) {
            foreach ($arr1 as $array) {
                    if ( $name == $array ) {
                        $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
                }
            }
        }
    }
    if ( $selected == 'Example 2' ) {
        if ( $tag->is_required() && empty( $value ) ) {
            foreach ($arr2 as $array) {
                    if ( $name == $array ) {
                        $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
                }
            }
        }
    }
}
return $result;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM