Support

Account

Home Forums General Issues Validate Front End Form Submission – Unique Values only

Solved

Validate Front End Form Submission – Unique Values only

  • Hi all,

    I have a site that allows a person to apply online for a vacancy. I have created the front-end form and that works perfectly.

    As part of the form I ask users for their email address and automatically populate the vacancy they are applying for into a ‘Vacancy Applied For’ field.

    What I am trying to do now is extend the code to not allow the front end form to submit/save if a user has already tried to apply for the same vacancy before using the vacancy and email fields as unique identifiers.

    I have the following code added to my functions.php file but it still allows the user to submit the form without showing any validation errors.

    add_filter('acf/validate_value/', 'acf_duplicate_candidate_application', 10, 4);
      
    function acf_duplicate_candidate_application($valid, $value, $field, $input) {
        if (!$valid || (!isset($_POST['post_ID']) && !isset($_POST['post_id']))) {
          return $valid;
        }
        if (isset($_POST['post_ID'])) {
          $post_id = intval($_POST['post_ID']);
        } else {
          $post_id = intval($_POST['post_id']);
        }
        if (!$post_id) {
          return $valid;
        }
        $post_type = get_post_type($post_id);
        $candidate_email = $field['candidate_email'];
        $vacancy_applied_for = $field['vacancy_applied_for'];
        $args = array(
          'post_type' => $post_type,
          'post_status' => 'publish, draft, trash',
          'post__not_in' => array($post_id),
          'meta_query' => array(
              'relation' => 'AND',
            array(
              'key' => $candidate_email,
              'value' => $value
            ),
            array(
              'key' => $vacancy_applied_for,
              'value' => $value
            )
          )
        );
        $query = new WP_Query($args);
        if (count($query->posts)){
          return 'This Value is not Unique.';
        }
        return true;
    }

    I found tried to edit the above code snippet from the following forum topic: https://support.advancedcustomfields.com/forums/topic/accept-only-unique-values/#post-45359. but no luck.

    Any help would be awesome!

  • 
    // your should only be testing the vacancy field
    // insert the field key of your field here
    add_filter('acf/validate_value/key=field_YYYYYYY', 'acf_duplicate_candidate_application', 10, 4);
    
    function acf_duplicate_candidate_application($valid, $value, $field, $input) {
      // acf now uses $_POST['_acf_post_id']
      // the other $_POST indexes may not be available on the front end
      if (!$valid || !isset($_POST['_acf_post_id'])) {
        return $valid;
      }
      $post_id = intval($_POST['_acf_post_id']);
      $post_type = get_post_type($post_id);
      
      // to get pother values submitted you must look in $_POST['acf'][$field_key]
      $candidate_email = $_POST['acf']['field_XXXXXXX']; // field key of email field
      
      $args = array(
        'post_type' => $post_type,
        'post_status' => 'publish, draft, trash', // double check possible post statuses 
        'post__not_in' => array($post_id),
        'meta_query' => array(
          'relation' => 'AND',
          array(
            'key' => 'candidate_email', // field name
            'value' => $candidate_email
          ),
          array(
            'key' => 'vacancy_applied_for', // field name
            'value' => $value
          )
        )
      );
      $query = new WP_Query($args);
      if (count($query->posts)){
        return 'You have already applied for this vacancy.';
      }
      return true;
    }
    
  • Hi John,

    Thanks for the pointers – I have added the above to functions.php and edited to add in the relevant field keys but am still not having any luck.

    The validation works if I add in an OR relation so looks like the vacancy applied for side of things is working but the candidate email value doesn’t seem to be working.

    Tried also swapping things around to have it check against the candidate_email field and works again if I use an OR relation but not with the AND.

    // Validate application is not a duplicate
    add_filter('acf/validate_value/key=field_5dba152669aaf', 'acf_duplicate_candidate_application', 10, 4);
    
    function acf_duplicate_candidate_application($valid, $value, $field, $input) {
      // acf now uses $_POST['_acf_post_id']
      // the other $_POST indexes may not be available on the front end
      if (!$valid || !isset($_POST['_acf_post_id'])) {
        return $valid;
      }
      $post_id = intval($_POST['_acf_post_id']);
      $post_type = get_post_type($post_id);
      
      // to get other values submitted you must look in $_POST['acf'][$field_key]
      $candidate_email = $_POST['acf']['field_5db9db5da28c0']; // field key of email field
      
      $args = array(
        'post_type' => 'candidates',
        'post_status' => 'publish', // double check possible post statuses 
        'post__not_in' => array($post_id),
        'meta_query' => array(
          'relation' => 'AND',
          array(
            'key' => 'candidate_email', // field name
            'value' => $candidate_email
          ),
          array(
            'key' => 'vacancy_applied_for', // field name
            'value' => $value
          )
        )
      );
      $query = new WP_Query($args);
      if (count($query->posts)){
        return 'You have already applied for this post.  Please content OHSC HR via email to update your application if you want to submit additional information.  Alternatively you can apply for other vacancies <a href="#">here</a>';
      }
      return true;
    }
    

    Here is the current code snippet. Not sure what the issue is.

  • what type of field is the email field?

  • It’s a ACF email field.

    the vacancy field is a text field.

  • Is it a sub field of a repeater of anything like that?

  • Nope – its not.

    And no other code targeted at this particular field other than registering the form itself and setting candidate email as an admin column on my post type in Wp-Admin.

    Here the form code for reference:

    // 1. Candidate Application Form
    
        //Defines the fields to display
        $fields = array(
            'field_5db9db36a28bf',	    // candidate first name
            'field_5e06338abb373',      // candidate last name
            'field_5db9db5da28c0',	    // candidate email
            'field_5db9dc8ca28c1',	    // candidate contact number
            'field_5dcc08f0a11b5',      // candidate gender
            'field_5dcc092ba11b6',      // candidate race
            'field_5dcc09e2a11b7',      // candidate nationality check
            'field_5dcc0a32a11b8',      // candidate nationality
            'field_5e42e3cf90206',      // candidate work permit check
            'field_5e42e43490207',      // candidate work permit doc
            'field_5e42e30990204',      // candidate notice period
            'field_5e42e35190205',      // candidate disability check
            'field_5e42e47390208',      // candidate criminal record check
            'field_5e5bf8b8e879b',      // candidate language proficiency
            'field_5db9dd10a28c2',	    // candidate cv
            'field_5db9ddf5a28c4',      // candidate supporting docs
            'field_5dba152669aaf',      // candidate vacancy applied for
            'field_5dcc0f15030b6',       // candidate disclaimer
            'field_5ec4e941df19d'       // duplicate check
    
        );
    
        // Sets the ACF Form
        acf_register_form(
    
        // Defines all the settings associated with the ACF Form 
        array(
    
            /* (string) Unique identifier for the form. Defaults to 'acf-form' */
            'id' => 'acf-candidate-application-form',
    
            /* (int|string) The post ID to load data from and save data to. Defaults to the current post ID. 
            Can also be set to 'new_post' to create a new post on submit */
            'post_id' => 'new_post',
    
            /* (array) An array of post data used to create a post. See wp_insert_post for available parameters.
            The above 'post_id' setting must contain a value of 'new_post' */
            'new_post' => array(
                'post_type'		=> 'candidates',
                'post_status'	=> 'publish',
            ),
    
            /* (array) An array of field group IDs/keys to override the fields displayed in this form */
            'field_groups' => false,
    
            /* (array) An array of field IDs/keys to override the fields displayed in this form */
            'fields' => $fields,
    
            /* (boolean) Whether or not to show the post title text field. Defaults to false */
            'post_title' => false,
    
            /* (boolean) Whether or not to show the post content editor field. Defaults to false */
            'post_content' => false,
    
            /* (boolean) Whether or not to create a form element. Useful when a adding to an existing form. Defaults to true */
            'form' => true,
    
            /* (array) An array or HTML attributes for the form element */
            'form_attributes' => array(),
    
            /* (string) The URL to be redirected to after the form is submit. Defaults to the current URL with a GET parameter '?updated=true'.
            A special placeholder '%post_url%' will be converted to post's permalink (handy if creating a new post)
            A special placeholder '%post_id%' will be converted to post's ID (handy if creating a new post) */
            //'return' => home_url('candidate-application-success'),
    
            /* (string) Extra HTML to add before the fields */
            'html_before_fields' => '',
    
            /* (string) Extra HTML to add after the fields */
            'html_after_fields' => '',
    
            /* (string) The text displayed on the submit button */
            'submit_value' => __("Submit Application", 'acf'),
    
            /* (string) A message displayed above the form after being redirected. Can also be set to false for no message */
            'updated_message' => __("Application successfully submitted", 'acf'),
    
            /* (string) Determines where field labels are places in relation to fields. Defaults to 'top'. 
            Choices of 'top' (Above fields) or 'left' (Beside fields) */
            'label_placement' => 'left',
    
            /* (string) Determines where field instructions are places in relation to fields. Defaults to 'label'. 
            Choices of 'label' (Below labels) or 'field' (Below fields) */
            'instruction_placement' => 'field',
    
            /* (string) Determines element used to wrap a field. Defaults to 'div' 
            Choices of 'div', 'tr', 'td', 'ul', 'ol', 'dl' */
            'field_el' => 'div',
    
            /* (string) Whether to use the WP uploader or a basic input for image and file fields. Defaults to 'wp' 
            Choices of 'wp' or 'basic'. Added in v5.2.4 */
            'uploader' => 'basic',
    
            /* (boolean) Whether to include a hidden input field to capture non human form submission. Defaults to true. Added in v5.3.4 */
            'honeypot' => true,
    
            /* (string) HTML used to render the updated message. Added in v5.5.10 */
            'html_updated_message'	=> '<div id="message" class="updated"><p>%s</p></div>',
    
            /* (string) HTML used to render the submit button. Added in v5.5.10 */
            'html_submit_button'	=> '<input type="submit" class="acf-button button button-primary button-large" value="%s" />',
    
            /* (string) HTML used to render the submit button loading spinner. Added in v5.5.10 */
            'html_submit_spinner'	=> '<span class="acf-spinner"></span>',
    
            /* (boolean) Whether or not to sanitize all $_POST data with the wp_kses_post() function. Defaults to true. Added in v5.6.5 */
            'kses'	=> true
    
        )
    );

    Running ACF Pro v 5.8.6

  • I can’t see anything here that would cause it to not work.

    Possibilities

    candidate_email is incorrect, double check the field name

    Double check that the field key you’re validating is the key for the email field.

    The value of the field submitted through ACF does not match what is stored in the DB.

    Simple Test:

    
    add_filter('acf/validate_value/key=field_5db9db5da28c0', 'acf_duplicate_candidate_application', 10, 4);
    
    function acf_duplicate_candidate_application($valid, $value, $field, $input) {
      $post_id = intval($_POST['_acf_post_id']);
      $current_value = get_field($field['key'];
      return $post_id.' '.$value.' '.$current_value;
    }
    
  • Hi John,

    Found the mistake – I added in [$value] on this line by mistake -> $candidate_email = $_POST[‘acf’][‘field_5db9db5da28c0’];

    All working as it should now. πŸ™‚

    Thanks so much for the help – much appreciated!

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

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.