Skip to content

Instantly share code, notes, and snippets.

@DavidCramer
Last active September 13, 2017 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidCramer/a932ab836978eec58145 to your computer and use it in GitHub Desktop.
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
<?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;
}
@august2017
Copy link

Have anyone tried on this?

@intanandani
Copy link

Yep, its works..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment