Skip to content

Conversation

@malayladu
Copy link
Contributor

@malayladu malayladu commented Apr 25, 2025

Context

⛑️ Ticket(s): https://secure.helpscout.net/conversation/2916143012/82450

Summary

By default, GP Auto List Field calculates the all rows (including blank rows) when we use :count modifier. This snippet is useful when you want to count only non-blank rows.

82450-Count-Non-Blank-Rows

@malayladu malayladu self-assigned this Apr 25, 2025
@coderabbitai
Copy link

coderabbitai bot commented Apr 25, 2025

Walkthrough

A new JavaScript file was introduced to extend Gravity Forms functionality by customizing how the ":count" merge tag operates for list fields. The script hooks into the Gravity Forms filter for merge tag value calculation and, when a merge tag with the ":count" suffix is encountered, it counts only those rows in a list field that contain at least one non-empty value. If the merge tag or field does not match the expected pattern, the value is returned unchanged.

Changes

File(s) Change Summary
gp-auto-list-field/gpalf-count-only-non-blank-rows.js Added a script that filters Gravity Forms merge tag values to count only non-blank rows in list fields when ":count" is used in the merge tag.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant GravityForms
    participant CustomScript

    User->>GravityForms: Submits form with a list field
    GravityForms->>CustomScript: Calls filter for merge tag value with ":count"
    CustomScript->>GravityForms: Returns count of non-blank rows in the list field
    GravityForms->>User: Displays or processes the calculated count
Loading

Suggested reviewers

  • saifsultanc
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions
Copy link

Warnings
⚠️ When ready, don't forget to request reviews on this pull request from your fellow wizards.

Generated by 🚫 dangerJS against 24f26d7

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (5)
gp-auto-list-field/gpalf-count-only-non-blank-rows.js (5)

1-11: Documentation looks good but could be improved.

The header comment clearly explains the purpose of the snippet, which matches the PR objectives of counting only non-blank rows in a List field. However, the title "Dynamic Row Labels for List Fields" doesn't accurately reflect the functionality being added, which is about counting non-blank rows.

-/**
- * Gravity Perks // Auto List Field // Dynamic Row Labels for List Fields
+/**
+ * Gravity Perks // Auto List Field // Count Only Non-Blank Rows
 * https://gravitywiz.com/documentation/gravity-forms-auto-list-field/
 *
 * Count only non-blank rows in a List field.
 *
 * Instructions:
 *
 * 1. Install this snippet with our free Custom JavaScript plugin.
 *    https://gravitywiz.com/gravity-forms-code-chest/
 */

12-15: Consider adding jQuery dependency check.

The code uses jQuery but doesn't verify its availability. It's also missing comments explaining what the filter does and the structure of the match parameter.

+/**
+ * Filter the merge tag value before calculation.
+ * Modifies the behavior of :count modifier to only count non-blank rows in a list field.
+ * 
+ * @param {string|number} value - The current value of the merge tag
+ * @param {Array} match - The regex match array from the merge tag pattern
+ * @param {boolean} isVisible - Whether the field is visible
+ * @param {object} formulaField - The field object containing the formula
+ * @param {number} formId - The ID of the current form
+ * @return {string|number} - The modified value or original value if conditions aren't met
+ */
 gform.addFilter('gform_merge_tag_value_pre_calculation', function (value, match, isVisible, formulaField, formId) {
+    // Ensure jQuery is available
+    if (typeof jQuery === 'undefined') {
+        console.error('jQuery is required for the non-blank rows counter to work.');
+        return value;
+    }
+    
+    // Check if this is a :count merge tag
 	if (typeof match[3] === 'undefined' || match[3].indexOf(':count') === -1) {
 		return value;
 	}

17-23: Add error handling for invalid field ID.

The code is well-structured but lacks error handling for when the inputId doesn't convert to a valid numeric fieldId.

 	var inputId = match[1];
 	var fieldId = parseInt(inputId, 10);
+
+	// Check if the parsed fieldId is a valid number
+	if (isNaN(fieldId)) {
+		console.warn('Invalid field ID in merge tag:', inputId);
+		return value;
+	}
 
 	var $fieldWrapper = $(`#gform_${formId} #field_${formId}_${fieldId}`);
 	if ($fieldWrapper.length === 0) {
+		console.debug(`Field wrapper not found for field ID ${fieldId} in form ${formId}`);
 		return value;
 	}

25-28: Look for all types of form controls, not just inputs.

The code currently only checks for list groups but doesn't validate if this is actually a list field before proceeding.

 	var $rows = $fieldWrapper.find('.gfield_list_group');
 	if ($rows.length === 0) {
+		// Check if this is actually a list field
+		if (!$fieldWrapper.hasClass('gfield_contains_list')) {
+			console.debug(`Field ${fieldId} in form ${formId} is not a list field`);
+		} else {
+			console.debug(`No list rows found for field ${fieldId} in form ${formId}`);
+		}
 		return value;
 	}

47-48: Function return value lacks type coercion.

The return value should match the expected type of the original value for consistency. The merge tag system likely expects a string, but this returns a number.

-	return nonBlankCount;
+	// Convert to string to match the expected return type of merge tags
+	return String(nonBlankCount);
 });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a4c8c66 and 24f26d7.

📒 Files selected for processing (1)
  • gp-auto-list-field/gpalf-count-only-non-blank-rows.js (1 hunks)

Comment on lines +30 to +45
var nonBlankCount = 0;

$rows.each(function () {
var isNonBlank = false;

$(this).find('input').each(function () {
if ($(this).val().trim() !== '') {
isNonBlank = true;
return false;
}
});

if (isNonBlank) {
nonBlankCount++;
}
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve non-blank row detection to include all form controls.

The current implementation only checks for input elements, but list fields might contain other form controls like select, textarea, etc. Additionally, the code uses jQuery's .each() with a return false to break the inner loop, which is correct but could be documented for clarity.

 	var nonBlankCount = 0;
 
 	$rows.each(function () {
 		var isNonBlank = false;
 
-		$(this).find('input').each(function () {
+		// Check all possible form controls (inputs, selects, textareas)
+		$(this).find('input, select, textarea').each(function () {
 			if ($(this).val().trim() !== '') {
 				isNonBlank = true;
+				// Break the .each() loop early since we found a non-blank value
 				return false;
 			}
 		});
 
 		if (isNonBlank) {
 			nonBlankCount++;
 		}
 	});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var nonBlankCount = 0;
$rows.each(function () {
var isNonBlank = false;
$(this).find('input').each(function () {
if ($(this).val().trim() !== '') {
isNonBlank = true;
return false;
}
});
if (isNonBlank) {
nonBlankCount++;
}
});
var nonBlankCount = 0;
$rows.each(function () {
var isNonBlank = false;
// Check all possible form controls (inputs, selects, textareas)
$(this).find('input, select, textarea').each(function () {
if ($(this).val().trim() !== '') {
isNonBlank = true;
// Break the .each() loop early since we found a non-blank value
return false;
}
});
if (isNonBlank) {
nonBlankCount++;
}
});

Copy link
Contributor

@saifsultanc saifsultanc left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests look good. LGTM. S&M!

@malayladu malayladu merged commit 1ae5515 into master Apr 28, 2025
4 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants