Skip to content

gpnf-sort-nested-form-entries.php: Added snippet for sorting nested form entries both on frontend and backend. #1068

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

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

Conversation

… form entries both on frontend and backend.
Copy link

coderabbitai bot commented Apr 4, 2025

Walkthrough

This pull request adds a new PHP file that introduces the GPNF_Sort_Nested_Entries class. The class provides functionality to sort nested form entries based on a specified field and order. It hooks into WordPress’s initialization process to register filters for adjusting template arguments and loading a JavaScript sorting script during form rendering. The sorting is performed both in PHP using usort and on the client side via an injected JavaScript snippet. An example instantiation of the class is provided within the file.

Changes

File(s) Changed Change Summary
gp-nested-forms/gpnf-sort-nested-form-entries.php Added GPNF_Sort_Nested_Entries class with methods: __construct, init, sort_entries_php, load_form_script, and output_script. Includes an example instantiation demonstrating sorting functionality.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant U as User
    participant WP as WordPress
    participant SN as GPNF_Sort_Nested_Entries
    participant JS as JavaScript Environment

    U->>WP: Request Nested Form Page
    WP->>SN: Trigger init() during WordPress initialization
    SN->>WP: Add filters for template arguments and script loading
    WP->>SN: On form render, call load_form_script()
    SN->>WP: Execute output_script() to inject JS snippet
    JS->>JS: Register filter and sort nested form entries on client side

Possibly related PRs

Suggested reviewers

  • claygriffiths
✨ 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

github-actions bot commented Apr 4, 2025

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

Generated by 🚫 dangerJS against ba85fc3

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

17-30: Consider adding validation for required parameters.

The constructor sets default values of false for critical parameters (parent_form_id, nested_field_id, and sort_field_id), but doesn't validate that proper values are provided during instantiation.

public function __construct( $args = array() ) {
    $this->_args = wp_parse_args( $args, array(
        'parent_form_id'   => false,
        'nested_field_id'  => false,
        'sort_field_id'    => false,
        'sort_order'       => 'asc',
    ) );

+   // Validate required parameters
+   if ( ! $this->_args['parent_form_id'] || ! $this->_args['nested_field_id'] || ! $this->_args['sort_field_id'] ) {
+       error_log( 'GPNF_Sort_Nested_Entries: Required parameters missing.' );
+       return;
+   }

    add_action( 'init', array( $this, 'init' ) );
}

37-59: Improve sorting robustness with type-safe comparison and validation.

The sorting function has a few areas that could be improved:

  1. Add array validation before using usort
  2. Use strict comparison (===) instead of loose equality (==)
  3. Consider type conversion for consistent sorting
public function sort_entries_php( $args ) {
    $field_id = $this->_args['sort_field_id'];
    $order    = strtolower( $this->_args['sort_order'] );

-   if ( isset( $args['entries'] ) ) {
+   if ( isset( $args['entries'] ) && is_array( $args['entries'] ) ) {
        usort( $args['entries'], function( $a, $b ) use ( $field_id, $order ) {
            $first  = rgar( $a, $field_id );
            $second = rgar( $b, $field_id );

-           if ( $first == $second ) {
+           if ( $first === $second ) {
                return 0;
            }

+           // Convert to comparable types if possible
+           if ( is_numeric( $first ) && is_numeric( $second ) ) {
+               $first = (float) $first;
+               $second = (float) $second;
+           }
+
            if ( $order === 'asc' ) {
                return ( $first < $second ) ? -1 : 1;
            } else {
                return ( $first > $second ) ? -1 : 1;
            }
        } );
    }

    return $args;
}

70-105: Add browser compatibility enhancements and handle different data types.

The JavaScript code uses modern features (template literals with backticks, optional chaining) that might not be supported in older browsers. Also, the sort logic only compares string values, which might not work well for numeric fields.

public function output_script() {
    $args = array(
        'parentFormId'  => (int) $this->_args['parent_form_id'],
        'nestedFieldId' => (int) $this->_args['nested_field_id'],
        'sortFieldId'   => (int) $this->_args['sort_field_id'],
        'sortOrder'     => strtolower( $this->_args['sort_order'] ),
    );
    ?>

    <script type="text/javascript">
        (function($) {
            var sortFieldId = "<?php echo esc_js( $args['sortFieldId'] ); ?>";
            var sortOrder   = "<?php echo esc_js( $args['sortOrder'] ); ?>";

            window.gform.addFilter('gpnf_sorted_entries', function(entries, formId, fieldId, gpnf) {
                if (!entries || !entries.length || !entries[0][sortFieldId]) {
-                   console.warn(`GPNF Sort: Field ID ${sortFieldId} not found in entries or entries are empty.`);
+                   console.warn('GPNF Sort: Field ID ' + sortFieldId + ' not found in entries or entries are empty.');
                    return entries;
                }

                return entries.sort(function(a, b) {
-                   let valA = a[sortFieldId]?.label || '';
-                   let valB = b[sortFieldId]?.label || '';
+                   var valA = a[sortFieldId] && a[sortFieldId].label ? a[sortFieldId].label : '';
+                   var valB = b[sortFieldId] && b[sortFieldId].label ? b[sortFieldId].label : '';
+                   
+                   // Handle numeric values
+                   if (!isNaN(valA) && !isNaN(valB)) {
+                       valA = parseFloat(valA);
+                       valB = parseFloat(valB);
+                       
+                       if (sortOrder === 'desc') {
+                           return valB - valA;
+                       }
+                       return valA - valB;
+                   }
+                   
+                   // Handle string values
                    if (sortOrder === 'desc') {
                        return valB.localeCompare(valA);
                    }

                    return valA.localeCompare(valB);
                });
            });
        })(jQuery);
    </script>

    <?php
}

108-114: Improve example usage with comments.

The example instantiation would benefit from additional comments explaining how to adapt the IDs for different implementations.

# Example usage:
new GPNF_Sort_Nested_Entries( array(
-   'parent_form_id'  => 184,
-   'nested_field_id' => 1,
-   'sort_field_id'   => 2,     // field on child form to sort by
+   'parent_form_id'  => 184,   // ID of your parent form
+   'nested_field_id' => 1,     // ID of the Nested Form field in the parent form
+   'sort_field_id'   => 2,     // ID of the field in the child form to sort by
    'sort_order'      => 'asc', // or 'desc'
) );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 116f997 and ba85fc3.

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

1-16: Well-structured documentation header!

The documentation provides clear information about the purpose of the snippet, includes links to resources, and follows proper plugin header format.


32-35: LGTM - Proper hook implementation.

The initialization method properly adds filters with specific form and field IDs.


61-68: LGTM - Good use of hook checks to prevent duplicate script loading.

The method correctly checks if the current form matches the target parent form and uses a smart approach to prevent multiple script inclusions.

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.

None yet

1 participant