July 27, 2020: Fixed issue where script could be run before jQuery was loaded.
April 25, 2020: Added compatibility for the GravityView Edit Entry screen.
August 22, 2019: Fixed intermittent issue where loading script in Gravity Forms Gutenberg block caused Parent Selector to disappear.
October 5, 2013: Updated snippet to use a class format for easier instantiation which also adds support for applying to multiple forms and multiple fields on the same form.
January 26, 2013: Updated to better select the current list field table rows.
<?php | |
/** | |
* Gravity Wiz // Gravity Forms // Set Number of List Field Rows by Field Value | |
* | |
* Add/remove list field rows automatically based on the value entered in the specified field. Removes the add/remove | |
* that normally buttons next to List field rows. | |
* | |
* @version 1.3 | |
* @author David Smith <david@gravitywiz.com> | |
* @license GPL-2.0+ | |
* @link http://gravitywiz.com/2012/06/03/set-number-of-list-field-rows-by-field-value/ | |
*/ | |
class GWAutoListFieldRows { | |
private static $_is_script_output; | |
public function __construct( $args = array() ) { | |
// set our default arguments, parse against the provided arguments, and store for use throughout the class | |
$this->_args = wp_parse_args( $args, array( | |
'form_id' => false, | |
'input_html_id' => false, | |
'list_field_id' => false | |
) ); | |
// do version check in the init to make sure if GF is going to be loaded, it is already loaded | |
add_action( 'init', array( $this, 'init' ) ); | |
} | |
public function init() { | |
// make sure we're running the required minimum version of Gravity Forms | |
if( ! property_exists( 'GFCommon', 'version' ) || ! version_compare( GFCommon::$version, '1.8', '>=' ) ) { | |
return; | |
} | |
// time for hooks | |
add_filter( 'gform_pre_render', array( $this, 'load_form_script' ), 10, 2 ); | |
add_filter( 'gform_register_init_scripts', array( $this, 'add_init_script' ), 10, 2 ); | |
} | |
public function load_form_script( $form, $is_ajax_enabled ) { | |
if( $this->is_applicable_form( $form ) && ! has_action( 'wp_footer', array( $this, 'output_script' ) ) ) { | |
add_action( 'wp_footer', array( $this, 'output_script' ) ); | |
add_action( 'gform_preview_footer', array( $this, 'output_script' ) ); | |
} | |
return $form; | |
} | |
public function output_script() { | |
?> | |
<script type="text/javascript"> | |
window.gwalfr; | |
(function($){ | |
gwalfr = function( args ) { | |
this.formId = args.formId, | |
this.listFieldId = args.listFieldId, | |
this.inputHtmlId = args.inputHtmlId; | |
this.init = function() { | |
var gwalfr = this, | |
triggerInput = $( this.inputHtmlId ); | |
// update rows on page load | |
this.updateListItems( triggerInput, this.listFieldId, this.formId ); | |
// update rows when field value changes | |
triggerInput.change(function(){ | |
gwalfr.updateListItems( $(this), gwalfr.listFieldId, gwalfr.formId ); | |
}); | |
} | |
this.updateListItems = function( elem, listFieldId, formId ) { | |
var listField = $( '#field_' + formId + '_' + listFieldId ), | |
count = parseInt( elem.val() ); | |
rowCount = listField.find( 'table.gfield_list tbody tr' ).length, | |
diff = count - rowCount; | |
if( diff > 0 ) { | |
for( var i = 0; i < diff; i++ ) { | |
listField.find( '.add_list_item:last' ).click(); | |
} | |
} else { | |
// make sure we never delete all rows | |
if( rowCount + diff == 0 ) | |
diff++; | |
for( var i = diff; i < 0; i++ ) { | |
listField.find( '.delete_list_item:last' ).click(); | |
} | |
} | |
} | |
this.init(); | |
} | |
})(jQuery); | |
</script> | |
<?php | |
} | |
public function add_init_script( $form ) { | |
if( ! $this->is_applicable_form( $form ) ) { | |
return; | |
} | |
$args = array( | |
'formId' => $this->_args['form_id'], | |
'listFieldId' => $this->_args['list_field_id'], | |
'inputHtmlId' => $this->_args['input_html_id'] | |
); | |
$script = "new gwalfr(" . json_encode( $args ) . ");"; | |
$key = implode( '_', $args ); | |
GFFormDisplay::add_init_script( $form['id'], 'gwalfr_' . $key , GFFormDisplay::ON_PAGE_RENDER, $script ); | |
} | |
public function is_applicable_form( $form ) { | |
$form_id = isset( $form['id'] ) ? $form['id'] : $form; | |
return empty( $this->_args['form_id'] ) || $form_id == $this->_args['form_id']; | |
} | |
} | |
// EXAMPLE #1: Number field for the "input_html_id" | |
new GWAutoListFieldRows( array( | |
'form_id' => 240, | |
'list_field_id' => 3, | |
'input_html_id' => '#input_240_4' | |
) ); | |
// EXAMPLE #2: Single Product Field's Quantity input as the "input_html_id" | |
new GWAutoListFieldRows( array( | |
'form_id' => 240, | |
'list_field_id' => 6, | |
'input_html_id' => '#ginput_quantity_240_5' | |
) ); |
Found this interesting question on the Gravity Forms forum:
I’m selling tickets. So each ticket needs to be associated with a name/email/etc…
Basically, the user needs a way to gather a set of data per ordered product/ticket. My first instinct was to simply recommend using the List field. The user could specify the number of tickets and then add/remove however many rows they need.
I kept thinking on it and realized it would be really nice if the number of List field rows increased/decreased automatically based on the number of selected tickets. Here’s a snippet to do just that!
How do I install this snippet?
Just copy and paste the snippet above into your theme’s functions.php file.
Do I need to modify this snippet to work with my form?
You just need to create your own instance of the GWAutoListFieldRows
class. You’ll find two examples at the bottom of the snippet. Comment them out and then add your own! All you need to set is the $form_id
, the $list_field_id
, and the HTML id of your input as the $input_html_id
property.
Did this resource help you do something awesome with Gravity Forms? Then you'll absolutely love Gravity Perks; a suite of 32+ essential add-ons for Gravity Forms with support you can count on.
hi thank you for you good snippet how can I find $list_field_id and $input_html_id and what are they? thanks
Hello Zoheir, To make this snippet work, all you need to set is the $form_id, the $list_field_id, and the HTML id of your input as the $input_html_id property. These will be within your personal form. So you forms ID will be the form_id. The field id that contains the list will be the list_field_id and the HTML Field ID on your form will be marked as the input_html_id_property;. Hopefully that clears things up.
I have created a woo-commerce frontend product submission form by gravity form plugin. When I uploaded everything is working fine except product gallery images not showing on the product page. I have used _product_image_gallery filed to upload the product images and uploading without any error but not showing on the product page can anyone help me to sort out this advance thanks.
Hi Rajab,
To successfully upload images to the WooCommerce Product Gallery, you’ll need to enable our GP Media Library Perk on the File Upload Field. This way, all images uploaded via the GF file Upload field are also uploaded into WordPress Media Library, making it possible for it to display on the product page.
Best,
Hi there, Is there any way to add the product field in these list fields? So that it can be repeated.
Hi Sarmad,
We don’t have an exact solution to add a product field into List fields, but a workaround would be to use the Nested Forms to handle this. Basically, you’d create a child form that includes your Drop Down Product field in it, and users can add as many entries to that child form. You may want to check out our documentation on Nested Form and how it works.
Best,
Unfortunately this doesn’t validate if all fields are filled out, let alone if the email field is in fact an email address. I had so much hope for this snippet. :(
Hello Claire, we are sorry that this did not resolve your issue. You could set all fields to Required to validate that all fields are filled out and for email address, are you currently using an Email Field? Let us know about your setup so we can help you out with this one. 😃
I used your “download code” button. The beginning now looks like this:
class GWAutoListFieldRows {
etc…(nothing else changed)
Hello Nicholas, thank you for that information. When using the snippet, You just need to create your own instance of the GWAutoListFieldRows class. You’ll find two examples at the bottom of the snippet. Comment them out and then add your own! All you need to set is the $form_id, the $list_field_id, and the HTML id of your input as the $input_html_id property.
// EXAMPLE #1: Number field for the "input_html_id" new GWAutoListFieldRows( array( 'form_id' => 240, 'list_field_id' => 3, 'input_html_id' => '#input_240_4' ) );
// EXAMPLE #2: Single Product Field's Quantity input as the "input_html_id" new GWAutoListFieldRows( array( 'form_id' => 240, 'list_field_id' => 6, 'input_html_id' => '#ginput_quantity_240_5' ) );
No need to change the code at the top. If you have a Gravity Perks license we would be more than happy to take a deeper dive into your forms. You could drop us a line through our support channel here. Thanks! 😃
Reading all the comments about how easy this was to implement, I am feeling a right twit because nothing seems to happen.
1) I copied the code snippet to my child functions.php file. 2) I removed the leading <!PHP 3) I configured the inputs:
Where 32 is the ID of my list field and 63 the ID of my source number field. The source field appears just above the list field.
The changes to functions.php saved without errors.
It seems to have exactly NO effect on my form: the list field still displays the +/- buttons and the value entered in the source number field doesn’t change the number of list field rows.
I’m probably doing or overlooking something very obvious and stupid. I would appreciate any thoughts/help.
I should add that I can see no errors and AJAX is not enabled.
Hello Nicholas, I am sorry that you are having this issue. I see that you have done things correctly. Are you keeping the whole configuration?
new GWAutoListFieldRows( array( 'form_id' => 18, 'list_field_id' => 32, 'input_html_id' => '#input_18_63' ) );
I just tested the code and everything seems to be working correctly on my end. Could you ensure that you have included the function at the top of the configuration as well as matched the formating? Thank you! 😃Hello Gravitywiz Team,
I’m looking for your solution(https://gravitywiz.com/set-number-of-list-field-rows-by-field-value/) for showing row from passing value in a text field.
But I’m used ajax gravity form so that js code added in above the Html start so it is pushing the jquery error and then my custom js not work on that form.
output_script() js function called in above the html after clicking next.
We are used save and continue form with ajax.
Without ajax is working fine but we need to use ajax form as our client requirement.
Looking for your help.
Hello Lalit, could you please try our Custom JavaScript plugin and see if you are still experiencing this issue. This plugin allows you to easily add custom JavaScript to your Gravity Forms that loads in the appropriate context and doesn’t interfere with other AJAX-enabled forms. Thanks!
How do I make all additional fields required. If I now fill in 1 field (it doesn’t matter which field), the visitor does not have to fill in the rest of the fields. How can I add this requirement. The visitor must complete all fields.
Hello Eduard, Excellent question. We just updated the documentation with this and you can make all field required by using this awesome snippet. 😀
Hi there,
I noticed there is a dangerous issue with running this using a vanilla quantity field. If a user accidentally (or on purpose for that matter) enters a huge quantity (2000) it will crash the browser as it tries to render 2000 input boxes. The solution is to enable drop down selection on the quantity field or use a JavaScript input mask to limit the input. It might be worth warning people about that.
I was also trying to use this snippet with http://gravitywiz.com/better-inventory-with-gravity-forms/ but the stock validation doesn’t seem to work when you combine the two snippets. When combined it still lets you select inputs when there isn’t enough stock and you are using two products on one form. When there is no stock the field disables but a user can still use the submission button. When there is no stock you get the out of stock message displayed correctly and the list input is disabled but the total price acts as if you have one item selected and it allows you to continue to submission. I can’t disable the form because there are other products with stock that need to be sold. I’ve tried setting the default value in the quantity field as 0, I’ve tried setting the default selection as zero. I’ve tried to also set the default value of the product field as zero with a php function rather than gravity forms form GUI. But every time it runs out of stock it defaults the value to 1 unit and allows you to submit.
I don’t know enough about php coding on WordPress to build this from the ground up. My guess is it is something to do with how the list item is first being called. It defaults to one item when the solution to this issue is to set the starting default as zero. I believe there needs to be an amendment to the “Set Number of List Field Rows by Field Value” snippet.
Hey Nick, that’s a good call. I’ve added this to the bug list for this snippet. We’ll get it in the queue to be addressed in the code.
Do you have an example of your Better-Inventory-enabled form? Also, if you could include your configuration of the Better Inventory snippet via a snippi, that’d be very helpful.
Also, if you’re a Gravity Perks customer, feel free to submit a support ticket for faster response times.
Hi, great snippet except it is beyond my mental understanding to a large degree.
https://athenainsurance.com/small-group-health/
I am not understanding how to modify what and where.
Please help
Hi Steve, this might help: https://gravitywiz.com/documentation/snippet-troubleshooting/
That does not help me.
The code-based approach is not for everyone. You might be interested in the plugin version that requires no code interaction. It’s called GP Auto List Field and is available by request to Gravity Perks license holders.
Hi, I have just discovered that when I include this code in my functions.php, the Parent Page selector disappears in under Page Attributes when editing a Page. It makes no sense since the snippet should only impact the form, not the page editor. The form itself works fine with the snippet.
I’m wondering if it has anything to do with the (jQuery) call in the function because there was a second snippet that also causes this error and it also included Javascript.
https://docs.gravityforms.com/making-a-field-read-only/
I created a pared down site using just this code snippet in the Twentynineteen theme to confirm that it’s not a problem with my theme. The site is password protected but I can send the login info if you are interested in taking a look at this unusual error.
Forgot to mention that the site is up to date with the latest WP and plugins. PHP 7.2.9 MySQL 5.7.23 WP v5.2.2
Hi Jennifer, if you’re a Gravity Perks customer, we’ll be happy to take a look at your site via the support form.
Hello, I’m trying to get this to work, but it shows a 404 error. I’m confused about the input_html_id… If my form id is 63 and my number field is 29, should it be:
‘input_html_id’ => ‘#input_63_29’
Or am I missing something? Do I need to add anything to the field itself?
I’m trying to use this to count the number of rows in my list field so that I can use conditional logic to show file upload fields. I’m using Slim Image Cropper, which doesn’t allow multiple file uploads, so I need to dynamically show these fields based on how many rows there are in a list field. Unfortunately I can’t say “if there are 4 rows, show 4 file upload fields”, so this is my more complicated workaround.
Thank you!
Hi Sarah, this doesn’t count the rows, it sets the rows. If you enter 4 in the number field, it adds 4 rows to the corresponding List field. The demo has a good example.
Sorry, I couldn’t reply to my previous comment… I’m aware it sets the rows, I just have further plans for it once I get it to work.
Problem is, I can’t get this to work. I suspect it’s the $input_html_id…
Using Example 1, if my form id is 63, my list field id is 16, and my number field is 27, should it be:
new GWAutoListFieldRows( array( ‘form_id’ => 63, ‘list_field_id’ => 16, ‘input_html_id’ => ‘#input_63_27’ ) );
Using this gives me a 503 Service Unavailable error…
Thank you!
Forgive my ignorance, but is there a syntax error on line 37? It’s highlighted in red.
Hey Sarah, your config looks right based on the field IDs. The red highlight is just the syntax highlighter getting a little confused. The syntax is valid.
I also confirmed that the demo is still working. If you’re still having trouble getting this working on your end, we do have a plugin version of this functionality available for our Gravity Perks customers.
Hi, Right now I am using this function as you have describe here and it works perfect. The user enters a number in a field and the same number of rows is shown. But how about this. Before number of rows the user select between 4 different settings as radio buttons and this will then create the number of columns the list field will generate.
Like this: Order shirts for the team!
Printing: – None – Name – Number – Name and Number
Number of shirts:
If the customer choose “Name” and 8 shirts, the list filed shows 2 columns (Name and size (Dropdown) and 8 rows. If the customer choose “Name and Number” and 4 shorts the list field shows 3 columns (Name, number and size (Dropdown) and 4 rows.
The Dropdown and number of rows is already in place and is working. Any idea about the conditional columns function?
Thanks! Fredrik Sundlöf
Hi Fredrik, this is a cool idea. We don’t have a ready solution for this but definitely something we’ll consider for a future version of this snippet.
I did solve this by creating multiply list fields with the different columns that I wanted and then show each at a time with conditional logic from the radio buttons.
:)
Clever! I like it. ?
I’m trying to run two instances of the code in one form. The first instance is running fine. But the second is not working. I double checked the field Id’s and everything seems to be correct. Any ideas??
new GWAutoListFieldRows( array( ‘form_id’ => 8, ‘list_field_id’ => 22, ‘input_html_id’ => ‘#ginput_quantity_8_16’ ) );
new GWAutoListFieldRows( array( ‘form_id’ => 8, ‘list_field_id’ => 20, ‘input_html_id’ => ‘#ginput_quantity_8_24’ ) );
Hi Adam, I tested this configuration locally and it works as expected. Just FYI, if you’re a Gravity Perks customer, you may be interested in our early-access GF Auto List Field perk available by request. It provides this same functionality but without the need to touch code.
hello there,
i don;t know if this forum is active, but im confused about $input_html_id where to find it? sorry im non dev guy.
THere’s not a great way to fetch the input’s HTML ID without viewing the source of the form. It’ll look something like this: https://gwiz.io/2Be3HvJ If you’d prefer to not touch any code, we do have a plugin version of this available to Gravity Perks users by request.
Hey David, Is this perk still available? I don’t see it in the list. -Rich
Hi Rich, it is an early-access perk, available by request for Gravity Perks users. ?
David, I would be interested in this as a perk. It’s a neat snippet with some scope for improvement. Please keep up work on this one.
Drop us a line via support, Nick. We’ll be happy to get you a copy.
EDIT: Add the following CSS:
field_X_XXX .gfield_list_icons { display: none; }
Hello! How do I put a value in the fields of this listing мф JS? For example, this does not work
$jq(‘.gfield_list_2_cell0 :input’).val(start);
How can I enable the “add” and “remove” buttons to show in the same form for another list field that is not using this script to function?
Do you have a URL where I could see this issue?
Is there a way to just indicate the number of list field rows that should be shown upon page load? My form will not have another field to indicate the number of rows required… I just need to show a minimum number of them for aesthetic purposes.
I don’t need/ wouldn’t want them to be required fields.
Just need say five rows to be shown on page-load, and allow the user to add more using the add another row icon.
I’d like to know about this as well. But in my case they would be required fields.
Out looking for this again…anyone have a snippet that will target a list field and allow me to set the number of rows?
I could use the snippet above, or a perk, but having a hidden field in a form with a default value just to set the number of rows seems a bit bloated.
Any help is appreciated!
Hi KO,
Unfortunately, we do not have a solution for this, aside from using a hidden field with a default value. However, I would think with some customization of the snippet above you should be able to achieve what you want.
Best,
This seems to work. If anyone has a better solution, please share! Hope it can help someone else.
Add the snippet in the link below to the theme’s function.php:
http://snippi.com/s/uofoa8a
NOTE: Be sure to add the class “GWListFixedRows” to the field.
TO REMOVE “+” “-“ buttons add the following CSS:
field_X_XXX .gfield_list_icons { display: none; }
EDIT: Left the hash off of the CSS ID. It should be:
field_X_XXX .gfield_list_icons { display: none; }