Pass arbitrary values through to a form

Created by Phil Kurth, Modified on Fri, 01 Jul 2022 at 01:34 PM by Phil Kurth

When displaying a form it's possible to pass custom form args to both the shortcode and the function. These args and their corresponding values will then be available for use inside custom hooked functions. 


Note: to avoid clashes with existing or future core form args, we suggest you prefix your arguments. e.g; instead of user_name choose a prefix relevant to your project/company. i.e; xyz_user_name. Doing so will ensure your custom form args continue to function without compatibility issues with Advanced Forms.


Passing values via the shortcode

If using the shortcode, you custom args would look as follows:

[advanced_form form="YOUR_FORM_KEY_HERE" xyz_user_name="some value here"]

Note that when using the shortcode, you won't have the same level of flexibility as when using PHP as the value cannot be dynamic. 


Passing values via the function

Using the function offers the most flexibility as it allows you to send dynamic data into the function. e.g; 

advanced_form( 'YOUR_FORM_KEY_HERE', [
  'xyz_user_name' => wp_get_current_user()->user_login
] );


Using the values

The custom args will be available anywhere the form's arguments are passed which is the case in most hook/filter callbacks. The following example demonstrates this in a custom submission handler: 

add_action( 'af/form/submission', function ( $form, $fields, $args ) {
  // If we need to run this only on a specific form, check for the form key.
  if ( $form['key'] !== 'YOUR_FORM_KEY_HERE' ) {
    return;
  }

  // Check if our custom variable is available.
  if ( isset( $args['xyz_user_name'] ) ) {

    // Do something with $args['some_key'] …

  }

}, 10, 3 );

If you have a scenario where the form args are not provided, you can access the same data on the global AF instance. e.g; 

add_action( 'af/form/submission', function ( $form, $fields, $args ) {

  // Note that if not processing a submission, AF()->submission will be NULL so factor that into your handler.
  if ( AF()->submission !== null ) {
    $value = AF()->submission['args']['xyz_user_name'] ?? null;
  }

}, 10, 3 );

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select atleast one of the reasons

Feedback sent

We appreciate your effort and will try to fix the article