微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何动态填充 Gravity Forms 从 Google Sheets 数据的不同列中选择菜单项

如何解决如何动态填充 Gravity Forms 从 Google Sheets 数据的不同列中选择菜单项

我正在尝试使用 Google 表格中的数据填充下拉列表中可供选择的选项。我发现这段代码运行良好,但我希望列名是动态的,并且基于另一个字段的输入。

$location_form_id = '21';
add_filter( 'gform_pre_render_'.$location_form_id,'populate_posts' );
add_filter( 'gform_pre_validation_'.$location_form_id,'populate_posts' );
add_filter( 'gform_pre_submission_filter_'.$location_form_id,'populate_posts' );
add_filter( 'gform_admin_pre_render_'.$location_form_id,'populate_posts' );


function populate_posts( $form ) {

    //the select feild id you want the names to load
    $field_ID = 'FIELD_ID_HERE';
    //your g sheet ID
    $gSheet_form_ID = 'SHEET_ID_HERE';
    // which column to scan - what is the heading name
    $column_name = 'COLUMN_heading_NAME_HERE';
    $placeholder = 'YOUR_PLACEHOLDER_HERE';
    $list_number = '1';


    //get data
    $url = 'https://spreadsheets.google.com/Feeds/list/'.$gSheet_form_ID.'/'.$list_number.'/public/values?alt=json';
    
    $file = file_get_contents($url);
    $json = json_decode($file);
    $rows = $json->{'Feed'}->{'entry'};


    //get all the same from sheet
    $names = array(); //store names in this array
    foreach($rows as $row) {
        $name = $row->{'gsx$'.$column_name}->{'$t'};
        array_push($names,$name); //push data
    }
    
    //Go through each form fields
    foreach ( $form['fields'] as $field ) {
        //check if field type is a select dropdown and id is correct
        if ( $field->type == 'select' && $field->id == $field_ID) {
            //add name and value to the option
            foreach($names as $single_name){
                $choices[] = array('text' => $single_name,'value' => $single_name );
            }
            //Add a place holder
            $field->$placeholder;
            //Add the new names to the form choices
            $field->choices = $choices;
            // Print out the contents of the array (troubleshooting only)
            //echo '<pre>'; print_r($choices); echo '</pre>';
        }
    }
    return $form; //return form
}

如何编辑此代码,以便 $column_name = 字段 1 中的任何输入显示 Google 表格列中字段 2 中的不同选择。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。