Dynamically Populating User Role
Use this snippet in conjunction with Gravity Forms dynamic population functionality to populate the current user’s role into any form field.
Read the WalkthroughCode
Filename: gw-dynamically-populating-user-role.php
<?php
/**
* Gravity Wiz // Gravity Forms // Dynamically Populating User Role
* https://gravitywiz.com/dynamically-populating-user-role/
*
* Use this snippet in conjunction with Gravity Forms dynamic population
* functionality to populate the current user’s role into any form field.
*
* @version 1.0
* @author David Smith <david@gravitywiz.com>
* @license GPL-2.0+
* @link https://gravitywiz.com/
*/
add_filter( 'gform_field_value_user_role', 'gform_populate_user_role' );
function gform_populate_user_role( $value ) {
$user = wp_get_current_user();
$role = $user->roles;
return reset( $role );
}
Does this work with GravityView (data tables)? When I edit the entry, it shows the original submitter’s role and not the current logged-in user’s role. I’m trying to figure out if I have a plugin conflict or if the functionality of it updating during edit is possible. I have a hidden field that I want to use conditional logic with based on the current logged-in user’s role.
Hi Matt,
Within GravityView, the field will show the value that is stored when the user initially submits the form, so what you’re experiencing is the expected behaviour. You’ll need to use a different solution, since you want to get the role of the currently logged-in user in GravityView. The new solution will require using GP Populate Anything Perk, to populate the field with the role of the currently logged-in user, and then use this snippet to force the field to rehydrate when editing the entry to get the role of the currently logged-in user.
I hope this helps. However, if this isn’t still working for you, please contact us via our support form so we can have a closer look at your setup and assist you to get it working.
Best,