#1576
Vladimir
Keymaster

Code:

// prefill roles at User profile editor Gravity Form fields
add_filter( 'gform_pre_render_10', 'frontend_profile_populate_roles' );


function frontend_profile_populate_roles( $form ) {
    
    foreach ( $form['fields'] as &$field ) {

        if ( $field->type == 'select' && $field->inputName==='primary_role' ) {
            prepare_primary_role_dropdown($field);
        }
        
        if ( $field->type == 'multiselect' && $field->inputName==='secondary_roles' ) {
            prepare_secondary_roles_multiselect($field);
        }
        
    }   // foreach
    
    return $form;
}


function get_primary_role() {
    global $current_user;
    
    if (!empty($current_user->roles)) {
        $roles = array_values($current_user->roles);
        $primary_role = array_shift($roles);
    } else {
        $primary_role = 'do-not-allow';
    }
    
    return $primary_role;
}


function prepare_primary_role_dropdown( &$field ) {
    global $wp_roles;
    
    $primary_role = get_primary_role();    
    $choices = array();    
    foreach ($wp_roles->role_names as $key=>$value) {
        $is_selected = $primary_role===$key;
        $choices[] = array('text'=>$value, 'value'=>$key, 'isSelected'=>$is_selected, 'price'=>0.00);
    }
    $field->choices = $choices;
    
}


function prepare_secondary_roles_multiselect( &$field ) {
    global $current_user, $wp_roles;
        
    $primary_role = get_primary_role();
    $choices = array();
    foreach ($wp_roles->role_names as $key=>$value) {
        if ($key==$primary_role) {
            continue;
        }
        $is_selected = in_array($key, $current_user->roles);
        $choices[] = array('text'=>$value, 'value'=>$key, 'isSelected'=>$is_selected, 'price'=>0.00);
        
    }
    $field->choices = $choices;
}

// update user's roles according to the on form selection
add_action( 'gform_user_updated', 'frontend_profile_change_user_roles', 10, 4);

function frontend_profile_change_user_roles($user_id, $user_config, $entry, $user_pass) {

    $user = new WP_User($user_id);
    $user->set_role($entry[6]); // Primary role
    
    // secondary roles
    if (empty($entry[7])) {
        return;
    }
    $roles = explode(',', $entry[7]);
    foreach($roles as $role) {
        $user->add_role($role);
    }
    
}

10 at the filter name ‘gform_pre_render_10’ is the ID of Gravity Forms form (with user profile fields including roles) linked to the “User Registration” add-on item with ‘update’ action.
Form ID=10 includes 2 roles related fields:
1) “Primary role” drop down field with “Allow field to be populated dynamically” flag turned on and “parameter name” value “primary_role”. It corresponds to the entry[6] at the code above.
2) “Secondary roles” multi select field with “Allow field to be populated dynamically” flag turned on and “parameter name” value “secondary_roles”. It corresponds to the entry[7] at the code above.