Skip to content

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

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

Merged
merged 1 commit into from
Apr 2, 2025

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

A new JavaScript snippet has been added to sort nested form entries in Gravity Forms. This snippet employs the gform.addFilter method to create a filter named gpnf_sorted_entries, which sorts entries alphabetically based on a specified field ID using the localeCompare() method. It includes error handling for cases where entries are empty or the field ID is not found, logging a warning to the console. Users are advised to replace the placeholder field ID "3" with the actual field ID for sorting.

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)

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
Loading

Suggested Reviewers

  • veryspry
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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

github-actions bot commented Mar 27, 2025

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

Generated by 🚫 dangerJS against cf065cd

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.

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.

@malayladu malayladu force-pushed the malay/add/79476-sort-nested-form-entries branch from beafe7b to cf065cd Compare April 2, 2025 13:57
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: 0

🧹 Nitpick comments (2)
gp-nested-forms/gpnf-sort-nested-form-entries.js (2)

26-26: Missing priority and context parameters

The filter is missing the priority and context parameters that would typically be included in a gform.addFilter() call.

-window.gform.addFilter('gpnf_sorted_entries', function (entries, formId, fieldId, gpnf) {
+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');

27-28: Consider adding a usage example comment

To further improve this snippet, consider adding a brief usage example or expected output comment to help users understand how the sorting will affect their forms.

 	});
 });
 
+// Usage example:
+// This will sort child entries alphabetically by the value in field 3.
+// For example, if field 3 is "Name", entries will be sorted by name A-Z.
📜 Review details

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

📥 Commits

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

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

1-10: Well-structured documentation header

The documentation header effectively communicates the purpose and installation instructions for this snippet. It provides clear guidance on how to use the Custom JavaScript plugin for implementation.


11-12: Good implementation of configurable field ID

You've successfully implemented the suggestion to make the field ID configurable with a clear comment indicating it should be from the child form. This approach makes the snippet more user-friendly and reduces the chance of implementation errors.


13-18: Effective error handling for edge cases

The code properly checks for empty entries and missing field IDs, providing a helpful console warning when issues are detected. This prevents silent failures and makes troubleshooting easier for users.


20-25: Robust sorting implementation with fallback handling

The sorting function correctly handles cases where fields or labels might be missing, ensuring the sort operation won't throw errors. The use of localeCompare() provides proper alphabetical sorting with language sensitivity.

@claygriffiths claygriffiths merged commit 0f8c00b into master Apr 2, 2025
3 of 4 checks passed
@claygriffiths claygriffiths deleted the malay/add/79476-sort-nested-form-entries branch April 2, 2025 14:06
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