Skip to content

Instantly share code, notes, and snippets.

@esoileme
Created May 23, 2018 11:06
Show Gist options
  • Save esoileme/4c7a7be7ff47b44c0e5eb2a5ac484a90 to your computer and use it in GitHub Desktop.
Save esoileme/4c7a7be7ff47b44c0e5eb2a5ac484a90 to your computer and use it in GitHub Desktop.
Gravity Forms - Fill dropdown with custom fields
/*Get the Page id as parameter from the link and fill dropdowns with the custom fields that you need from this page
We use gravity forms, and field Product (type dropdown).
In this example in pages there are parameters as date1, date2 etc and prices like price (default price) price1, price2 etc.
The form with id 3 will be filled with the above parameters and corresponding prices, if there is no corresponding price default price will be filled in.
*/
add_filter( 'gform_pre_render_3', 'populate_dates' );
add_filter( 'gform_pre_validation_3', 'populate_dates' );
add_filter( 'gform_pre_submission_filter_3', 'populate_dates' );
add_filter( 'gform_admin_pre_render_3', 'populate_dates' );
function populate_dates( $form ) {
if (isset($_GET['post_id'])) {
$post_id = $_GET['post_id'];
} else {
$post_id = '0';
}
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'product' || strpos( $field->cssClass, 'populate-dates' ) === false ) {
continue;
}
$the_date = array();
$the_price = array();
$DatesArr = array();
for($i=0;$i<10;$i++)
{
$the_date[$i] = get_post_meta($post_id, 'date' . $i);
if(!empty($the_date[$i]))
{
array_push($DatesArr, $the_date[$i][0]);
}
}
$choices = array();
foreach ( $DatesArr as $Date ) {
for($i=0;$i<10;$i++)
{
if($Date === $the_date[$i][0]) {
$price = get_post_meta($post_id, 'price' . $i);
}
}
if(empty($price))
{
$price = get_post_meta($post_id, 'price');
}
$choices[] = array( 'text' => $Date, 'value' => $Date, 'price' => $price[0] );
}
$field->placeholder = 'Select a Date';
$field->choices = $choices;
}
return $form;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment