AdvancedCustomFields / acf

Advanced Custom Fields
http://advancedcustomfields.com/
823 stars 168 forks source link

Changing field to not be required using `acf/prepare_field` fails validation #890

Closed crstauf closed 6 months ago

crstauf commented 6 months ago

Describe the bug A field is set as required in the field group. Using the acf/prepare_field/type=image filter, I'm changing the required parameter to false. However, when saving the page, the validation fails, and says the field is required. I suspect that acf/prepare_field is being called after the JavaScript has determined which fields to check for values. This order needs to be fixed.

My use-case is that during development we don't always have the images, so disabling the required parameter in those environments allows us to keep the requirement for staging and production environments.

To Reproduce Steps to reproduce the behavior:

  1. Create a field with the Required toggle on
  2. Create a filter with acf/prepare_field and set required parameter to false
  3. Notice that the asterisk is removed (indicating field is optional)
  4. Attempt to save the post/page, and notice the error stating field is required

Expected behavior Fields that aren't marked as required should not be required.

Screenshots or Video 2023-12-28T221405

Code

add_filter( 'acf/prepare_field/type=image', static function ( array $field ) : array {
    if ( ! in_array( wp_get_environment_type(), array( 'local', 'development' ) ) ) {
        return $field;
    }

    if ( empty( $field['required'] ) ) {
        return $field;
    }

    $field['required'] = false;
    $field['label']   .= ' <span style="color: #f00;" title="Required, but disabled in dev environment">*</span>';

    return $field;
}
{
    "key": "field_658d93b96c423",
    "label": "Desktop",
    "name": "desktop",
    "aria-label": "",
    "type": "image",
    "instructions": "",
    "required": 1,
    "conditional_logic": 0,
    "wrapper": {
        "width": "50",
        "class": "",
        "id": ""
    },
    "return_format": "array",
    "library": "all",
    "min_width": 600,
    "min_height": "",
    "min_size": "",
    "max_width": "",
    "max_height": "",
    "max_size": "0.65",
    "mime_types": "",
    "preview_size": "medium"
}

Version Information:

crstauf commented 6 months ago

True to form, as soon as I post this, I find acf/load_field: going to try that, and will close this issue if that works.

crstauf commented 6 months ago

Ugh, sure enough. My apologies. 😥