I set up a new function today to auto-populate a dropdown select with years ranging from a preset start (1940) to (current year - 18). It works and I’ll post the code here in case it does anyone else any good. It’s based on a GF doc on how to auto-populate a dropdown.
Two questions:
-
This works great. Oddly though, if I go to the form to change something in that field (like field size) I can’t access it. I click and nothing happens. If I temporarily remove the code, I can make the change, but when I put the code back in functions.php I can’t access that field in GF anymore.
-
Is there, or should there be, a section in the forum where people can post snippets and functions and such that they’ve done that don’t need help…but can be a library of starter code and ideas?
Here’s the function:
//AUTOPOPULATE THE YEAR OF BIRTH DROP DOWN SELECT
//FOR 1940 THROUGH (CURRENT YEAR-18)
//FOR FORM 6
add_filter( 'gform_pre_render_6', 'populate_year' );
add_filter( 'gform_pre_validation_6', 'populate_year' );
add_filter( 'gform_pre_submission_filter_6', 'populate_year' );
add_filter( 'gform_admin_pre_render_6', 'populate_year' );
function populate_year( $form ) {
foreach ( $form['fields'] as &$field ) {
//WILL WORK ON SELECT FIELD HAVING CSS CLASS OF 'populate-year'
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-year' ) === false ) {
continue;
}
// YEAR TO START AT
$earliest_year = 1940;
// LATEST YEAR IN THE RANGE (CURRENT YEAR-18)
$latest_year = date('Y')-18;
$choices = array();
// LOOPS OVER EACH YEAR int[year] from current year, back to the $earliest_year [1940]
foreach ( range( $latest_year, $earliest_year ) as $i ) {
//CREATE GF ARRAY
$choices[] = array( 'text' => $i, 'value' => $i );
}
// ADD 'Select Year of Birth'
$field->placeholder = 'Select Year of Birth';
$field->choices = $choices;
}
return $form;
}