Cray
Cray

Reputation: 5483

Gravity Forms: Dynamically populate field label or placeholder

I want to populate an input field with data from the current user. At the moment I populate the fields value parameter but I want to keep the input empty. Therefore it would be great if I could populate the label or the placeholder parameter of the input field.

I couldn't find anything in the docs.

Here's my current code:

add_filter('gform_field_value_username', create_function("", '$value = populate_usermeta(\'nickname\'); return $value;' ));

Upvotes: 1

Views: 1801

Answers (2)

Dave from Gravity Wiz
Dave from Gravity Wiz

Reputation: 2859

I believe this should work out-of-the-box with Gravity Forms:

Screenshot of field settings with the user merge tag in the placeholder setting

Upvotes: 2

Cray
Cray

Reputation: 5483

With some help from the Gravity Forms support and some own testing, I came up with a solution:

function populate_usermeta($meta_key){
    global $current_user;
    return $current_user->__get($meta_key);
}


add_filter( 'gform_pre_render', 'populate_text' );

//Note: when changing choice values, we also need to use the gform_pre_validation so that the new values are available when validating the field.
add_filter( 'gform_pre_validation', 'populate_text' );

//Note: this will allow for the labels to be used during the submission process in case values are enabled
add_filter( 'gform_pre_submission_filter', 'populate_text' );

function populate_text( $form ) {

    $items = array();

    $fields = $form['fields'];
    foreach( $form['fields'] as &$field ) {

        if ( $field->type != 'text' || strpos( $field->cssClass, 'populate-placeholder' ) === false ) {
            continue;
        }

        $field->placeholder = populate_usermeta($field->inputName);

    }

    return $form;
}

Upvotes: 1

Related Questions