When you create a product field in Gravity Forms, you have the option of displaying a quantity field with the product. Using the form editor you can disable the quantity field, but what if you want to auto populate the quantity amount? Using the advanced settings and a bit of code, this is easily done.
Set a Default Value for the Quantity of a Product Field
1. In the form editor, go to the Advanced tab of product field and check “Allow field to be populated dynamically”.
2. Enter a value for “parameter name” next to the quantity setting. This value is what we’ll use in our function to set the default quantity amount for the product.
3. Open your functions.php file or functionality plugin and add the following snippet:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( 'gform_field_value_default_quantity', 'endo_set_default_quantity' ); | |
function endo_set_default_quantity() { | |
return 1; // change this number to whatever you want the default quantity to be | |
} |
The filter we are using is gform_field_value_$parameter_value, where $parameter_value is the value we set in the Advanced tab of the product field. This allows you to specify the exact quantity field you want to set, even if you have multiple product fields in the form or in other forms.
In our callback function ‘endo_set_default_quantity’, we return the default value that we want to set for the quantity of the product field. You don’t have to set it to 1. You could set it to 5, 50, or 5000. The user can still manually change the value before they submit the form.
That’s it. Now the quantity field of the product will have a default value when your user fills out the payment form.
hello,
Just found this and tried to use it, but it doesn’t seem to work for me. Is there a change in the code snippet that’s needed?
Trying to use it here – http://pwclassic.com/registration/
In the ‘other tickets’ section of the form.
Any help is appreciated.
thx!
-matt