Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gpnf-sort-nested-form-entries.js: Added support to sort nested form entries. #1060

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

malayladu
Copy link
Contributor

Context

⛑️ Ticket(s): https://secure.helpscout.net/conversation/2876515303/79476

Summary

This snippet uses gpnf_sorted_entries JS filter to sort nested form entries in frontend.

@malayladu malayladu self-assigned this Mar 27, 2025
Copy link

coderabbitai bot commented Mar 27, 2025

Walkthrough

This pull request introduces a new JavaScript snippet that sorts nested form entries in Gravity Forms. The snippet uses the gform.addFilter method to add a filter named gpnf_sorted_entries that sorts the entries alphabetically. The sorting is done using the localeCompare() method on the entries' label property. Instructions are provided to replace the default placeholder field ID ("3") with the actual field ID to be sorted.

Changes

File Change Summary
gp-nested-forms/gpnf-sort-nested-form-entries.js Added a new JS snippet that registers a gpnf_sorted_entries filter using gform.addFilter to sort nested form entries alphabetically.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant GF as Gravity Forms
    participant Sorter as Nested Form Sorter
    GF ->> Sorter: Trigger "gpnf_sorted_entries" filter with entries
    Sorter ->> Sorter: Sort entries using localeCompare on label
    Sorter -->> GF: Return sorted entries

Suggested Reviewers

  • veryspry
✨ 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

Copy link

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

Generated by 🚫 dangerJS against beafe7b

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 (2)
gp-nested-forms/gpnf-sort-nested-form-entries.js (2)

15-15: Clarify context parameter

The 'emails' context parameter isn't explained. It's important to document what this parameter means and when this sorting will be applied.

Add a comment explaining the 'emails' context:

-}, 10, 'emails' );
+}, 10, 'emails' ); // Apply this filter only in the 'emails' context. Change or remove this parameter to apply in different contexts.

11-15: Consider supporting different sorting directions

The current implementation only supports ascending alphabetical sorting. Users might need descending sorting or numeric sorting based on their requirements.

Here's a more flexible implementation that supports both directions:

-window.gform.addFilter( 'gpnf_sorted_entries', function( entries, formId, fieldId, gpnf ) {
-	// Replace "3" with the field ID of the field you would like to sort by.
-	// JavaScript provides several ways to sort arrays, including different sorting functions like localeCompare(), numeric sorting, and custom sorting based on object properties. Use the one that best fits your needs.
-	return entries.sort((a, b) => a["3"].label.localeCompare(b["3"].label));
+// Configuration
+const sortConfig = {
+    fieldId: "3",      // The field ID to sort by
+    direction: "asc",  // "asc" for ascending, "desc" for descending
+    numeric: false     // Set to true for numeric sorting
+};
+
+window.gform.addFilter( 'gpnf_sorted_entries', function( entries, formId, fieldId, gpnf ) {
+    // Return early if no entries
+    if (!entries || !entries.length) return entries;
+    
+    return entries.sort((a, b) => {
+        // Handle missing fields gracefully
+        if (!a[sortConfig.fieldId] || !a[sortConfig.fieldId].label) return 1;
+        if (!b[sortConfig.fieldId] || !b[sortConfig.fieldId].label) return -1;
+        
+        let comparison;
+        if (sortConfig.numeric) {
+            // Numeric sorting
+            comparison = parseFloat(a[sortConfig.fieldId].label) - parseFloat(b[sortConfig.fieldId].label);
+        } else {
+            // Text sorting
+            comparison = a[sortConfig.fieldId].label.localeCompare(b[sortConfig.fieldId].label);
+        }
+        
+        // Reverse for descending order
+        return sortConfig.direction === "desc" ? -comparison : comparison;
+    });
}, 10, 'emails' );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 45ab4d6 and beafe7b.

📒 Files selected for processing (1)
  • gp-nested-forms/gpnf-sort-nested-form-entries.js (1 hunks)
🔇 Additional comments (1)
gp-nested-forms/gpnf-sort-nested-form-entries.js (1)

1-10: Documentation looks comprehensive!

The header documentation clearly identifies the purpose of the snippet and provides installation instructions with appropriate links.

Comment on lines +11 to +15
window.gform.addFilter( 'gpnf_sorted_entries', function( entries, formId, fieldId, gpnf ) {
// Replace "3" with the field ID of the field you would like to sort by.
// JavaScript provides several ways to sort arrays, including different sorting functions like localeCompare(), numeric sorting, and custom sorting based on object properties. Use the one that best fits your needs.
return entries.sort((a, b) => a["3"].label.localeCompare(b["3"].label));
}, 10, 'emails' );
Copy link

@coderabbitai coderabbitai bot Mar 27, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Hardcoded field ID needs attention

The sorting implementation uses a hardcoded field ID "3" which requires manual editing by each user. While there is a comment instructing users to replace it, this approach could lead to errors if users don't update it correctly.

Consider implementing one of these improvements:

  1. Make the field ID configurable using a variable that's clearly defined at the top of the file
  2. Add error handling to gracefully handle cases where the specified field doesn't exist in entries
-window.gform.addFilter( 'gpnf_sorted_entries', function( entries, formId, fieldId, gpnf ) {
-	// Replace "3" with the field ID of the field you would like to sort by.
-	// JavaScript provides several ways to sort arrays, including different sorting functions like localeCompare(), numeric sorting, and custom sorting based on object properties. Use the one that best fits your needs.
-	return entries.sort((a, b) => a["3"].label.localeCompare(b["3"].label));
+// Configuration - Change this value to the field ID you want to sort by
+const sortByFieldId = "3"; 
+
+window.gform.addFilter( 'gpnf_sorted_entries', function( entries, formId, fieldId, gpnf ) {
+	// Check if entries exist and have the specified field
+	if (!entries || !entries.length || !entries[0][sortByFieldId]) {
+		console.warn(`GPNF Sort: Field ID ${sortByFieldId} not found in entries or entries are empty. Returning unsorted entries.`);
+		return entries;
+	}
+	
+	// Sort entries by the specified field's label
+	return entries.sort((a, b) => {
+		if (!a[sortByFieldId] || !a[sortByFieldId].label) return 1;
+		if (!b[sortByFieldId] || !b[sortByFieldId].label) return -1;
+		return a[sortByFieldId].label.localeCompare(b[sortByFieldId].label);
+	});
}, 10, 'emails' );
📝 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
window.gform.addFilter( 'gpnf_sorted_entries', function( entries, formId, fieldId, gpnf ) {
// Replace "3" with the field ID of the field you would like to sort by.
// JavaScript provides several ways to sort arrays, including different sorting functions like localeCompare(), numeric sorting, and custom sorting based on object properties. Use the one that best fits your needs.
return entries.sort((a, b) => a["3"].label.localeCompare(b["3"].label));
}, 10, 'emails' );
// Configuration - Change this value to the field ID you want to sort by
const sortByFieldId = "3";
window.gform.addFilter( 'gpnf_sorted_entries', function( entries, formId, fieldId, gpnf ) {
// Check if entries exist and have the specified field
if (!entries || !entries.length || !entries[0][sortByFieldId]) {
console.warn(`GPNF Sort: Field ID ${sortByFieldId} not found in entries or entries are empty. Returning unsorted entries.`);
return entries;
}
// Sort entries by the specified field's label
return entries.sort((a, b) => {
if (!a[sortByFieldId] || !a[sortByFieldId].label) return 1;
if (!b[sortByFieldId] || !b[sortByFieldId].label) return -1;
return a[sortByFieldId].label.localeCompare(b[sortByFieldId].label);
});
}, 10, 'emails' );

Copy link
Contributor

Choose a reason for hiding this comment

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

@malayladu I like this suggestion. You?

Copy link

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Contributor

@claygriffiths claygriffiths left a comment

Choose a reason for hiding this comment

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

I like it! The AI review did have a nice suggestion.

Comment on lines +11 to +15
window.gform.addFilter( 'gpnf_sorted_entries', function( entries, formId, fieldId, gpnf ) {
// Replace "3" with the field ID of the field you would like to sort by.
// JavaScript provides several ways to sort arrays, including different sorting functions like localeCompare(), numeric sorting, and custom sorting based on object properties. Use the one that best fits your needs.
return entries.sort((a, b) => a["3"].label.localeCompare(b["3"].label));
}, 10, 'emails' );
Copy link
Contributor

Choose a reason for hiding this comment

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

@malayladu I like this suggestion. You?

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.

2 participants