Search code examples
phpwordpressgravity-forms-plugin

How to submit an outside variable to Gravity Forms through WP filter


This type of work is new to me, so please be patient if the answer is something easy.

I'm using Wordpress and Gravity Forms on my site, and I want to pre-populate the form with data from an object (the object comes from an API, so I can't just use wordpress current_user object).

How can I use an outside variable inside a wordpress filter?

For Example:

$fname = $object->first_name;
add_filter('gform_field_value_firstname', *Populate the field with $fname*);

The below is the normal usage of the function, from Gravity Forms Docs (http://www.gravityhelp.com/documentation/page/Gform_field_value_$parameter_name)

add_filter('gform_field_value_firstname', "dothis");

Where "dothis" points to a function.

The below also works (based on this excellent article: http://www.doitwithwp.com/pre-populate-fields-using-gravity-forms/):

add_filter('gform_field_value_firstname', create_function("", 'return "John";' ));

However, I can't figure out how to get it to accept an outside variable also. For example, I'd like to do:

$fname = $object->first_name;
add_filter('gform_field_value_firstname', create_function("", 'return $fname;' ));

But php tells me that fname is an undefined variable.

I've reviewed this thread PHP: How to make variable visible in create_function()? , but I could not get the Closure solutions to work. I have PHP Version 5.2.17.

Would you please post an example of how to do this correctly?


Solution

  • Make $fname a global variable and you can reference it in your create_function as a global.

    global $fname = $object->first_name;
    add_filter( 'gform_field_value_firstname', create_function( '', 'global $fname; return $fname;' ) );
    

    However if you have multiple values to return, it's better to make $object global:

    global $object;
    add_filter( 'gform_field_value_firstname', create_function( '', 'global $object; return 
    $object->first_name;' ));
    add_filter( 'gform_field_value_lastname', create_function( '', 'global $object; return $object->last_name;' ));
    

    And so on...