I was intrigued by this one, so I took a stab at it. Stealing a bit from here and here I came up with the following.
First.. create your dropdown field. Set the single option text to "Add New City" and the value to '' (blank). Click Advanced, and give it a class of "populate-city".
Add a second field below that. GIve it a title of New City. Make a note of the field ID. Set the Conditional tag to only show if your dropdown is set to ADD NEW CITY.
Then, in your functions.php file, add the following:
<?php
// update the '2' in gform_pre_render_2 to the ID of your form
add_filter('gform_pre_render_2', 'populate_cities');
function populate_cities($form){
foreach($form['fields'] as &$field){
if($field['type'] != 'select' || strpos($field['cssClass'], 'populate-city') === false)
continue;
// get previous entries user-added cities
// update the 4 below to the field ID of your "New City" field
$cities = get_entry_field_values(4, $form['id']);
// update 'City Dropdown
$choices = array();
foreach($cities as $city){
$choices[] = array('text' => $city['value'], 'value' => $city['value']);
}
$choices[] = array('text' => 'Add New City', 'value' => '');
$field['choices'] = $choices;
}
return $form;
}
function get_entry_field_values($field_id, $form_id) {
global $wpdb;
$tablename = $wpdb->prefix . 'rg_lead_detail';
return $wpdb->get_results($wpdb->prepare("SELECT value FROM $tablename WHERE form_id = %d AND field_number = %d", $form_id, $field_id), ARRAY_A);
}
?>
You may want to sort the choices array, and check for duplicates, not to mention make sure the formatting [capitalization, etc.] is correct, but I'll leave that up to you. When someone goes to fill out the form, they'll see a list of previously added cities. They can choose that or choose "ADD NEW CITY" and use the input field that appears to enter their city name.
Hope it helps.
Posted 12 years ago on Sunday December 25, 2011 |
Permalink