Skip to content

gw-gravity-forms-rounding.php: Fixed an issue with rounding now updating form total. #1126

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/2981539269/85760

Summary

The GF Rounding snippet isn't working as expected.

ISSUE 1
The minimum rounding doesn't work when the value is entered. It works only when you're using the number field controls to increase or decrease the value.
We had if( value != '' ), which we changed to if( value !== '' )
Switching from loose inequality (!=) to strict inequality (!==) to prevent unintended type coercion. This ensures that numeric 0 and empty string '' are treated as distinct values during comparison. With !=, javascript converts 0 != '' as a numeric comparison with both values as 0.

ISSUE 2
When the rounding is applied to a quantity value, it doesn't update the total.
Using $input.val( value ).change(); alone wasn’t enough to trigger Gravity Forms' total recalculation in some cases. Gravity Forms listens for native input events on fields like quantity and product fields for live calculations. We add a native input event dispatch after setting the value, ensuring Gravity Forms detects the change and recalculates totals as if the user had typed the value manually.

BEFORE (Samuel's loom):
https://www.loom.com/share/c94f0966f80f495db537dc68e7d5da81

AFTER:
https://www.loom.com/share/b012dd305bdb4ed1b800c2ef3957bcf9

Copy link

coderabbitai bot commented Jun 28, 2025

Walkthrough

The JavaScript function responsible for rounding input values in Gravity Forms was updated to dispatch a native input event after modifying the input's value and triggering a jQuery change event. Additionally, a strict inequality check is now used to verify non-empty values before applying rounding.

Changes

File(s) Change Summary
gravity-forms/gw-gravity-forms-rounding.php Enhanced input event dispatching after value change and updated value check to use strict inequality

Possibly related PRs

Suggested reviewers

  • veryspry

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 phpcs (3.7.2)
gravity-forms/gw-gravity-forms-rounding.php

Warning: PHP Startup: Invalid date.timezone value 'UTC', using 'UTC' instead in Unknown on line 0

Fatal error: Uncaught Error: Class "Phar" not found in /usr/local/bin/phpcs:3
Stack trace:
#0 {main}
thrown in /usr/local/bin/phpcs on line 3

✨ 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

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

Generated by 🚫 dangerJS against 409ad13

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 (1)
gravity-forms/gw-gravity-forms-rounding.php (1)

188-196: Consider adding error handling for the native event dispatch.

While the implementation is correct, consider adding error handling around the dispatchEvent call to gracefully handle edge cases where the DOM element might not support the method.

 self.applyRoundingActions = function( $input ) {
     var value = self.getRoundedValue( $input );
     if( $input.val() != value ) {
         $input.val( value ).change();
         const input = $input[0];
-        // Ensure Gravity Forms detects the programmatic value change by dispatching a native input event
-        input.dispatchEvent( new Event( 'input', { bubbles: true } ) );
+        // Ensure Gravity Forms detects the programmatic value change by dispatching a native input event
+        if ( input && typeof input.dispatchEvent === 'function' ) {
+            input.dispatchEvent( new Event( 'input', { bubbles: true } ) );
+        }
     }
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 24c21fd and 409ad13.

📒 Files selected for processing (1)
  • gravity-forms/gw-gravity-forms-rounding.php (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: saifsultanc
PR: gravitywiz/snippet-library#1079
File: gp-populate-anything/gppa-acf-repeater-mapper.php:78-87
Timestamp: 2025-04-17T02:43:14.227Z
Learning: When working with Gravity Forms, `rgar()` is a utility function that safely retrieves values from arrays and can be used to implement cleaner safety checks compared to direct conditionals.
Learnt from: veryspry
PR: gravitywiz/snippet-library#1077
File: gravity-forms/gw-require-alt-text-description-post-image.php:23-32
Timestamp: 2025-05-30T13:53:21.893Z
Learning: In Gravity Forms snippets, use 'gravityforms' as the translation domain for internationalization functions instead of creating custom domains, to maintain consistency with the related plugin.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Danger JS
🔇 Additional comments (2)
gravity-forms/gw-gravity-forms-rounding.php (2)

192-194: LGTM! Good implementation of native input event dispatching.

The addition of native input event dispatching correctly addresses the issue where Gravity Forms wasn't detecting programmatic value changes for form total recalculation. Using bubbles: true ensures the event propagates properly through the DOM.


222-222: Excellent fix for type coercion issues.

The change from loose inequality (!=) to strict inequality (!==) prevents unintended type coercion between numeric zero and empty strings, which was causing the minimum rounding functionality to fail when values were entered manually.

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