Skip to content

gw-product-quantity-conditional.php: Added snippet to use quantity value of Product Field as a conditional logic field. #1123

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/2951687684/84205

Summary

Targeting Single Product field's quantity input to be applicable in Gravity Forms' regular conditional logic.

Snippet Demo:
https://www.loom.com/share/38547a28853f4706b10cfdb42eaa45ca

…value of Product Field as a conditional lopic field.
Copy link

coderabbitai bot commented Jun 20, 2025

Walkthrough

A new plugin file introduces the GW_Product_Quantity_Conditional class, which augments Gravity Forms by adding quantity field options to conditional logic for certain Single Product fields. The class uses a singleton pattern, hooks into the admin lifecycle, and enqueues JavaScript to update conditional logic options on relevant admin pages.

Changes

File(s) Change Summary
gravity-forms/gw-product-quantity-conditional.php Added new plugin file with GW_Product_Quantity_Conditional class, singleton instantiation, and admin JS logic

Sequence Diagram(s)

sequenceDiagram
    participant AdminUser
    participant WP_Admin
    participant GW_Product_Quantity_Conditional
    participant GravityForms_AdminPage
    participant JS_Script

    AdminUser->>WP_Admin: Accesses Gravity Forms admin page
    WP_Admin->>GW_Product_Quantity_Conditional: Triggers admin_init
    GW_Product_Quantity_Conditional->>GW_Product_Quantity_Conditional: init()
    GW_Product_Quantity_Conditional->>GravityForms_AdminPage: Checks if GF page
    GW_Product_Quantity_Conditional->>GravityForms_AdminPage: Enqueues JS script
    AdminUser->>GravityForms_AdminPage: Edits form conditional logic
    GravityForms_AdminPage->>JS_Script: Loads JS
    JS_Script->>GravityForms_AdminPage: Augments conditional logic fields with quantity options
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.

@saifsultanc saifsultanc changed the title gw-product-quantity-conditional.php: Added snippet to use quantity value of Product Field as a conditional lopic field. gw-product-quantity-conditional.php: Added snippet to use quantity value of Product Field as a conditional logic field. Jun 20, 2025
Copy link

Warnings
⚠️ When ready, don't forget to request reviews on this pull request from your fellow wizards.
Messages
📖 A new snippet with a Loom video? Magical! 📹
📖 Merlin would give this scroll the highest of praises. Cheers for adding this new snippet to the library! 🪄

Generated by 🚫 dangerJS against 73e6bef

1 similar comment
Copy link

Warnings
⚠️ When ready, don't forget to request reviews on this pull request from your fellow wizards.
Messages
📖 A new snippet with a Loom video? Magical! 📹
📖 Merlin would give this scroll the highest of praises. Cheers for adding this new snippet to the library! 🪄

Generated by 🚫 dangerJS against 73e6bef

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 (5)
gravity-forms/gw-product-quantity-conditional.php (5)

20-24: Use strict comparison in singleton pattern.

The singleton implementation uses loose comparison which is less reliable than strict comparison.

-		if ( self::$_instance == null ) {
+		if ( self::$_instance === null ) {

46-75: Optimize JavaScript object structure and add error handling.

The JavaScript object has some inefficiencies and missing error handling that could be improved.

 		<script type="text/javascript">
 			window.gwProductQuantityConditional = {
 				
 				// Check if product has dedicated quantity field
 				productHasQuantityField: function(fieldId, form) {
+					if (!form || !form.fields) return false;
 					for(var i = 0; i < form.fields.length; i++) {
 						var field = form.fields[i];
 						if(field.type == 'quantity' && field.productId == fieldId) {
 							return true;
 						}
 					}
 					return false;
 				},
 				
 				// Check if field is a custom quantity field
 				isCustomQtyField: function(fieldId) {
 					return typeof fieldId === 'string' && fieldId.indexOf('quantity_') === 0;
 				},
 				
 				// Get the product field ID from a quantity field ID
 				getCustomQtyFieldId: function(fieldId) {
 					return fieldId.replace('quantity_', '');
 				},
 
 				isQtyField: function(fieldId) {
+					if (typeof GetFieldById !== 'function') return false;
 					var field = GetFieldById(fieldId);
 					return field && field.type == 'quantity';
 				}
 				
 			};

77-94: Enhance conditional logic filter with validation and performance optimization.

The filter logic should include better validation and could be optimized for performance.

 			gform.addFilter('gform_conditional_logic_fields', function(options, form, selectedFieldId) {
+				if (!form || !form.fields || !Array.isArray(form.fields)) {
+					return options;
+				}
+				
 				for(var i = 0; i < form.fields.length; i++) {
 					var field = form.fields[i];
 					
+					// Skip if field is not valid
+					if (!field || !field.type || !field.id) {
+						continue;
+					}
+					
 					if(field.type != 'product' || 
 					   field.inputType != 'singleproduct' || 
 					   gwProductQuantityConditional.productHasQuantityField(field.id, form) || 
 					   field.disableQuantity) {
 						continue;
 					}
 
 					options.push({
 						label: (field.adminLabel ? field.adminLabel : field.label) + ' (Quantity)',
 						value: field.id,
 					});
 				}
 				return options;
 			});

88-92: Add fallback for missing field labels.

The label concatenation should handle cases where both adminLabel and label might be missing.

 					options.push({
-						label: (field.adminLabel ? field.adminLabel : field.label) + ' (Quantity)',
+						label: (field.adminLabel || field.label || 'Product Field ' + field.id) + ' (Quantity)',
 						value: field.id,
 					});

105-105: Consider using get_instance() method for consistency.

For consistency with the singleton pattern, consider using the get_instance() method instead of direct instantiation.

-new GW_Product_Quantity_Conditional();
+GW_Product_Quantity_Conditional::get_instance();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ad33967 and 73e6bef.

📒 Files selected for processing (1)
  • gravity-forms/gw-product-quantity-conditional.php (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Danger JS
  • GitHub Check: Danger JS
🔇 Additional comments (1)
gravity-forms/gw-product-quantity-conditional.php (1)

1-15: Plugin header looks good with clear documentation.

The plugin metadata is well-structured with appropriate description and links to instruction materials.

Comment on lines +27 to +31
public function __construct() {

add_action( 'admin_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 Gravity Forms dependency check.

The constructor doesn't verify that Gravity Forms is active, which could lead to fatal errors if the plugin is activated without Gravity Forms.

 	public function __construct() {
-
+		// Check if Gravity Forms is active
+		if ( ! class_exists( 'GFForms' ) ) {
+			add_action( 'admin_notices', array( $this, 'gravity_forms_required_notice' ) );
+			return;
+		}
+
 		add_action( 'admin_init', array( $this, 'init' ) );
-
 	}

Add the notice method:

public function gravity_forms_required_notice() {
	echo '<div class="notice notice-error"><p>GF Product Quantity Conditional requires Gravity Forms to be installed and activated.</p></div>';
}
🤖 Prompt for AI Agents
In gravity-forms/gw-product-quantity-conditional.php around lines 27 to 31, the
constructor lacks a check to verify if Gravity Forms is active, risking fatal
errors if this plugin is activated without Gravity Forms. Add a check in the
constructor to see if the Gravity Forms class or function exists; if not, hook a
method that displays an admin notice about the missing dependency. Implement the
gravity_forms_required_notice method to output an admin error notice informing
users that Gravity Forms must be installed and activated.

@spivurno
Copy link
Contributor

@saifsultanc Does this work on submission as well? I was expecting to see some PHP validation but maybe it's not required?

@saifsultanc
Copy link
Contributor Author

@saifsultanc Does this work on submission as well? I was expecting to see some PHP validation but maybe it's not required?

@spivurno Yup, it's works on submission. Tested it out. No PHP validation required!

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.

2 participants