Skip to content

gw-require-alt-text-description-post-image.php: Added snippet for requiring Alt Text and Description in Post Image Field. #1077

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/2907346978/82160

Summary

Required Alt Text & Description for Post Image Field by leveraging gform_field_validation for the logic.

How this update works:
https://www.loom.com/share/6d0e70da14c64f5ea40d0aa0f918684d

…equiring Alt Text and Description in Post Image Field.
Copy link

coderabbitai bot commented Apr 16, 2025

Walkthrough

A new Gravity Forms plugin file has been added to require the Alt Text and Description subfields for Post Image fields when those fields are set as required. The plugin uses the gform_field_validation filter to check submitted form values and returns specific error messages if either or both subfields are missing. The validation logic is only applied when the Post Image field is configured to display both subfields and is marked as required. Plugin metadata and an instructional video link are included in the file header.

Changes

File(s) Change Summary
gravity-forms/gw-require-alt-text-description-post-image.php Added new plugin to enforce required Alt Text and Description for required Post Image fields in Gravity Forms.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant GravityForms
    participant Plugin

    User->>GravityForms: Submit form with Post Image field
    GravityForms->>Plugin: Trigger gform_field_validation filter
    Plugin->>GravityForms: Validate Alt Text and Description subfields
    alt Both subfields missing
        Plugin-->>GravityForms: Mark field invalid, return combined error
    else Only Alt Text missing
        Plugin-->>GravityForms: Mark field invalid, return Alt Text error
    else Only Description missing
        Plugin-->>GravityForms: Mark field invalid, return Description error
    else Both present
        Plugin-->>GravityForms: Mark field valid
    end
    GravityForms-->>User: Display validation result
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 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 2f377f7

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 (3)
gravity-forms/gw-require-alt-text-description-post-image.php (3)

17-18: Consider using strict comparison for field type check.

The field type comparison should use strict comparison (===) instead of loose comparison (==) to avoid potential type juggling issues in PHP.

- if ( $field->type == 'post_image' && $field->displayAlt && $field->displayDescription && $field->wasRequired ) {
+ if ( $field->type === 'post_image' && $field->displayAlt && $field->displayDescription && $field->wasRequired ) {

20-21: Document the meaning of array indices for better code maintainability.

The hard-coded array keys .2 and .7 aren't immediately clear. Consider adding a comment explaining that these are Gravity Forms' specific indices for Alt Text and Description fields.

+ // Gravity Forms stores Alt Text at index .2 and Description at index .7 for Post Image fields
  $alt_text    = $value[ $field->id . '.2' ];
  $description = $value[ $field->id . '.7' ];

17-36: Consider field-specific customization options for more flexibility.

The current implementation uses the same error messages for all Post Image fields. For greater flexibility, consider adding options to customize error messages per field or specify which fields should enforce this validation using field IDs.

 add_filter( 'gform_field_validation', function ( $result, $value, $form, $field ) {
-	if ( $field->type === 'post_image' && $field->displayAlt && $field->displayDescription && $field->wasRequired ) {
+	// Optional: Define specific field IDs that should enforce this validation
+	$enforce_for_fields = apply_filters( 'gw_require_alt_desc_field_ids', array() );
+	
+	if ( $field->type === 'post_image' && $field->wasRequired &&
+	    ( $field->displayAlt && $field->displayDescription || in_array( $field->id, $enforce_for_fields ) ) ) {

		$alt_text    = $value[ $field->id . '.2' ];
		$description = $value[ $field->id . '.7' ];
+
+		// Optional: Allow customizing error messages per field
+		$messages = apply_filters( 'gw_require_alt_desc_messages', array(
+			'both'        => esc_html__( 'Check Post Image. Please enter Alt Text and Description.', 'gw-require-alt-text' ),
+			'alt_text'    => esc_html__( 'Check Post Image. Please enter Alt Text.', 'gw-require-alt-text' ),
+			'description' => esc_html__( 'Check Post Image. Please enter Description.', 'gw-require-alt-text' ),
+		), $field );
📜 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 2f377f7.

📒 Files selected for processing (1)
  • gravity-forms/gw-require-alt-text-description-post-image.php (1 hunks)
🔇 Additional comments (2)
gravity-forms/gw-require-alt-text-description-post-image.php (2)

1-16: Good documentation and metadata structure in the plugin header.

The plugin header follows WordPress standards with clear description, version information, and includes an instruction video link which is helpful for users.


17-36:

❓ Verification inconclusive

Verify image field validation logic is consistent with user expectations.

The current implementation validates Alt Text and Description only when both display options are enabled and the field is required. However, there could be cases where users want to validate these fields individually based on their own display settings.


🏁 Script executed:

#!/bin/bash
# Check if there are any similar snippets in the repository that handle Post Image validation
fd -e php -x grep -l "post_image.*validation\|gform_field_validation.*post_image" {}

Length of output: 88


Action Required: Verify Post Image Field Validation Logic

The current implementation validates both Alt Text and Description only when both display options (displayAlt and displayDescription) are enabled and the field is required. This means that if users intend to validate only one of the options (for instance, when only one display option is active), the validation won’t be triggered.

Please verify if this behavior meets user expectations or if the logic should allow independent validation when only one of the options is enabled. If independent validation is desired, update the conditions accordingly.

Comment on lines +23 to +32
if ( ! $alt_text && ! $description ) {
$result['is_valid'] = false;
$result['message'] = 'Check Post Image. Please enter Alt Text and Description.';
} elseif ( ! $alt_text ) {
$result['is_valid'] = false;
$result['message'] = 'Check Post Image. Please enter Alt Text.';
} elseif ( ! $description ) {
$result['is_valid'] = false;
$result['message'] = 'Check Post Image. Please enter Description.';
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Implement internationalization for user-facing messages.

Error messages should use WordPress internationalization functions to support translation. Also, consider using more robust empty value checking with empty() instead of just negation.

- if ( ! $alt_text && ! $description ) {
+ if ( empty( $alt_text ) && empty( $description ) ) {
  	$result['is_valid'] = false;
-   $result['message']  = 'Check Post Image. Please enter Alt Text and Description.';
+   $result['message']  = esc_html__( 'Check Post Image. Please enter Alt Text and Description.', 'gw-require-alt-text' );
- } elseif ( ! $alt_text ) {
+ } elseif ( empty( $alt_text ) ) {
  	$result['is_valid'] = false;
-   $result['message']  = 'Check Post Image. Please enter Alt Text.';
+   $result['message']  = esc_html__( 'Check Post Image. Please enter Alt Text.', 'gw-require-alt-text' );
- } elseif ( ! $description ) {
+ } elseif ( empty( $description ) ) {
  	$result['is_valid'] = false;
-   $result['message']  = 'Check Post Image. Please enter Description.';
+   $result['message']  = esc_html__( 'Check Post Image. Please enter Description.', 'gw-require-alt-text' );
  }
📝 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
if ( ! $alt_text && ! $description ) {
$result['is_valid'] = false;
$result['message'] = 'Check Post Image. Please enter Alt Text and Description.';
} elseif ( ! $alt_text ) {
$result['is_valid'] = false;
$result['message'] = 'Check Post Image. Please enter Alt Text.';
} elseif ( ! $description ) {
$result['is_valid'] = false;
$result['message'] = 'Check Post Image. Please enter Description.';
}
if ( empty( $alt_text ) && empty( $description ) ) {
$result['is_valid'] = false;
$result['message'] = esc_html__( 'Check Post Image. Please enter Alt Text and Description.', 'gw-require-alt-text' );
} elseif ( empty( $alt_text ) ) {
$result['is_valid'] = false;
$result['message'] = esc_html__( 'Check Post Image. Please enter Alt Text.', 'gw-require-alt-text' );
} elseif ( empty( $description ) ) {
$result['is_valid'] = false;
$result['message'] = esc_html__( 'Check Post Image. Please enter Description.', 'gw-require-alt-text' );
}

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