ACF | Problem with conditional fields values

1k Views Asked by At

So I'm dealing with quite a weird issue with ACF.

  1. I have field B, which is set to appear only if field A == true. If A == true, B appears and I can change its value.
  2. In a given post, I have A == true and then I set a value to B. I save the post. All is well with the world.
  3. I then change my mind and I find that I do not want to have A == true, I want A == false. Field B disappears, as expected.

Problem: While field B disappears as expected, its value is still saved in the post and its still showing in the frontend.

My expectation: Since field B is hidden, it should have its value erased.

Has anyone else faced this issue? Am I wrong to expect that behaviour?

2

There are 2 best solutions below

0
On

The behavious is as it is and this has the advantage, that when switch A back to true, B has it's old value again.

So you have to an if query in your code to use B only if A == true.

0
On

Adding to @Keks, that this is the correct behaviour, as the value for Field B hasn't been changed by the user, even if the field has been conditionally hidden. Conditional hiding is a user-interface function and does not change values, and should not default to changing values. If one doesn't want to display the value of Field B under certain conditions, they should use an if-statement or equivalent, before displaying the other value.

$field_A = get_field('field_A', $post_id);

if(true == $field_A) {         
    the_field('field_B', $post_id);
}

If you need to conditionally change or clear a value in Field B you can do this when the post is saved by hooking into the acf/save_post. You could run this before or after saving the post, but you should do it after, so that you also clear any Field B values previously saved in the database. So use the action with a priority >10.

add_action('acf/save_post', 'conditionally_clear_field_B', 11);   
function conditionally_clear_field_B($post_id) {

    $field_A = get_field('field_A', $post_id);
    
    if(true == $field_A) {         
        update_field('field_B', '', $post_id);
    }
};

This way, as already said, you also keep selected Field B values available until the user has indicated their commitment to a Field A value by saving the post.