I have two select menus built with Gravityforms and I am trying to use the filters below to dynamically populate them with WooCommerce order ids and WooCommerce products. The first foreach loop works as expected. I thought I could the replicate the loop for the second select menu. The queries work as I have tried them in a non-gravityforms form.
I suspect its the variable names I’m using in the second loop?
add_filter('gform_pre_render', 'populate_rma_dropdowns');
add_filter( 'gform_pre_validation', 'populate_rma_dropdowns' );
add_filter( 'gform_admin_pre_render', 'populate_rma_dropdowns' );
add_filter( 'gform_pre_submission_filter', 'populate_rma_dropdowns' );
function populate_rma_dropdowns( $form ) {
if ( $form['title'] != "RMA" ) return $form;
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'order-list' ) === false ) {
continue;
}
$query = new WC_Order_Query( array(
'limit' => -1,
'orderby' => 'date',
'order' => 'DESC',
'return' => 'ids',
) );
$orders = $query->get_orders();
$choices = array(array('text' => 'Please find your order number', 'value' => 0 ));
foreach ( $orders as $order ) {
$choices[] = array( 'text' => $order, 'value' => $order, 'isSelected' => false );
}
$field['choices'] = $choices;
}
foreach ( $form['fields'] as &$field2 ) {
if ( $field2->type != 'select' || strpos( $field2->cssClass, 'product-list' ) === false ) {
continue;
}
$args2 = array( 'post_type' => 'product' ,'posts_per_page' => 100);
$products = get_posts( $args2 );
$choices2 = array(array('text' => 'Please select product', 'value' => 0 ));
foreach ( $products as $product ) {
$choices2[] = array( 'text' => $product->post_title, 'value' => $product->post_title, 'isSelected' => false );
}
$field2['choices2'] = $choices2;
}
return $form;
}
2
Answers
I've fixed this: in the second foreach loop I had added a number to the &$field array element
@Marc was correct as well about his suggestion as well. Both drop downs now work as required.
Looks like you’ve made a small typo in the second loop. You’re setting
$field2['choices2']
rather than$field2['choices']