Skip to content

gpeb-filter-by-nested-field.php: Added snippet to allow filtering data via nested entries. #1109

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 2 commits into
base: master
Choose a base branch
from

Conversation

saifsultanc
Copy link
Contributor

Context

⛑️ Ticket(s): https://secure.helpscout.net/conversation/2943573391/83636

Summary

Add support to make it possible to include the child form field values to the filter block on the parent form.

Loom Demo:
https://www.loom.com/share/f795e8b5ef58489794dca96e83fcd230

Copy link

coderabbitai bot commented May 23, 2025

Walkthrough

A new PHP class, GPEB_Filter_By_Nested_Entry, is introduced to allow filtering of parent Gravity Forms entries based on values from nested form entries. The class hooks into form filtering and entry querying processes, modifies the filter UI, and filters parent entries by matching nested entry field values. The class is then instantiated with specific configuration parameters.

Changes

File(s) Change Summary
gp-entry-blocks/gpeb-filter-by-nested-field.php Added GPEB_Filter_By_Nested_Entry class with methods for nested entry-based filtering; instantiated with config.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant FilterForm
    participant GPEB_Filter_By_Nested_Entry
    participant ParentEntries
    participant NestedEntries

    User->>FilterForm: Submits filter with value for hidden field
    FilterForm->>GPEB_Filter_By_Nested_Entry: Trigger modify_filter_form
    GPEB_Filter_By_Nested_Entry->>FilterForm: Replace hidden field with nested field

    FilterForm->>GPEB_Filter_By_Nested_Entry: Trigger filter_entries_by_nested_value
    GPEB_Filter_By_Nested_Entry->>NestedEntries: Query nested entries by target field value
    NestedEntries->>GPEB_Filter_By_Nested_Entry: Return matching nested entries
    GPEB_Filter_By_Nested_Entry->>ParentEntries: Fetch parent entries by parent IDs from nested entries
    ParentEntries->>GPEB_Filter_By_Nested_Entry: Return filtered parent entries
    GPEB_Filter_By_Nested_Entry->>FilterForm: Return filtered parent entries
    FilterForm->>User: Display filtered results
Loading

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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.

Copy link

github-actions bot commented May 23, 2025

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

Generated by 🚫 dangerJS against 43d906f

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: 4

🧹 Nitpick comments (2)
gp-entry-blocks/gpeb-filter-by-nested-field.php (2)

34-34: Use strict comparison for type safety.

Using loose comparison (==) instead of strict comparison (===) can lead to unexpected behavior with type coercion.

Apply this diff for type safety:

-return $form_id == $this->parent_form_id;
+return $form_id === $this->parent_form_id;

88-93: Move hard-coded configuration to a more appropriate location.

Hard-coding configuration values directly in the class file makes the code less reusable and harder to maintain. Consider moving this to a configuration file, plugin options, or at least adding documentation about customization.

Consider one of these approaches:

  1. Move to a separate configuration file:
// In a separate config file or at the top of this file
$gpeb_filter_config = array(
	'parent_form_id'         => 4,
	'nested_form_id'         => 3,
	'parent_hidden_field_id' => 10,
	'nested_target_field_id' => 4,
);

new GPEB_Filter_By_Nested_Entry( $gpeb_filter_config );
  1. Add configuration documentation:
+/**
+ * Configuration for GPEB Filter By Nested Entry
+ * 
+ * To customize for your forms, update the following values:
+ * - parent_form_id: ID of the parent form containing the entries to filter
+ * - nested_form_id: ID of the nested form containing the filter criteria
+ * - parent_hidden_field_id: ID of the hidden field in the parent form
+ * - nested_target_field_id: ID of the field in the nested form to filter by
+ */
 new GPEB_Filter_By_Nested_Entry( array(
 	'parent_form_id'         => 4,
 	'nested_form_id'         => 3,
 	'parent_hidden_field_id' => 10,
 	'nested_target_field_id' => 4,
 ) );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 54c5969 and 008525f.

📒 Files selected for processing (1)
  • gp-entry-blocks/gpeb-filter-by-nested-field.php (1 hunks)

Comment on lines 16 to 23
public function __construct( $config = array() ) {
$this->parent_form_id = rgar( $config, 'parent_form_id' );
$this->nested_form_id = rgar( $config, 'nested_form_id' );
$this->parent_hidden_field_id = rgar( $config, 'parent_hidden_field_id' );
$this->nested_target_field_id = rgar( $config, 'nested_target_field_id' );

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

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation for required configuration parameters.

The constructor accepts configuration parameters but doesn't validate that required parameters are provided, which could lead to runtime errors when the class methods are called.

Consider adding validation in the constructor:

 public function __construct( $config = array() ) {
+	// Validate required configuration parameters
+	$required_params = array( 'parent_form_id', 'nested_form_id', 'parent_hidden_field_id', 'nested_target_field_id' );
+	foreach ( $required_params as $param ) {
+		if ( empty( $config[ $param ] ) ) {
+			throw new InvalidArgumentException( "Required parameter '$param' is missing or empty." );
+		}
+	}
+
 	$this->parent_form_id         = rgar( $config, 'parent_form_id' );
 	$this->nested_form_id         = rgar( $config, 'nested_form_id' );
 	$this->parent_hidden_field_id = rgar( $config, 'parent_hidden_field_id' );
 	$this->nested_target_field_id = rgar( $config, 'nested_target_field_id' );

 	add_action( 'init', array( $this, 'init' ) );
 }
📝 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
public function __construct( $config = array() ) {
$this->parent_form_id = rgar( $config, 'parent_form_id' );
$this->nested_form_id = rgar( $config, 'nested_form_id' );
$this->parent_hidden_field_id = rgar( $config, 'parent_hidden_field_id' );
$this->nested_target_field_id = rgar( $config, 'nested_target_field_id' );
add_action( 'init', array( $this, 'init' ) );
}
public function __construct( $config = array() ) {
// Validate required configuration parameters
$required_params = array( 'parent_form_id', 'nested_form_id', 'parent_hidden_field_id', 'nested_target_field_id' );
foreach ( $required_params as $param ) {
if ( empty( $config[ $param ] ) ) {
throw new InvalidArgumentException( "Required parameter '$param' is missing or empty." );
}
}
$this->parent_form_id = rgar( $config, 'parent_form_id' );
$this->nested_form_id = rgar( $config, 'nested_form_id' );
$this->parent_hidden_field_id = rgar( $config, 'parent_hidden_field_id' );
$this->nested_target_field_id = rgar( $config, 'nested_target_field_id' );
add_action( 'init', array( $this, 'init' ) );
}
🤖 Prompt for AI Agents
In gp-entry-blocks/gpeb-filter-by-nested-field.php around lines 16 to 23, the
constructor assigns configuration parameters without validating their presence,
which may cause runtime errors later. Add input validation in the constructor to
check that all required parameters like parent_form_id, nested_form_id,
parent_hidden_field_id, and nested_target_field_id are provided and not empty.
If any required parameter is missing, throw an exception or trigger an error to
prevent improper instantiation.

Comment on lines 63 to 85
$nested_entries = GFAPI::get_entries( $this->nested_form_id, array(
'field_filters' => array(
array(
'key' => $this->nested_target_field_id,
'value' => $filters[ $this->parent_hidden_field_id ],
),
),
) );

$entries = array();
$parent_entry_ids = array();

foreach ( $nested_entries as $nested_entry ) {
$parent_entry_id = rgar( $nested_entry, 'gpnf_entry_parent' );
$entry = GFAPI::get_entry( $parent_entry_id );
if ( ! in_array( $parent_entry_id, $parent_entry_ids ) && $entry && ! is_wp_error( $entry ) ) {
$parent_entry_ids[] = $parent_entry_id;
$entries[] = $entry;
}
}

return $entries;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize performance and add error handling for entry queries.

The current implementation has several performance and reliability issues:

  1. Multiple individual GFAPI::get_entry() calls in a loop
  2. No error handling for GFAPI calls
  3. Complete replacement of entries array rather than filtering existing entries

Consider this optimized approach:

-$entries = array();
-$parent_entry_ids = array();
-
-foreach ( $nested_entries as $nested_entry ) {
-	$parent_entry_id = rgar( $nested_entry, 'gpnf_entry_parent' );
-	$entry = GFAPI::get_entry( $parent_entry_id );
-	if ( ! in_array( $parent_entry_id, $parent_entry_ids ) && $entry && ! is_wp_error( $entry ) ) {
-		$parent_entry_ids[] = $parent_entry_id;
-		$entries[] = $entry;
-	}
-}
+// Collect unique parent entry IDs
+$parent_entry_ids = array();
+foreach ( $nested_entries as $nested_entry ) {
+	$parent_entry_id = rgar( $nested_entry, 'gpnf_entry_parent' );
+	if ( $parent_entry_id && ! in_array( $parent_entry_id, $parent_entry_ids ) ) {
+		$parent_entry_ids[] = $parent_entry_id;
+	}
+}
+
+// Filter existing entries to only include those with matching parent IDs
+if ( ! empty( $parent_entry_ids ) ) {
+	$entries = array_filter( $entries, function( $entry ) use ( $parent_entry_ids ) {
+		return in_array( $entry['id'], $parent_entry_ids );
+	});
+} else {
+	$entries = array(); // No matching nested entries found
+}

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In gp-entry-blocks/gpeb-filter-by-nested-field.php around lines 63 to 85, the
code inefficiently calls GFAPI::get_entry() inside a loop without error handling
and replaces the entries array instead of filtering it. To fix this, refactor to
batch query parent entries in one call if possible, add checks for errors after
each GFAPI call, and modify the logic to filter the existing entries array
rather than replacing it entirely. This will improve performance and
reliability.

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

♻️ Duplicate comments (1)
gp-entry-blocks/gpeb-filter-by-nested-field.php (1)

86-96: Performance optimization still needed for entry retrieval.

The code still has the performance issue identified in previous reviews - making individual GFAPI::get_entry() calls within a loop, which can be inefficient for large datasets.

Consider this optimized approach to reduce database queries:

-$entries = array();
-$parent_entry_ids = array();
-
-foreach ( $nested_entries as $nested_entry ) {
-	$parent_entry_id = rgar( $nested_entry, 'gpnf_entry_parent' );
-	$entry = GFAPI::get_entry( $parent_entry_id );
-	if ( ! in_array( $parent_entry_id, $parent_entry_ids ) && $entry && ! is_wp_error( $entry ) ) {
-		$parent_entry_ids[] = $parent_entry_id;
-		$entries[] = $entry;
-	}
-}
+// Collect unique parent entry IDs
+$parent_entry_ids = array();
+foreach ( $nested_entries as $nested_entry ) {
+	$parent_entry_id = rgar( $nested_entry, 'gpnf_entry_parent' );
+	if ( $parent_entry_id && ! in_array( $parent_entry_id, $parent_entry_ids ) ) {
+		$parent_entry_ids[] = $parent_entry_id;
+	}
+}
+
+// Filter existing entries to only include those with matching parent IDs
+if ( ! empty( $parent_entry_ids ) ) {
+	$entries = array_filter( $entries, function( $entry ) use ( $parent_entry_ids ) {
+		return in_array( $entry['id'], $parent_entry_ids );
+	});
+} else {
+	$entries = array(); // No matching nested entries found
+}
🧹 Nitpick comments (1)
gp-entry-blocks/gpeb-filter-by-nested-field.php (1)

102-107: Consider making configuration more flexible.

The hardcoded form and field IDs make this snippet less reusable. Consider adding configuration comments or making it easier to customize for different use cases.

Add configuration comments to make it easier for users to customize:

 new GPEB_Filter_By_Nested_Entry( array(
+	// Parent form ID that contains the hidden field for filtering
 	'parent_form_id'         => 4,
+	// Nested form ID that contains the target field to filter by
 	'nested_form_id'         => 3,
+	// Hidden field ID in the parent form (will be replaced in filter UI)
 	'parent_hidden_field_id' => 10,
+	// Target field ID in the nested form to filter by
 	'nested_target_field_id' => 4,
 ) );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 008525f and 43d906f.

📒 Files selected for processing (1)
  • gp-entry-blocks/gpeb-filter-by-nested-field.php (1 hunks)
🔇 Additional comments (3)
gp-entry-blocks/gpeb-filter-by-nested-field.php (3)

16-28: Good improvement on input validation!

The constructor now properly validates required parameters before proceeding, which addresses the previous review comment about missing input validation. The early return approach prevents the class from being initialized with invalid configuration.


49-54: Excellent error handling implementation!

The error handling for the GFAPI::get_field() call has been properly implemented as suggested in the previous review. The error logging and graceful continuation prevent fatal errors when fields don't exist.


81-84: Good error handling for nested entries query!

The error handling for GFAPI::get_entries() has been properly implemented, checking for WP_Error objects and providing appropriate error logging.

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.

1 participant