GravityForms Hooks To Pre-fill Inputs

The following briefly describes how you can use GravityForms hooks in order to pre-fill any user data (either from WordPress tables themselves, or from a web api server.

  1. Copy the following code into your child theme’s functions.php file (or create a functions.php file).
  2. Edit a desired form field by going to the Advanced tab and checking “Allow field to be populated dynamically”
  3. Then enter one of the bolded options below as the parameter name
  4. Voila, GravityForms should now pre-fill your form inputs automatically based on the current user who is logged in

 

// populate form field(s) with current user’s meta data.  Inspired by https://www.gravityhelp.com/forums/topic/right-parameter-names-to-pre-populate-the-names-fields
add_filter(‘gform_field_value_user_firstname‘, create_function(“”, ‘$value = populate_usermeta(‘first_name’); return $value;’ ));
add_filter(‘gform_field_value_user_lastname‘, create_function(“”, ‘$value = populate_usermeta(‘last_name’); return $value;’ ));
add_filter(‘gform_field_value_user_ename‘, create_function(“”, ‘$value = populate_usermeta(‘user_login’); return $value;’ ));
add_filter(‘gform_field_value_user_email‘, create_function(“”, ‘$value = populate_usermeta(‘user_email’); return $value;’ ));
add_filter(‘gform_field_value_user_name‘, create_function(“”, ‘$value = populate_usermeta(‘display_name’); return $value;’ ));
// populate form field(s) using eName against web api
add_filter(‘gform_field_value_user_phone‘, create_function(“”, ‘$value = populate_fromweid(‘user_login’,’PHONE’); if (IsNullOrEmptyString($value)) $value = populate_fromweid(‘user_login’,’EMPLOYEE_PHONE’); return $value;’ ));
add_filter(‘gform_field_value_user_csuid‘, create_function(“”, ‘$value = populate_fromweid(‘user_login’,’CSU_ID’); return $value;’ ));
add_filter(‘gform_field_value_user_major‘, create_function(“”, ‘$value = populate_fromweid(‘user_login’,’STUDENT_MAJOR’); return $value;’ ));
// this function returns the requested user meta of the current user
function populate_usermeta($meta_key){
    global $current_user;
    return $current_user->__get($meta_key);
}
function populate_fromweid($meta_key, $column){
    global $current_user;
// get username of current user
    $username = $current_user->__get($meta_key);
if (IsNullOrEmptyString($username))
return;
// assemble web api url
$webapi = ‘http://obtainurlfromshaun.colostate.edu/api/weidperson/’ . $username;
// call web api
$response = file_get_contents($webapi);
//$response = new SimpleXMLElement($response);
$json = json_decode($response);
//var_dump($json[0]);
//var_dump($json[0]->ENAME);
if (IsNullOrEmptyString($json))
return;
return $json[0]->$column;
}
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($var){
    return (!isset($var) || trim($var)===”);
}