Dynamically populating field labels

I have tested dynamically populating fields using the various snippets of code getting about and they seem to work fine. But would there be a good snippet of code for populating field labels? Specifically, I am wanting to add the post name with other text to the consent and checkbox field labels.

1 Like

I don’t have a snippet available for setting a field label dynamically. However, you could always use the gform_pre_render filter as shown here:

Note that you need to use four filters to ensure the label is updated everywhere:

The gform_pre_render filter is executed before the form is displayed and can be used to manipulate the Form Object prior to rendering the form.

This filter should be used in conjunction with the gform_pre_validation, gform_pre_submission_filter, and gform_admin_pre_render filters to update the Form Object to be able to use those values elsewhere (merge tags in the confirmation and notification, for example).

You would be setting the field label like this:

$form['fields'][0]['label'] = $something;

Or, there is a plugin available which can handle all this and more:

/** Modify the fields . */
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)
{

    // Consent fields.
    foreach ($form['fields'] as &$field) {
        if ('consent' === $field['type']) {
            $field['checkboxLabel'] = 'Consent Text';
        }
    }

    return $form;
}
1 Like