Support

Account

Home Forums ACF PRO Multiple user acf_forms on one page with validation

Helping

Multiple user acf_forms on one page with validation

  • I’ve looked through the forum and have seen something similar to my issue, but never quite the same. The closest that came to my issue was never resolved: https://support.advancedcustomfields.com/forums/topic/acf_form-id-not-being-set-from-args/

    Anyway, here goes.

    I have a frontend where multiple users are listed on a single page, each with their won acf_form. During validation, the values of the correct form are submitted, but the _acf_form and post_id values are always taken from the last form on the page. Here’s the simplified code:

    <?php
    foreach($users as $user) {
      acf_form(array(
        'id' => 'user-form-' . $user->ID,
        'post_id' => 'user_' . $user->ID,
        'fields' => array(
          'firstname',
          'lastname',
          'email'
        )
      ));
    }
    

    and then the verification hook:

    
    function my_validate_value_email($valid, $value, $field, $input) {
      $user_id = substr($_POST['post_id'], 5);
      $user = get_user_by('email', $value);
      return $user && $user->ID != $user_id ? __('Email already exists', 'text-domain') : $valid;
    }
    add_filter('acf/validate_value/name=email', 'my_validate_value_email', 10, 4);
    

    Now when I view the page, the form IDs are all correct, and the data is pre-filled correctly. But when I click on “save” for the first user, then the form data that is submitted for verification is correct except for post_id = user_{last-user-id}, meaning every time I just try to save a user that is not the last user in the list, then I get the “email already exists” error.

    I’m using ACF Pro 5.5.3 if that helps.

  • Hi @deejayfaggyfag

    That’s sure weird. Could you please open a new ticket so it can be passed to the plugin author? You can open a new ticket here: https://support.advancedcustomfields.com/new-ticket. Also, please don’t forget to explain the issue again and provide the link to this thread.

    As a workaround, you can get the correct data from the _acf_form form data like this:

    function my_validate_value_email($valid, $value, $field, $input) {
        
        // get the encrypted form data
        $data = acf_extract_var($_POST, '_acf_form');
        
        // decode the form data
        $data = @json_decode(base64_decode($data), true);
        
        // get the correct post ID
        $user_id = $data['post_id'];
        
        $user_id = substr($_POST['post_id'], 5);
        $user = get_user_by('email', $value);
        return $user && $user->ID != $user_id ? __('Email already exists', 'text-domain') : $valid;
    }
    add_filter('acf/validate_value/name=email', 'my_validate_value_email', 10, 4);

    I hope this helps ๐Ÿ™‚

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.