Skip to content

gw-conditional-logic-operator-does-not-contain.php: Added snippet for does not contain conditional logic comparison. #1073

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/2901482497/81913

Summary

Snippet that adds 'does not contain' operator for conditional logic comparison

Inspired from https://gravitywiz.com/snippet-library/gw-conditional-logic-operator-is-in/

Loom Demo:
https://www.loom.com/share/8e1b27ec47b341dbb4f0da2bec6a960b

…or does not contain conditional logic comparison.
Copy link

coderabbitai bot commented Apr 14, 2025

Walkthrough

A new PHP class, GF_CLO_Does_Not_Contain, is introduced in the Gravity Forms codebase to implement a custom "does not contain" conditional logic operator. This class hooks into the system on the init action, registers multiple filters, outputs inline and form scripts, and implements evaluation logic. The functionality includes JavaScript integration for the operator display, logic evaluation in PHP, conversion of conditions to SQL-friendly formats, and checks to confirm form applicability.

Changes

File Path Change Summary
gravity-forms/.../gw-conditional-logic-operator-does-not-contain.php Added new PHP class GF_CLO_Does_Not_Contain implementing the "does not contain" operator for conditional logic. The class registers scripts, outputs inline admin scripts, provides JavaScript evaluation logic, whitelists the operator, converts conditions for SQL queries, and checks form applicability.

Sequence Diagram(s)

sequenceDiagram
    participant Init as "WordPress Init"
    participant GF as "Gravity Forms System"
    participant CLO as "GF_CLO_Does_Not_Contain"
    participant Admin as "Admin Interface"
    participant Form as "Form Frontend"
    participant DB as "Database"

    Init->>CLO: Instantiate on init action
    CLO->>GF: Register filters (operator whitelist, script output, evaluation logic)
    GF->>Admin: Request inline script output
    CLO->>Admin: Output JS variable & function for "does not contain" operator
    GF->>Form: Check if form supports conditional logic
    Form->>CLO: Call load_form_script to attach necessary scripts
    Form->>CLO: Evaluate condition with evaluate_operator
    CLO->>CLO: Execute "does not contain" logic check
    CLO->>DB: Convert operator to SQL ("NOT LIKE") format for field filters
Loading

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ 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

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 8ef65ea

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

🧹 Nitpick comments (5)
gravity-forms/gw-conditional-logic-operator-does-not-contain.php (5)

34-50: Consider adding admin capability check for additional security

While the current page check provides some protection, consider also checking for appropriate admin capabilities before outputting the script.

public function output_admin_inline_script() {
-	if ( ! GFForms::get_page() && ! is_admin() && ! in_array( rgget( 'page' ), array( 'gp-email-users' ) ) ) {
+	if ( ( ! GFForms::get_page() && ! is_admin() && ! in_array( rgget( 'page' ), array( 'gp-email-users' ) ) ) || ! current_user_can( 'manage_options' ) ) {
		return;
	}

119-133: Consider adding type checking for more robust evaluation

The operator evaluation could be more defensive by ensuring both values are strings before performing the string operation.

// If the field contains the target value, it's not a match.
-$is_match = strpos( $field_value, $target_value ) === false;
+$is_match = is_string( $field_value ) && is_string( $target_value ) ? 
+    strpos( (string) $field_value, (string) $target_value ) === false : 
+    true;

106-109: Add option for case-insensitive matching

Consider adding an option for case-insensitive matching, which would be useful in many scenarios.

This would require modifications to both the JavaScript and PHP evaluation functions to support a case-insensitive option, potentially using toLowerCase() in JavaScript and stripos() in PHP.


158-160: Consider making the class instantiation filterable

For maximum flexibility, consider wrapping the class instantiation in a conditional that can be filtered.

# Configuration
-
-new GF_CLO_Does_Not_Contain();
+if ( apply_filters( 'gw_enable_clo_does_not_contain', true ) ) {
+    new GF_CLO_Does_Not_Contain();
+}

127-128: Add documentation for the evaluation logic

While the comment is helpful, consider adding more detailed documentation to explain the evaluation logic, especially for developers who might extend this functionality.

-// If the field contains the target value, it's not a match.
+/**
+ * Evaluate if the field value does NOT contain the target value.
+ * 
+ * strpos() returns false when the needle is not found in the haystack.
+ * Therefore, if strpos() returns false, it means the target value is not 
+ * contained in the field value, which is what we want for "does not contain".
+ */
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0390f25 and 8ef65ea.

📒 Files selected for processing (1)
  • gravity-forms/gw-conditional-logic-operator-does-not-contain.php (1 hunks)
🔇 Additional comments (3)
gravity-forms/gw-conditional-logic-operator-does-not-contain.php (3)

1-15: Well-structured plugin header with clear documentation

The plugin header follows WordPress standards and provides clear information about the functionality. Including the Loom instruction video link is a thoughtful addition for users who prefer visual instructions.


16-32: Good initialization with proper hook registration

The class is properly initialized with appropriate hooks into Gravity Forms' conditional logic system. The hook structure follows WordPress best practices.


135-151: Good SQL conversion for the new operator

The conversion to SQL-compatible field filters is well-implemented, properly adding wildcards for the LIKE operator and converting to NOT LIKE for the containment check.

Comment on lines +64 to +88
<script type="text/javascript">
( function( $ ) {

window.GWCLODoesNotContain = function( args ) {

var self = this;

for ( var prop in args ) {
if ( args.hasOwnProperty( prop ) ) {
self[ prop ] = args[ prop ];
}
}

self.init = function() {
gform.addFilter( 'gform_is_value_match', function( isMatch, formId, rule ) {

if ( rule.operator !== 'does_not_contain' ) {
return isMatch;
}

var fieldValue = $( '#input_' + formId + '_' + rule.fieldId ).val();
isMatch = fieldValue.indexOf( rule.value ) === -1;

return isMatch;
} );
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 type checking to prevent JavaScript errors

The JavaScript code assumes fieldValue is always a string. Add type checking to prevent potential errors when handling null or undefined values.

var fieldValue = $( '#input_' + formId + '_' + rule.fieldId ).val();
-isMatch = fieldValue.indexOf( rule.value ) === -1;
+isMatch = typeof fieldValue === 'string' && fieldValue.indexOf( rule.value ) === -1;
📝 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
<script type="text/javascript">
( function( $ ) {
window.GWCLODoesNotContain = function( args ) {
var self = this;
for ( var prop in args ) {
if ( args.hasOwnProperty( prop ) ) {
self[ prop ] = args[ prop ];
}
}
self.init = function() {
gform.addFilter( 'gform_is_value_match', function( isMatch, formId, rule ) {
if ( rule.operator !== 'does_not_contain' ) {
return isMatch;
}
var fieldValue = $( '#input_' + formId + '_' + rule.fieldId ).val();
isMatch = fieldValue.indexOf( rule.value ) === -1;
return isMatch;
} );
<script type="text/javascript">
( function( $ ) {
window.GWCLODoesNotContain = function( args ) {
var self = this;
for ( var prop in args ) {
if ( args.hasOwnProperty( prop ) ) {
self[ prop ] = args[ prop ];
}
}
self.init = function() {
gform.addFilter( 'gform_is_value_match', function( isMatch, formId, rule ) {
if ( rule.operator !== 'does_not_contain' ) {
return isMatch;
}
var fieldValue = $( '#input_' + formId + '_' + rule.fieldId ).val();
isMatch = typeof fieldValue === 'string' && fieldValue.indexOf( rule.value ) === -1;
return isMatch;
} );

Comment on lines +84 to +85
var fieldValue = $( '#input_' + formId + '_' + rule.fieldId ).val();
isMatch = fieldValue.indexOf( rule.value ) === -1;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve form field value retrieval for complex field types

The current implementation only handles simple input fields. Consider enhancing to support complex field types like checkboxes, radio buttons, and multi-selects.

-var fieldValue = $( '#input_' + formId + '_' + rule.fieldId ).val();
+var fieldValue = '';
+var $field = $( '#input_' + formId + '_' + rule.fieldId );
+
+// Handle different field types
+if ( $field.is(':checkbox') || $field.is(':radio') ) {
+    fieldValue = $field.filter(':checked').map(function() { 
+        return this.value; 
+    }).get().join(',');
+} else if ( $field.is('select[multiple]') ) {
+    fieldValue = $field.val() ? $field.val().join(',') : '';
+} else {
+    fieldValue = $field.val() || '';
+}
📝 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
var fieldValue = $( '#input_' + formId + '_' + rule.fieldId ).val();
isMatch = fieldValue.indexOf( rule.value ) === -1;
var fieldValue = '';
var $field = $( '#input_' + formId + '_' + rule.fieldId );
// Handle different field types
if ( $field.is(':checkbox') || $field.is(':radio') ) {
fieldValue = $field.filter(':checked').map(function() {
return this.value;
}).get().join(',');
} else if ( $field.is('select[multiple]') ) {
fieldValue = $field.val() ? $field.val().join(',') : '';
} else {
fieldValue = $field.val() || '';
}
isMatch = fieldValue.indexOf( rule.value ) === -1;

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