Skip to content

gppa-force-lmt-populate-on-edit.php: Added snippet to update Live Merge Tags when editing entries. #1093

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

saifsultanc
Copy link
Contributor

Context

⛑️ Ticket(s): https://secure.helpscout.net/conversation/2918356655/82575

💬 Slack: https://gravitywiz.slack.com/archives/D042XMBHJ91/p1745768566723809?thread_ts=1745647036.839519&cid=D042XMBHJ91

Summary

Live Merge Tags does not appear to be working when editing entries via the Entry Details page.

Snippet Demo:
https://www.loom.com/share/6a7f28fc0cde406798d5bad4b386a70a

Copy link

coderabbitai bot commented May 2, 2025

Walkthrough

A new PHP script has been added to ensure that Gravity Forms fields using Populate Anything live merge tags are dynamically repopulated whenever an entry is edited. The script hooks into the gform_after_update_entry action, retrieves the relevant form and entry, and processes each field to detect and update live merge tag values based on the latest entry data. This guarantees that dynamically populated fields remain accurate after edits.

Changes

File(s) Change Summary
gp-populate-anything/gppa-force-lmt-populate-on-edit.php Added a script that hooks into entry updates to force dynamic repopulation of fields with live merge tags.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant GravityForms
    participant CustomScript

    User->>GravityForms: Edit and update entry
    GravityForms->>CustomScript: Trigger gform_after_update_entry hook
    CustomScript->>GravityForms: Retrieve form and entry data
    loop For each field in form
        CustomScript->>CustomScript: Check for live merge tags in field default value
        CustomScript->>GravityForms: Process and replace merge tags with current entry data
        CustomScript->>GravityForms: Update entry field value
    end
Loading
✨ 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.

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

@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: 3

🧹 Nitpick comments (2)
gp-populate-anything/gppa-force-lmt-populate-on-edit.php (2)

20-23: Consider validating the preg_replace result.

The code uses preg_replace() without checking if the pattern replacement succeeded. While this specific pattern is simple, it's a good practice to validate regex operations.

 // Process the Live Merge Tags.
-$merge_tag = preg_replace( '/@(?=\{)/', '', $field->defaultValue );
+$merge_tag = preg_replace( '/@(?=\{)/', '', $field->defaultValue );
+if ( $merge_tag === null ) {
+    // Handle preg_replace error
+    continue;
+}
 $value     = GFCommon::replace_variables( $merge_tag, $form, $entry );

24-26: Missing validation before updating entry field.

The code updates the entry field without validating the generated value. Consider adding a check to ensure the value is appropriate before updating.

 // Store updated value on the entry.
+// Skip update if value didn't change
+$current_value = rgar( $entry, $field->id );
+if ( $current_value !== $value ) {
 GFFormsModel::update_entry_field_value( $form, $entry, $field, '', $field->id, $value );
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2e9d14c and 38ad34f.

📒 Files selected for processing (1)
  • gp-populate-anything/gppa-force-lmt-populate-on-edit.php (1 hunks)
🔇 Additional comments (3)
gp-populate-anything/gppa-force-lmt-populate-on-edit.php (3)

1-10: Well-documented snippet with clear purpose.

The documentation header clearly explains the purpose of the snippet and includes useful references to documentation and a demonstration video. This is excellent practice for maintainability.


14-16: LGTM: Logical field iteration with proper validation.

The code correctly iterates through form fields and checks for the presence of live merge tags in the default values.


27-28: Good priority setting for the hook.

Setting the priority to 15 ensures this runs after Gravity Forms' default handlers (typically at priority 10) but before most custom code (which often uses higher priorities).

Comment on lines +11 to +13
add_action( 'gform_after_update_entry', function ( $form, $entry_id ) {
$gppa_lmt = GP_Populate_Anything_Live_Merge_Tags::get_instance();
$entry = GFAPI::get_entry( $entry_id );
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Missing error handling for entry retrieval.

The code retrieves an entry but doesn't validate whether it was successful. If the entry doesn't exist or there's an API error, this could lead to PHP notices or errors.

 add_action( 'gform_after_update_entry', function ( $form, $entry_id ) {
 	$gppa_lmt = GP_Populate_Anything_Live_Merge_Tags::get_instance();
 	$entry    = GFAPI::get_entry( $entry_id );
+	if ( is_wp_error( $entry ) ) {
+		return;
+	}

Comment on lines +1 to +28
<?php
/**
* Gravity Forms // Populate Anything // Force Dynamic Population When Editing Entry.
* https://gravitywiz.com/documentation/gravity-forms-populate-anything/
*
* Instruction Video: https://www.loom.com/share/6a7f28fc0cde406798d5bad4b386a70a
*
* Use this snippet to force fields to be dynamically repopulated via Populate Anything when they are
* edited via the Gravity Forms edit entry screen.
*/
add_action( 'gform_after_update_entry', function ( $form, $entry_id ) {
$gppa_lmt = GP_Populate_Anything_Live_Merge_Tags::get_instance();
$entry = GFAPI::get_entry( $entry_id );
foreach ( $form['fields'] as $field ) {
// For any field having Live Merge Tags.
if ( $gppa_lmt->has_live_merge_tag( $field->defaultValue ) ) {
$gppa_lmt->populate_lmt_whitelist( $form );
remove_all_filters('gform_pre_replace_merge_tags');

// Process the Live Merge Tags.
$merge_tag = preg_replace( '/@(?=\{)/', '', $field->defaultValue );
$value = GFCommon::replace_variables( $merge_tag, $form, $entry );

// Store updated value on the entry.
GFFormsModel::update_entry_field_value( $form, $entry, $field, '', $field->id, $value );
}
}
}, 15, 2 );
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider validating plugin dependencies.

The code assumes that GP Populate Anything and its classes are available. Consider adding a check to ensure the required classes exist before executing the main functionality.

<?php
/**
 * Gravity Forms // Populate Anything // Force Dynamic Population When Editing Entry.
 * https://gravitywiz.com/documentation/gravity-forms-populate-anything/
 *
 * Instruction Video: https://www.loom.com/share/6a7f28fc0cde406798d5bad4b386a70a
 *
 * Use this snippet to force fields to be dynamically repopulated via Populate Anything when they are
 * edited via the Gravity Forms edit entry screen.
 */
+// Exit if accessed directly
+if ( ! defined( 'ABSPATH' ) ) {
+	exit;
+}
+
+// Check if required plugins/classes exist
+if ( ! class_exists( 'GP_Populate_Anything_Live_Merge_Tags' ) || ! class_exists( 'GFAPI' ) ) {
+	return;
+}
+
 add_action( 'gform_after_update_entry', function ( $form, $entry_id ) {
📝 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
<?php
/**
* Gravity Forms // Populate Anything // Force Dynamic Population When Editing Entry.
* https://gravitywiz.com/documentation/gravity-forms-populate-anything/
*
* Instruction Video: https://www.loom.com/share/6a7f28fc0cde406798d5bad4b386a70a
*
* Use this snippet to force fields to be dynamically repopulated via Populate Anything when they are
* edited via the Gravity Forms edit entry screen.
*/
add_action( 'gform_after_update_entry', function ( $form, $entry_id ) {
$gppa_lmt = GP_Populate_Anything_Live_Merge_Tags::get_instance();
$entry = GFAPI::get_entry( $entry_id );
foreach ( $form['fields'] as $field ) {
// For any field having Live Merge Tags.
if ( $gppa_lmt->has_live_merge_tag( $field->defaultValue ) ) {
$gppa_lmt->populate_lmt_whitelist( $form );
remove_all_filters('gform_pre_replace_merge_tags');
// Process the Live Merge Tags.
$merge_tag = preg_replace( '/@(?=\{)/', '', $field->defaultValue );
$value = GFCommon::replace_variables( $merge_tag, $form, $entry );
// Store updated value on the entry.
GFFormsModel::update_entry_field_value( $form, $entry, $field, '', $field->id, $value );
}
}
}, 15, 2 );
<?php
/**
* Gravity Forms // Populate Anything // Force Dynamic Population When Editing Entry.
* https://gravitywiz.com/documentation/gravity-forms-populate-anything/
*
* Instruction Video: https://www.loom.com/share/6a7f28fc0cde406798d5bad4b386a70a
*
* Use this snippet to force fields to be dynamically repopulated via Populate Anything when they are
* edited via the Gravity Forms edit entry screen.
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Check if required plugins/classes exist
if ( ! class_exists( 'GP_Populate_Anything_Live_Merge_Tags' ) || ! class_exists( 'GFAPI' ) ) {
return;
}
add_action( 'gform_after_update_entry', function ( $form, $entry_id ) {
$gppa_lmt = GP_Populate_Anything_Live_Merge_Tags::get_instance();
$entry = GFAPI::get_entry( $entry_id );
foreach ( $form['fields'] as $field ) {
// For any field having Live Merge Tags.
if ( $gppa_lmt->has_live_merge_tag( $field->defaultValue ) ) {
$gppa_lmt->populate_lmt_whitelist( $form );
remove_all_filters( 'gform_pre_replace_merge_tags' );
// Process the Live Merge Tags.
$merge_tag = preg_replace( '/@(?=\{)/', '', $field->defaultValue );
$value = GFCommon::replace_variables( $merge_tag, $form, $entry );
// Store updated value on the entry.
GFFormsModel::update_entry_field_value( $form, $entry, $field, '', $field->id, $value );
}
}
}, 15, 2 );

Comment on lines +17 to +18
$gppa_lmt->populate_lmt_whitelist( $form );
remove_all_filters('gform_pre_replace_merge_tags');
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Potential side effect when removing filters.

The remove_all_filters('gform_pre_replace_merge_tags') call removes all filters, which could affect other functionality that relies on these filters. Consider using a more targeted approach or restoring filters afterward.


🏁 Script executed:

#!/bin/bash
# Check if other code is using the same filter
rg "add_filter\(\s*['\"]gform_pre_replace_merge_tags['\"]" --type php

Length of output: 1284


🏁 Script executed:

#!/bin/bash
# Display the first 200 lines of the file to understand the context around the remove_all_filters call
sed -n '1,200p' gp-populate-anything/gppa-force-lmt-populate-on-edit.php

Length of output: 1253


Avoid Removing All gform_pre_replace_merge_tags Filters

Removing all filters on gform_pre_replace_merge_tags will clear callbacks added by other plugins and add-ons (e.g. gw-cache-buster, gw-all-fields-template, gw-format-date-merge-tags, gw-merge-tag-tab, gw-multi-file-merge-tag, gppa-page-modifier, gp-advanced-phone-field, etc.), likely breaking their functionality.

Consider one of these targeted approaches:

  • Remove only your own callback instead of all filters:
    remove_filter(
      'gform_pre_replace_merge_tags',
      [ $gppa_lmt, 'your_specific_callback' ],
      $your_callback_priority,
      $your_callback_arg_count
    );
  • Or back up & restore the original filter list around your merge-tag processing:
    $tag              = 'gform_pre_replace_merge_tags';
    $original_filters = $GLOBALS['wp_filter'][ $tag ] ?? [];
    
    // Whitelist and add only necessary WP filters
    $gppa_lmt->populate_lmt_whitelist( $form );
    
    // Process merge tags
    $value = GFCommon::replace_variables( $merge_tag, $form, $entry );
    
    // Restore all other filters
    $GLOBALS['wp_filter'][ $tag ] = $original_filters;

Please update gppa-force-lmt-populate-on-edit.php to use one of these patterns so you don’t unintentionally disable other integrations.

Copy link

github-actions bot commented May 2, 2025

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

Generated by 🚫 dangerJS against 38ad34f

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