I'm writing a rating system using Gravity Forms. Next to each post is a "Vote" link which opens a lightbox with a Gravity Forms shortcode in it. The shortcode populates two hidden fields - the Post ID and the User ID:
[gravityform id="2" field_values="gf_rating_post=123&gf_rating_user=456" title="false" description="false" ajax="true" tabindex="49"]
Inside the form are dropdown menus to rate the various elements, from 1-10. I'm trying to write code to insert SELECTED with the previously selected value from the dropdown, but I need to be able to reference the Post ID in order to retrieve that previously selected value.
add_filter('gform_pre_render_2', 'ac_populate_post_ratings');
add_filter('gform_pre_validation_2', 'ac_populate_post_ratings');
add_filter('gform_pre_submission_filter_2', 'ac_populate_post_ratings');
add_filter('gform_admin_pre_render_2', 'ac_populate_post_ratings');
function ac_populate_post_ratings($form) {
foreach ( $form['fields'] as &$field ) {
if ( $field->type != "select" || strpos( $field->cssClass, 'populate-posts' ) ) {
continue;
}
$choices = $field->choices;
foreach ( $choices as $choice ) {
// echo "defaultValue: " . $field->defaultValue . "<br />";
$newchoices[] = array( 'text' => $choice['text'], 'value' => $choice['value'] );
}
$field->choices = $newchoices;
}
return $form;
}
It seems that because the Post ID value is dynamically added to the form, it isn't able to be referenced using the field's defaultValue, which is always empty even though when you view the source, the input value is set correctly.
Any ideas how I can reference that Post ID inside the ac_populate_post_ratings()
function?
As a last ditch effect, I contacted Gravity Forms support, and they came through with the goods.
The field defaultValue
property will only contain a value if you have configured that setting in the form editor. Values which are being dynamically populated are not available from the $form
.
The gform_pre_render
filter is passed the dynamic population values from the shortcode in its third param.
I needed to change this line:
add_filter('gform_pre_render_2', 'ac_populate_post_ratings');`
to this:
add_filter('gform_pre_render_2', 'ac_populate_post_ratings', 10, 3 );`
And this line:
function ac_populate_post_ratings($form) {
to this:
function ac_populate_post_ratings( $form, $ajax = false, $field_values = array() ) {
And now I can access the values like so:
$gf_rating_post = rgar( $field_values, 'gf_rating_post' );