How to count list rows?

Hi there,

I would like to count the rows of list entries. I want to use this number in a calculation. I´d prefer not to use another plugin or addon. And it seems that there is a function, that should do it. But I can´t get it to work.

What I have done:

  • added the code snippet to the functions.php
  • changed the IDs at the end of it according to my form: ListFieldRowTotal(1, 22, 41)
  • added a custom field (field type: number / custom field name: new) in the form and
  • activated dynamic population

Unfortunately there´s no number of rows coming up in the form. Any ideas?

Regards,
Jens

Give this script a try. Just change the form ID (401), list field ID (1), and results field ID (2) at the bottom of the code:

<script>
jQuery(function($){

  function listFieldRowCount(formId, fieldId, totalFieldId) {
    const listFieldSel  = '#field_' + formId + '_' + fieldId;
    const totalFieldSel = '#input_' + formId + '_' + totalFieldId;

    const $list  = $(listFieldSel);
    const $total = $(totalFieldSel);

    if (!$list.length || !$total.length) return;

    // Next paint (lets GF update DOM first)
    requestAnimationFrame(function(){
      const totalRows = $list.find('.gfield_list_group').length;
      // console.log('[GF] rows:', totalRows);
      if ($total.val() != totalRows) {
        $total.val(totalRows).trigger('change');
      }
    });
  }

  function listFieldRowTotal(formId, fieldId, totalFieldId) {
    const listFieldSel = '#field_' + formId + '_' + fieldId;
    const $list        = $(listFieldSel);

    if (!$list.length) return;

    // Prevent double-init on redraws
    if ($list.data('rowTotalInited')) return;
    $list.data('rowTotalInited', true);

    // Initial count
    listFieldRowCount(formId, fieldId, totalFieldId);

    // Add/Delete row events
    $(document).on('gform_list_item_add gform_list_item_delete', function(event, fId, fldId){
      if (parseInt(fId,10) === parseInt(formId,10) && parseInt(fldId,10) === parseInt(fieldId,10)) {
        listFieldRowCount(formId, fieldId, totalFieldId);
      }
    });

    // Fallback: observe only the list container body for child changes
    const container = $list.find('.gfield_list_container, table.gfield_list')[0] || $list[0];

    let obsTimer = null;
    if (container && 'MutationObserver' in window) {
      const mo = new MutationObserver(function(){
        // debounce to one update per tick
        if (obsTimer) return;
        obsTimer = requestAnimationFrame(function(){
          obsTimer = null;
          listFieldRowCount(formId, fieldId, totalFieldId);
        });
      });
      mo.observe(container, { childList: true, subtree: true });
      $list.data('rowTotalObserver', mo);
    }
  }

  // Init on first load
  listFieldRowTotal(401, 1, 2);

  // Re-init on GF redraws (AJAX/conditional/page change)
  $(document).on('gform/post_render', function(e, formId){
    if (parseInt(formId,10) === 401) {
      listFieldRowTotal(401, 1, 2);
    }
  });

});
</script>

Disclaimer: Third-party plugins or code snippets that are provided or referenced by our Support Team or documentation, are provided as suggestions only. We do not evaluate, test, guarantee or officially support third-party solutions or code-snippets. You are wholly responsible for determining if any suggestion or code snippet provided is sufficient to meet the functional, security, legal, ongoing cost and support needs of your project, as well as testing and confirming performance across future product updates.

Thanks, Chris!

I´ve added this to the functions.php with the plugin code snippets, changed the IDs (1, 22, 43) and activated the snippet for the frontend. Unfortunately it´s not working yet: neither in preview nor live.

I guess there´s a problem in the form itself. What kind of result field and settings are necessary?

  • field type: single line text oder number or custom field
  • activate dynamic population: yes or no
  • any other settings for this field

list-field:

result-field:

#1 Adding the provided script to the functions.php file directly will not work because it is JavaScript, not PHP. So first thing is to make sure we’re adding the code the correct way. See this doc for an example: Where Do I Put This Code? - Gravity Forms Documentation .

You can also copy the snippet provided into an HTML field within your form.

#2 You can use any type of alphanumeric input field. I would recommend either single line text or a number field

#3 You do not need to activate dynamic population

#4 To be clear, your IDs are 1 = Form ID, 22 = List field ID, 43 = Results field ID.

This is a demonstration of the results of the code snippet provided: https://docs.wprescue.me/L1uwrAZL

Thank you very much, Chris! Now it works like a charm. And I will never forget the difference between JavaScript and PHP anymore. :person_facepalming:

2 Likes

I love custom code as much as any wizard but if you’re ever interested in a solution that doesn’t involve custom code, our Auto List Field plugin supports this out of the box. :takeout_box:

3 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.