Autofill Form from Cookies

Hello,

I’d like to be able to automatically save the user’s information they inputed into this form so that when they go back to fill in the form later, they wouldn’t need to fill their first/last name, Instagram username, and email. I found this online but it’s not working.

/* ----- create cookies to remember items for auction gravity forms ----- */
add_action("gform_pre_submission", "pre_submission_handler");
function pre_submission_handler($form_meta) {
$saveVars = array("first", "last", "insta", "email");
foreach($form_meta["fields"] as $field) {
if( $field["allowsPrepopulate"] ){
if( is_array($field["inputs"]) ){
foreach($field["inputs"] as $sub){
$val = $POST["input" . str_replace(".", "", $sub["id"])];
setcookie("gf".$sub["name"], $val, time() + 31536000, COOKIEPATH, COOKIE_DOMAIN, false, true);
}
}else{
$val = $POST["input" . $field["id"]];
setcookie("gf_".$field["inputName"], $val, time() + 31536000, COOKIEPATH, COOKIE_DOMAIN, false, true);
}
}
}
}

add_filter("gform_pre_render", "add_auto_update_filters");
$contego_callbacks = array();
function add_auto_update_filters($form){
foreach($form["fields"] as &$field){
if( $field["allowsPrepopulate"] ){
if( is_array($field["inputs"]) ){
foreach($field["inputs"] as $sub){
$fieldName = $sub["name"];
add_filter("gform_field_value_" . $fieldName, function($f) use ($fieldName){
return $COOKIE["gf" . $f];
});
}
}else{
$fieldName = $field["inputName"];
add_filter("gform_field_value_" . $fieldName, function($f) use ($fieldName){
return $COOKIE["gf" . $f];
});
}

            }
    }
    return $form;
}

//Save the utm_source parameter as a session cookie
function namespace_set_source() {
  GFCommon::log_debug( __METHOD__ . '(): running.' );
  if (isset($_GET['utm_source'])) {
    GFCommon::log_debug( __METHOD__ . '(): There is a GET utm_source.' );
    if (!isset($_COOKIE['utm_source'])) {
      GFCommon::log_debug( __METHOD__ . '(): There is no cookie utm_source.' );
      setcookie('utm_source', $_GET['utm_source']);
    }
  }
}

This form they will be filling out, they will need to fill it out very frequently so I’d prefer if I could autofill it. Here is the form live on my site.

If your custom code is not working, I recommend using the built in logging in Gravity Forms to see what’s going wrong. First please enable logging:

Next, add some custom logging statements to your code. I recommend adding a logging statement inside each loop or conditional, and also after you set any variable or object, to see if it holds the value you think it should. Here is how you can add custom logging to your code, which will be added to the Gravity Forms logs:

With that additional logging, you should be able to see where this is falling apart.

I’m quite new to php so learning as I go, I’ll give that a try then report back, thank you!

1 Like

@chrishajer here is the log after some custom logging statements were added.

2020-05-29 21:59:30.116274 - DEBUG --> namespace_set_source(): running. 
2020-05-29 21:59:31.358433 - DEBUG --> namespace_set_source(): running. 
2020-05-29 21:59:39.615708 - DEBUG --> namespace_set_source(): running. 
2020-05-29 21:59:41.312776 - DEBUG --> namespace_set_source(): running. 
2020-05-29 22:00:01.145946 - DEBUG --> namespace_set_source(): running. 
2020-05-29 22:00:24.529155 - DEBUG --> namespace_set_source(): running. 
2020-05-29 22:00:31.561384 - DEBUG --> namespace_set_source(): running. 
2020-05-29 22:00:38.551335 - DEBUG --> namespace_set_source(): running. 
2020-05-29 22:00:40.407819 - DEBUG --> namespace_set_source(): running. 
2020-05-29 22:00:50.535209 - DEBUG --> namespace_set_source(): running. 
2020-05-29 22:01:34.976718 - DEBUG --> namespace_set_source(): running. 
2020-05-29 22:01:34.992660 - DEBUG --> GFAsyncUpload::upload(): Starting. 
2020-05-29 22:01:34.997714 - DEBUG --> GFAsyncUpload::upload(): File upload complete. temp_filename: e12e9e0e_input_1_o_1e9hl06k81jia79a69kdmqp4sa.png  uploaded_filename: B9A2DFB6-9EAC-496E-8316-BD7DD6E52E04.png  
2020-05-29 22:01:53.843017 - DEBUG --> namespace_set_source(): running. 
2020-05-29 22:01:53.854836 - DEBUG --> GFFormDisplay::process_form(): Starting to process form (#2) submission. 
2020-05-29 22:01:53.855818 - DEBUG --> GFFormDisplay::process_form(): Source page number: 1. Target page number: 0. 
2020-05-29 22:01:53.856642 - DEBUG --> GF_Field_FileUpload::validate(): Validating field input_1 
2020-05-29 22:01:53.856698 - DEBUG --> GF_Field_FileUpload::validate(): Validating file upload for B9A2DFB6-9EAC-496E-8316-BD7DD6E52E04.png 
2020-05-29 22:01:53.856754 - DEBUG --> GF_Field_FileUpload::validate(): Validation complete. 
2020-05-29 22:01:53.963679 - DEBUG --> GFFormDisplay::process_form(): After validation. Is submission valid? Yes. 
2020-05-29 22:01:53.966379 - DEBUG --> GFFormDisplay::process_form(): Submission is valid. Moving forward. 
2020-05-29 22:01:53.966599 - DEBUG --> GFFormsModel::save_entry(): Saving entry. 
2020-05-29 22:01:53.976435 - DEBUG --> GFFormsModel::save_entry(): Entry record created in the database. ID: 27. 
2020-05-29 22:01:53.981549 - DEBUG --> GFFormsModel::save_entry(): Saving entry fields. 
2020-05-29 22:01:53.981724 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: Name(#15.2 - name). 
2020-05-29 22:01:53.981821 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: Name(#15.3 - name). 
2020-05-29 22:01:53.981859 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: Name(#15.4 - name). 
2020-05-29 22:01:53.981894 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: Name(#15.6 - name). 
2020-05-29 22:01:53.981925 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: Name(#15.8 - name). 
2020-05-29 22:01:53.982048 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: How would you like us to display your name?(#12.1 - checkbox). 
2020-05-29 22:01:53.982084 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: How would you like us to display your name?(#12.2 - checkbox). 
2020-05-29 22:01:53.982114 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: How would you like us to display your name?(#12.3 - checkbox). 
2020-05-29 22:01:53.982211 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: Email(#3 - email). 
2020-05-29 22:01:53.982264 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: Who did you control with?(#9 - text). 
2020-05-29 22:01:53.982311 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: What’s something you’d like to say in the description of the post?(#7 - textarea). 
2020-05-29 22:01:53.982358 - DEBUG --> GF_Field_FileUpload::get_multifile_value(): Starting. 
2020-05-29 22:01:53.983700 - DEBUG --> GF_Field_FileUpload::move_temp_file(): Moving temp file from: /home/customer/www/ifatceg.com/public_html/wp-content/uploads/gravity_forms/2-cc3c7dc0ab1ed89612665092e4e57ace/tmp/e12e9e0e_input_1_o_1e9hl06k81jia79a69kdmqp4sa.png 
2020-05-29 22:01:53.984133 - DEBUG --> GF_Field_FileUpload::move_temp_file(): File successfully moved. 
2020-05-29 22:01:53.984169 - DEBUG --> GF_Field_FileUpload::set_permissions(): Setting permissions on: /home/customer/www/ifatceg.com/public_html/wp-content/uploads/gravity_forms/2-cc3c7dc0ab1ed89612665092e4e57ace/2020/05/B9A2DFB6-9EAC-496E-8316-BD7DD6E52E04.png 
2020-05-29 22:01:53.984261 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: Screenshot(#1 - fileupload). 
2020-05-29 22:01:53.984358 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: Permission(#10.1 - consent). 
2020-05-29 22:01:53.984410 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: Permission(#10.2 - consent). 
2020-05-29 22:01:53.984486 - DEBUG --> GFFormsModel::queue_save_input_value(): Queued field operation: Permission(#10.3 - consent). 
2020-05-29 22:01:53.992389 - DEBUG --> GFFormsModel::save_entry(): Finished saving entry fields. 
2020-05-29 22:01:53.992516 - DEBUG --> GFCommon::is_spam_entry(): Is submission considered spam? No. 
2020-05-29 22:01:55.199208 - DEBUG --> GF_Background_Process::dispatch(): Running for gf_feed_processor. 
2020-05-29 22:01:55.202307 - DEBUG --> GF_Background_Process::dispatch(): Unable to dispatch tasks to Admin Ajax: Nothing left to process 
2020-05-29 22:01:55.202383 - DEBUG --> GFFormsModel::create_post(): Starting. 
2020-05-29 22:01:55.202517 - DEBUG --> GFFormsModel::create_post(): Stopping. The form doesn't have any post fields. 
2020-05-29 22:01:55.202544 - DEBUG --> GFAPI::send_notifications(): Gathering notifications for form_submission event for entry #27. 
2020-05-29 22:01:55.202578 - DEBUG --> GFCommon::send_notifications(): Processing notifications for form_submission event for entry #27: Array
(
    [0] => 5ecd61707c9e2
)

(only active/applicable notifications are sent) 
2020-05-29 22:01:55.202600 - DEBUG --> GFCommon::send_notification(): Starting to process notification (#5ecd61707c9e2 - Admin Notification). 
2020-05-29 22:01:55.204771 - DEBUG --> GFCommon::send_email(): Sending email via wp_mail(). 
2020-05-29 22:01:55.204847 - DEBUG --> Array
(
    [to] => trio@ifatceg.com
    [subject] => New Screenshot Submission
    [message] => <html>
	<head>
		<title>New Screenshot Submission</title>
	</head>
	<body>
		<table width="99%" border="0" cellpadding="1" cellspacing="0" bgcolor="#EAEAEA"><tr><td>
                            <table width="100%" border="0" cellpadding="5" cellspacing="0" bgcolor="#FFFFFF">
                            <tr bgcolor="#EAF2FA">
		                                    <td colspan="2">
		                                        <font style="font-family: sans-serif; font-size:12px;"><strong>Name</strong></font>
		                                    </td>
		                               </tr>
		                               <tr bgcolor="#FFFFFF">
		                                    <td width="20">&nbsp;</td>
		                                    <td>
		                                        <font style="font-family: sans-serif; font-size:12px;">Kyle Boas</font>
		                                    </td>
		                               </tr>
		                               <tr bgcolor="#EAF2FA">
		                                    <td colspan="2">
		                                        <font style="font-family: sans-serif; font-size:12px;"><strong>How would you like us to display your name?</strong></font>
		                                    </td>
		                               </tr>
		                               <tr bgcolor="#FFFFFF">
		                                    <td width="20">&nbsp;</td>
		                                    <td>
		                                        <font style="font-family: sans-serif; font-size:12px;"><ul class='bulleted'><li>Full name</li></ul></font>
		                                    </td>
		                               </tr>
		                               <tr bgcolor="#EAF2FA">
		                                    <td colspan="2">
		                                        <font style="font-family: sans-serif; font-size:12px;"><strong>Email</strong></font>
		                                    </td>
		                               </tr>
		                               <tr bgcolor="#FFFFFF">
		                                    <td width="20">&nbsp;</td>
		                                    <td>
		                                        <font style="font-family: sans-serif; font-size:12px;"><a href='mailto:test@test.com'>test@test.com</a></font>
		                                    </td>
		                               </tr>
		                               <tr bgcolor="#EAF2FA">
		                                    <td colspan="2">
		                                        <font style="font-family: sans-serif; font-size:12px;"><strong>Who did you control with?</strong></font>
		                                    </td>
		                               </tr>
		                               <tr bgcolor="#FFFFFF">
		                                    <td width="20">&nbsp;</td>
		                                    <td>
		                                        <font style="font-family: sans-serif; font-size:12px;">Test</font>
		                                    </td>
		                               </tr>
		                               <tr bgcolor="#EAF2FA">
		                                    <td colspan="2">
		                                        <font style="font-family: sans-serif; font-size:12px;"><strong>What’s something you’d like to say in the description of the post?</strong></font>
		                                    </td>
		                               </tr>
		                               <tr bgcolor="#FFFFFF">
		                                    <td width="20">&nbsp;</td>
		                                    <td>
		                                        <font style="font-family: sans-serif; font-size:12px;">Test</font>
		                                    </td>
		                               </tr>
		                               <tr bgcolor="#EAF2FA">
		                                    <td colspan="2">
		                                        <font style="font-family: sans-serif; font-size:12px;"><strong>Screenshot</strong></font>
		                                    </td>
		                               </tr>
		                               <tr bgcolor="#FFFFFF">
		                                    <td width="20">&nbsp;</td>
		                                    <td>
		                                        <font style="font-family: sans-serif; font-size:12px;"><ul><li><a href='https://ifatceg.com/index.php?gf-download=2020%2F05%2FB9A2DFB6-9EAC-496E-8316-BD7DD6E52E04.png&amp;form-id=2&amp;field-id=1&amp;hash=35e5a733244bfb6e483eb131bd27e2ad2c5ed173eb3b5f44cf423e0b5b7c72db' target='_blank' aria-label='Click to view'>B9A2DFB6-9EAC-496E-8316-BD7DD6E52E04.png</a></li></ul></font>
		                                    </td>
		                               </tr>
		                               <tr bgcolor="#EAF2FA">
		                                    <td colspan="2">
		                                        <font style="font-family: sans-serif; font-size:12px;"><strong>Permission</strong></font>
		                                    </td>
		                               </tr>
		                               <tr bgcolor="#FFFFFF">
		                                    <td width="20">&nbsp;</td>
		                                    <td>
		                                        <font style="font-family: sans-serif; font-size:12px;"><img src="https://ifatceg.com/wp-content/plugins/gravityforms/images/tick.png" /> I give you permission and got permission<br /><div class="gfield_consent_description">You give us permission to use all the information and materials you provided and you got permission to send the other controller(s) information if that was provided.</div></font>
		                                    </td>
		                               </tr>
		                               </table>
                        </td>
                   </tr>
               </table>
	</body>
</html>
    [headers] => Array
        (
            [From] => From: "trio@ifatceg.com" <trio@ifatceg.com>
            [Content-type] => Content-type: text/html; charset=UTF-8
        )

    [attachments] => Array
        (
        )

    [abort_email] => 
)
 
2020-05-29 22:01:55.245693 - DEBUG --> GFCommon::send_email(): Result from wp_mail(): 1 
2020-05-29 22:01:55.245805 - DEBUG --> GFCommon::send_email(): WordPress successfully passed the notification email (#5ecd61707c9e2 - Admin Notification) for entry #27 to the sending server. 
2020-05-29 22:01:55.245836 - DEBUG --> GFCommon::send_email(): The WordPress phpmailer_init hook has been detected, usually used by SMTP plugins. It can alter the email setup/content or sending server, and impact the notification deliverability. 
2020-05-29 22:01:55.250653 - DEBUG --> GFFormDisplay::handle_confirmation(): Sending confirmation. 
2020-05-29 22:01:55.250854 - DEBUG --> GFFormDisplay::handle_confirmation(): Executing functions hooked to gform_confirmation. 
2020-05-29 22:01:55.251068 - DEBUG --> GFFormDisplay::handle_confirmation(): Confirmation => <div id='gform_confirmation_wrapper_2' class='gform_confirmation_wrapper '><div id='gform_confirmation_message_2' class='gform_confirmation_message_2 gform_confirmation_message'>You successfully submitted your screenshot. This will be added to a queue to go out on our Instagram. <a href="https://ifatceg.com/sessions/screenshots">Submit another</a></div></div> 
2020-05-29 22:01:55.251099 - DEBUG --> GFFormDisplay::process_form(): Executing functions hooked to gform_after_submission. 
2020-05-29 22:01:58.966957 - DEBUG --> namespace_set_source(): running. 
2020-05-29 22:01:59.390826 - DEBUG --> namespace_set_source(): running. 
2020-05-29 22:02:05.235003 - DEBUG --> namespace_set_source(): running. 
2020-05-29 22:02:12.002273 - DEBUG --> namespace_set_source(): running.

Thanks Kyle. Can you post your modified code with the logging statements, so we can see what we’re looking for? Thank you.

Sorry! Here is what I have currently that is identical to what was used for that log I posted.

/* ----- create cookies to remember items for auction gravity forms ----- */
add_action("gform_pre_submission", "pre_submission_handler");
function pre_submission_handler($form_meta) {
$saveVars = array("first", "last", "insta", "email");
foreach($form_meta["fields"] as $field) {
if( $field["allowsPrepopulate"] ){
if( is_array($field["inputs"]) ){
foreach($field["inputs"] as $sub){
$val = $POST["input" . str_replace(".", "", $sub["id"])];
setcookie("gf".$sub["name"], $val, time() + 31536000, COOKIEPATH, COOKIE_DOMAIN, false, true);
}
}else{
$val = $POST["input" . $field["id"]];
setcookie("gf_".$field["inputName"], $val, time() + 31536000, COOKIEPATH, COOKIE_DOMAIN, false, true);
}
}
}
}

add_filter("gform_pre_render", "add_auto_update_filters");
$contego_callbacks = array();
function add_auto_update_filters($form){
foreach($form["fields"] as &$field){
if( $field["allowsPrepopulate"] ){
if( is_array($field["inputs"]) ){
foreach($field["inputs"] as $sub){
$fieldName = $sub["name"];
add_filter("gform_field_value_" . $fieldName, function($f) use ($fieldName){
return $COOKIE["gf" . $f];
});
}
}else{
$fieldName = $field["inputName"];
add_filter("gform_field_value_" . $fieldName, function($f) use ($fieldName){
return $COOKIE["gf" . $f];
});
}

            }
    }
    return $form;
}

//Save the utm_source parameter as a session cookie
function namespace_set_source() {
  GFCommon::log_debug( __METHOD__ . '(): running.' );
  if (isset($_GET['utm_source'])) {
    GFCommon::log_debug( __METHOD__ . '(): There is a GET utm_source.' );
    if (!isset($_COOKIE['utm_source'])) {
      GFCommon::log_debug( __METHOD__ . '(): There is no cookie utm_source.' );
      setcookie('utm_source', $_GET['utm_source']);
    }
  }
}

//Call the above function
add_action( 'init', 'namespace_set_source' );


//Return the utm_source to Gravity Forms
function namespace_populate_source($value) {
  GFCommon::log_debug( __METHOD__ . '(): Cookies => ' . print_r( $_COOKIE['utm_source'], true ) );
  return $_COOKIE['utm_source'];
}

//Call the above function
add_filter('gform_field_value_source', 'namespace_populate_source');

It kind of seems like I’m going to have the same problem as was seen in this topic but I don’t know what the resolution was. I can’t tell though.

Hi Kyle. You need way more logging than that! I modified your code to clean up the formatting a little and add some more debugging statements. Please try this code instead:

view-source:http://chrishajer.com/cook.php.txt

then test the form to run your code, and post a link to the log file, rather than the log statements. It’s easier to view in the browser that way.

1 Like

Oh ok, thank you for doing that, I tried my best haha.

Successfully added that. Here is the link to the log file: https://ifatceg.com/wp-content/uploads/gravity_forms/logs/gravityforms_0f4b75a34be4ca03831d9b0d29a8adbc346d7e37.txt

I switched to a log in system to autofill because this has been too complicated to figure out.

1 Like

Thanks for the update Kyle.

1 Like

Amazing news! I’m quite stubborn… so after days of changing things I managed to figure this out from this tutorial and it now works. :tada:

See here: ifatceg.com/sessions/screenshots

/* ----- create cookies to remember items for auction gravity forms       ----- */ 
add_action("gform_pre_submission", "pre_submission_handler");
function pre_submission_handler($form_meta) {
  $saveVars = array("first", "last", "insta", "email");
  foreach($form_meta["fields"] as $field) {
    if( $field["allowsPrepopulate"] ){
      if( is_array($field["inputs"]) ){
        foreach($field["inputs"] as $sub){
          $val = $_POST["input_" . str_replace(".", "_", $sub["id"])];
          setcookie("gf_".$sub["name"], $val, time() + 31536000, COOKIEPATH, COOKIE_DOMAIN, false, true);
      }else{
        $val = $_POST["input_" . $field["id"]];
        setcookie("gf_".$field["inputName"], $val, time() + 31536000, COOKIEPATH, COOKIE_DOMAIN, false, true);
      }
    }
  }
}
 
add_filter("gform_pre_render", "add_auto_update_filters");
$contego_callbacks = array();
function add_auto_update_filters($form){
  foreach($form["fields"] as &$field){
    if( $field["allowsPrepopulate"] ){
      if( is_array($field["inputs"]) ){
        foreach($field["inputs"] as $sub){
          $fieldName = $sub["name"];
          add_filter("gform_field_value_" . $fieldName, function($f) use ($fieldName){
            return $_COOKIE["gf_" . $fieldName];
          });
        }
      }else{
        $fieldName = $field["inputName"];
        add_filter("gform_field_value_" . $fieldName, function($f) use ($fieldName){
          return $_COOKIE["gf_" . $fieldName];
        });
      }
 
    }
  }
  return $form;
}
1 Like

Good Job!

perseverance-keep-trying-you-can-do-it

1 Like

Good work, Kyle (@trio)! If you ever want to do this easier in the future, Gravity Forms Easy Passthrough handles this pretty deliciously without any custom code required.

But I know how good it feels to figure something like this out on your own! :smile:

1 Like
© 2008 - 2019. Gravity Forms is a project by Rocketgenius Inc.