Last active
September 13, 2017 07:28
-
-
Save DavidCramer/a932ab836978eec58145 to your computer and use it in GitHub Desktop.
Dynamically populating an option based field (select,radio,checkbox etc.) in Caldera Forms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* Example to auto populate an option based field in caldera forms | |
* This example uses a by slug. method. this way you can populate the | |
* field by simply giving it the desired slug. in this example: gdp | |
* | |
* To populate based on type where {type} is dropdown, radio, checkbox etc... | |
* add_filter('caldera_forms_render_get_field_type-{type}', 'cf_get_data_json'); | |
*/ | |
// Add filter on the fetch field config to populate | |
add_filter('caldera_forms_render_get_field_slug-gdp', 'cf_get_data_json'); | |
// function to populate the options | |
function cf_get_data_json($field){ | |
// Use transient to cache result to limit calls | |
$source = get_transient( '_cf_get_gdp_data_json' ); | |
// fetch source if transient is empty / expired | |
if( empty( $source ) ){ | |
$source = json_decode( file_get_contents( 'https://www.quandl.com/api/v1/datasets/FRED/GDP.json' ), true ); | |
set_transient( '_cf_get_gdp_data_json', $source, 86400 ); // 86400 seconds = 24 hours | |
} | |
// reset defined options | |
$field['config']['option'] = array(); | |
// uncomment below to set the default to the first item | |
// $field['config']['default'] = 0; | |
// go over the data in the source and create the labels and options | |
foreach ( $source['data'] as $key => $data) { | |
// set the option in the array | |
$field['config']['option'][] = array( | |
'value' => $data[1], | |
'label' => $data[0] | |
); | |
} | |
// return the field to the form | |
return $field; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have anyone tried on this?