Populate dropdown field options from Google Sheet

fluenform_rendering_field_data_select #

Dropdown/select fields options can be fetched from Google Sheet using fluenform_rendering_field_data_select filter. Here is the following code :

add_filter('fluenform_rendering_field_data_select', function ($data, $form) {
    
    $targetFormID = 3;
    //google sheet shared as CSV link
    $csvUrl = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vT5FV_MYPwTqjhelf6_g02pS1Y60DbdkHDWPvRKVzLPeZSKFNFa4y6kMas3amvM7v1El-b1PVdC0wrP/pub?output=csv';
    
    $columName = 'Players'; // 'Players' is the column name
    $uniqueData = true;     // remove duplicate values
    
    if ($form->id !=  $targetFormID) {
        return $data;
    }
    
    // check if the name attribute is 'dropdown' , it is by default dropdown for the first dropdown input
    
    if (\FluentForm\Framework\Helpers\ArrayHelper::get($data, 'attributes.name') != 'dropdown') {
        return $data;
    }
    
    $result=[] ;
    
    if (!class_exists('CSVParser')) {
        require_once(FLUENTFORMPRO_DIR_PATH . 'libs/CSVParser/CSVParser.php');
    }
    
    $csvParser = new \CSVParser;
    $content = file_get_contents($csvUrl);
    $csvParser->load_data($content);
    $rows = $csvParser->parse($csvParser->find_delimiter());
    
    if(!$rows) {
        return $data;
    }
    $headers = array_shift($rows); // remove the first item
    $headerIndex = array_search($columName, $headers);
    
    foreach ($rows as $row) {
        
        if(!empty($row[$headerIndex])) {
            $result[]=
                
                [
                    "label"      => $row[$headerIndex],
                    "value"      => $row[$headerIndex],
                    "calc_value" => ""
                ];
        }
    }
    
    $result = ($uniqueData === true) ?   array_map("unserialize", array_unique(array_map("serialize", $result))) :  $result;
    
    // Merging with existing options here
    $data['settings']['advanced_options'] = array_merge($data['settings']['advanced_options'], $result );
    return $data;

}, 10, 2);

You need to do the following :

  1. Change your form ID and place this code in your function.php file.
  2. Change the $csvUrl with google sheet link published as CSV.
  3. Add your column name in $columName.
  4. Here we have used ‘dropdown’ as the name attribute
  5. Set $uniqueData to true to remove duplicated data

That is all. New data added to the sheet will be automatically added to your dropdown option after a few minutes.

Hope that will be useful. Feel free to let us know if you need any help with our hooks and filters.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *