简体   繁体   English

如何从 Google Sheets 数据动态填充 Gravity Forms 选择(下拉)菜单项

[英]How to dynamically populate Gravity Forms select (dropdown) menu items from Google Sheets data

I'm trying to dynamically populate the options available for selection in a dropdown menu using data from google sheets.我正在尝试使用谷歌表格中的数据动态填充下拉菜单中可供选择的选项。 The data is located on column A (A2:A4 at the moment, but this is subject to change) and will include the names of available employees.数据位于 A 列(目前为 A2:A4,但可能会发生变化)并将包括可用员工的姓名。

So if:因此,如果:

   A
1 name 
2 jack 
3 Bob
4 John

I need these 3 names to dynamically be available for selection in a dropdown menu within gravity forms.我需要这 3 个名称在重力形式的下拉菜单中动态可供选择。 I also need the flexibility allowing there to be more or less names whenever an employees availability changes.我还需要灵活性,允许在员工可用性发生变化时有更多或更少的名字。

I've been trying to put something together using the gravity forms documentation, as well as taking bits and pieces from snippets I've found on github.我一直在尝试使用重力形式文档将一些东西放在一起,并从我在 github 上找到的片段中获取点点滴滴。 This is what I have so far, but it is giving me a critical error:到目前为止,这是我所拥有的,但它给了我一个严重错误:

$location_form_id = [FORM ID HERE];
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_'.$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){
      
      foreach($form['fields'] as &$field){
          
        if($field->id != [FIELD ID HERE] ) {
           continue;
            
            // Hook into Google Spreadsheets //
            $url = 'http://spreadsheets.google.com/feeds/list/[SPREADSHEET ID HERE]/od6/public/values?alt=json';
            $file = file_get_contents($url);
            
            $json = json_decode($file);
            $rows = $json->{'feed'}->{'entry'};
            
            $names = array();
            
            foreach($rows as $row) {
                $name = $row->{'gsx$name'}->{'$t'};
                    $names[] = $name;
            }
    
        foreach($names as $single_name){
                $choices[] = array('text' => $single_name, 'value' => $single_name );
            }
            
         $field['choices'] = $choices;
          
      }
     
      return $form;
  }

You need to use few filters given by gravity forms to achieve this.您需要使用重力形式给出的一些filtersachieve这一点。 Only four filters are required.只需要四个过滤器。

  1. gform_pre_render_
  2. gform_pre_validation_
  3. gform_pre_submission_filter_
  4. gform_admin_pre_render_

You need to get the loop through all the fields of your form id XX and check whether the field you are selecting is an actual dropdown field means a select field.您需要遍历表单 ID XX所有fields ,并检查您选择的字段是否是实际的dropdown字段意味着select字段。

To push all the new found in the sheets we can use array_push method and then loop through that array to get all the names that were stored.push在工作表中找到的所有新名称,我们可以使用array_push方法,然后遍历该array以获取所有存储的名称。

You can also add a placeholder if you want to to your select field and lastly just the return the $form如果您想添加到您的选择field ,您还可以添加一个占位符,最后只返回$form

In the below code just add your own $form_id , select $feild_id and $gSheet_form_ID .在下面的代码中,只需添加您自己的$form_id ,选择$feild_id$gSheet_form_ID

Add this code your active theme functions.php file.将此代码添加到您的活动主题functions.php 文件中。 (Code tested and works) (代码测试和工作)

$location_form_id = '62';
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 = '2';
    //your g sheet ID
    $gSheet_form_ID = 'your_public_google_sheet_id';

    //get data
    $url = 'https://spreadsheets.google.com/feeds/list/'.$gSheet_form_ID.'/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$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 2
        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 = 'Select a Name';
            //Add the new names to the form choices
            $field->choices = $choices;
        }
    }
    return $form; //return form
}

Working Select Field Preview工作选择字段预览

在此处输入图片说明

Thank you for this great example.谢谢你这个很好的例子。 Initially, it did not work for me until I realized that the 'name' is the heading (name) of the column and is hard-coded - I modified that.最初,它对我不起作用,直到我意识到“名称”是列的标题(名称)并且是硬编码的 - 我修改了它。 I was also missing the ability to browse between lists, so I added a variable for that.我还缺少在列表之间浏览的能力,所以我为此添加了一个变量。

Lastly, if your side is running on WordPress, I recommend using the 'Code Snippets' plugin instead of directly adding code into the functions.php - it is cleaner + will not stop working if your theme is modified/changed.最后,如果您的一方在 WordPress 上运行,我建议使用“代码片段”插件,而不是直接将代码添加到 functions.php - 它更干净+ 如果您的主题被修改/更改,则不会停止工作。

See below:见下文:

$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
}

What can still be improved?还有什么可以改进的?

  1. The URL used for retrieving the data via Google Sheets API is using API v3, which will be deprecated on June 8th, 2021. If anyone has thoughts on how to improve the code for APIv4, then please let us know!用于通过 Google Sheets API 检索数据的 URL 使用 API v3,该版本将于 2021 年 6 月 8 日弃用。如果有人对如何改进 APIv4 的代码有任何想法,请告诉我们!

  2. If you are checking for a cell that is in a column that is 'shorter' than another one, you will end up with empty values in the array.如果您要检查的列中的单元格比另一列“短”,则数组中最终会出现空值。 There should be a check against empty values in the code (should be pretty simple to add).应该检查代码中的空值(添加应该很简单)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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