2

I've created an ACF frontend form using acf_form; these fields are added to the User record on the backend; however because this form has required fields this means the admin cannot make basic changes to the user on the backend unless the user has filled in this form.

So I'm wondering if it's possible in certain situations to allow the admin to bypass being required to fill in required fields and if so, how do I go about doing this?

Brett
  • 19,449
  • 54
  • 157
  • 290

1 Answers1

3

Ok, found a way to do this - this is a way to do it for the User screen, it may differ for other post types.

We not only have to disable server side validation, but also client side validation, to do this, we do something a little like this:

add_action('acf/input/admin_head', 'my_acf_admin_head');

function my_acf_admin_head() {

    if (!function_exists('get_current_screen')) {
        return;
    }

    // Get current page/screen
    $screen = get_current_screen();

    // Get current user
    $user = wp_get_current_user();

    if (is_object($screen) and is_a($screen, 'WP_Screen')) {

        if (($screen->id == 'user-edit' or ($screen->id == 'user' and $screen->action == 'add')) and in_array('administrator', $user->roles)) {
            ?>
                <script type="text/javascript">
                    window.acf.validation.active = false;
                </script>
            <?php
        }

    }

}

This will add some Javascript to any page that matches our qualifers to disable ACF client-side validation.

Now, to disable backend validation, we do something like this:

add_action('acf/validate_save_post', 'my_acf_validate_save_post', 10, 0);

function my_acf_validate_save_post() {

    if (!function_exists('get_current_screen')) {
        return;
    }

    // Get current page/screen
    $screen = get_current_screen();

    // Get current user
    $user = wp_get_current_user();

    if (is_object($screen) and is_a($screen, 'WP_Screen')) {

        if (($screen->id == 'user-edit' or ($screen->id == 'user' and $screen->action == 'add')) and in_array('administrator', $user->roles)) {
            // clear all errors so they can bypass validation for user data
            acf_reset_validation_errors();
        }

    }

}

Note that because get_current_screen() isn't always available, these methods do not support front end forms.

Also note that this code could definitely be improved to be a lot more DRY, but I will leave that up to you. :)

Brett
  • 19,449
  • 54
  • 157
  • 290