Skip Navigation

[Resolved] Unique user field value form to prevent duplicate values

This thread is resolved. Here is a description of the problem and solution.

Problem:

The issue here is that the user wanted to ensure that only unique values can be entered into their custom field on their frontend form.

This means that 2 users can't have the same values in the custom fields.

Solution:

You can use the Toolset forms Validation hook to do this.

Add the following hook to your Toolset custom code section in Toolset->Custom Codes and enable it

/**
 * CRED custom validation to prevent duplicates CREATE FORM 
 */
add_filter( 'cred_form_validate', 'prevent_duplicate_submissions_registration' ,10,2);
function prevent_duplicate_submissions_registration( $error_fields, $form_data) {
    $nickname = $_POST['wpcf-form-field']; // Gets value from form
    $unique_field = 'wpcf-field-name';  // Meta key stored in db
      
    $form_ids = array( 69696969 );  // Edit IDs of CRED forms
   
    list( $fields,$errors ) = $error_fields;
   
    if ( in_array($form_data['id'], $form_ids ) ) {
  
        // Get existing posts with unique field
        $args = array(
            'meta_key' => $unique_field,
            'meta_value' => $nickname,
            'meta_compare' => '=' ,
            );
      
        $matching = new WP_User_Query( $args );
          
        $results = $matching->get_results();
        if ( !empty( $results ) ) {
            $errors[ $unique_field ] =  $nickname . ' is already in use. Choose a different name.';
        }
    }
   
    return array($fields,$errors);
};
  
/**
 * CRED custom validation to prevent duplicates EDIT FORM - excludes current user from the query as it will find a matching nickname
 */
add_filter( 'cred_form_validate', 'prevent_duplicate_submissions' ,10,2);
function prevent_duplicate_submissions( $error_fields, $form_data) {
    $current_user = get_current_user_id();
        $nickname = $_POST['wpcf-form-field']; // Gets value from form
    $unique_field = 'wpcf-field-name';  // Meta key stored in db
      
    $form_ids = array(  420420 );  // Edit IDs of CRED forms
   
    list( $fields,$errors ) = $error_fields;
   
    if ( in_array($form_data['id'], $form_ids ) ) {
  
        // Get existing posts with unique field
        $args = array(
            'meta_key' => $unique_field,
            'meta_value' => $nickname,
            'meta_compare' => '=' ,
            'exclude' => $current_user
            );
      
        $matching = new WP_User_Query( $args );
          
        $results = $matching->get_results();
        if ( !empty( $results ) ) {
            $errors[ $unique_field ] =  $nickname . ' is already in use. Choose a different name.';
        }
    }
   
    return array($fields,$errors);
};

Note this is for a user form and will need to be customized to work for posts, however in the case of a user form you will need to change the wpcf-form-field and wpcf-field-name to the slug of the field that you want to prevent the duplicate on while keeping the wpcf- prefix on the field slug.

This support ticket is created 3 years, 8 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 -
- 13:00 – 18:00 13:00 – 18:00 13:00 – 18:00 14:00 – 18:00 13:00 – 18:00 -

Supporter timezone: America/Jamaica (GMT-05:00)

Tagged: 

This topic contains 10 replies, has 2 voices.

Last updated by fredr 3 years, 8 months ago.

Assisted by: Shane.

Author
Posts
#1991017

Tell us what you are trying to do?

I need to make sure that a specific user field is unique (it is a company ID, created for a specific user role), when creating OR modifying the user.

Is there any documentation that you are following?

https://toolset.com/forums/topic/unique-user-field-value-form-to-prevent-duplicate-values/

This support link looks like a perfect answer to my problem. Bue it does not work in my case.
The user field is a toolset field, so I tried adding 'wpcf-' in front of the name, with no result.

Is there a similar example that we can see?

What is the link to your site?
hidden link
(password : reaumur)

#1991243

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi Fred,

Thank you for getting in touch, the code that you've provided should work fine.

/**
 * CRED custom validation to prevent duplicates CREATE FORM 
 */
add_filter( 'cred_form_validate', 'prevent_duplicate_submissions_registration' ,10,2);
function prevent_duplicate_submissions_registration( $error_fields, $form_data) {
    $nickname = $_POST['wpcf-form-field']; // Gets value from form
    $unique_field = 'wpcf-field-name';  // Meta key stored in db
     
    $form_ids = array( 69696969 );  // Edit IDs of CRED forms
  
    list( $fields,$errors ) = $error_fields;
  
    if ( in_array($form_data['id'], $form_ids ) ) {
 
        // Get existing posts with unique field
        $args = array(
            'meta_key' => $unique_field,
            'meta_value' => $nickname,
            'meta_compare' => '=' ,
            );
     
        $matching = new WP_User_Query( $args );
         
        $results = $matching->get_results();
        if ( !empty( $results ) ) {
            $errors[ $unique_field ] =  $nickname . ' is already in use. Choose a different name.';
        }
    }
  
    return array($fields,$errors);
};
 
/**
 * CRED custom validation to prevent duplicates EDIT FORM - excludes current user from the query as it will find a matching nickname
 */
add_filter( 'cred_form_validate', 'prevent_duplicate_submissions' ,10,2);
function prevent_duplicate_submissions( $error_fields, $form_data) {
    $current_user = get_current_user_id();
        $nickname = $_POST['wpcf-form-field']; // Gets value from form
    $unique_field = 'wpcf-field-name';  // Meta key stored in db
     
    $form_ids = array(  420420 );  // Edit IDs of CRED forms
  
    list( $fields,$errors ) = $error_fields;
  
    if ( in_array($form_data['id'], $form_ids ) ) {
 
        // Get existing posts with unique field
        $args = array(
            'meta_key' => $unique_field,
            'meta_value' => $nickname,
            'meta_compare' => '=' ,
            'exclude' => $current_user
            );
     
        $matching = new WP_User_Query( $args );
         
        $results = $matching->get_results();
        if ( !empty( $results ) ) {
            $errors[ $unique_field ] =  $nickname . ' is already in use. Choose a different name.';
        }
    }
  
    return array($fields,$errors);
};

Replace the form id value with the ID of your form, that means you will need to change 69696969 and 420420 to the ID of your Create and Edit form respectively.

Where did you add the code ? Please let me know so that I can assist better with this.

Thanks,
Shane

#1991385

I put all the code in the function.php file of my theme, and the form references are good.
But the error message saying that it is duplicate appears, and it does not save, even when I enter a new not-already-used value for the unique field.

#1992289

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi Fred,

Can you allow me to have admin access to the website so that I can have a look for you ?

I've enabled the private fields for your next response. Also please let me know the page where you are testing this out on.

Thanks,
Shane

#1992603

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi Fred,

The credentials that you've provided doesn't allow me to have access to the backend.

Could you update the user role to admin so that I can have a look.

Thanks,
Shane

#1993163

Sorry, my mistake.
The user role is ok now.

#1993165
#1993573

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi Fred,

Not sure what you did but this exact code below works fine.

/**
 * CRED custom validation to prevent duplicates CREATE FORM 
 */
add_filter( 'cred_form_validate', 'prevent_duplicate_submissions_registration' ,10,2);
function prevent_duplicate_submissions_registration( $error_fields, $form_data) {
    $nickname = $_POST['wpcf-siren']; // Gets value from form
    $unique_field = 'wpcf-siren';  // Meta key stored in db
      
    $form_ids = array( 3862 );  // Edit IDs of CRED forms
   
    list( $fields,$errors ) = $error_fields;
   
    if ( in_array($form_data['id'], $form_ids ) ) {
  
        // Get existing posts with unique field
        $args = array(
            'meta_key' => $unique_field,
            'meta_value' => $nickname,
            'meta_compare' => '=' ,
            );
      
        $matching = new WP_User_Query( $args );
          
        $results = $matching->get_results();
        if ( !empty( $results ) ) {
            $errors[ $unique_field ] =  $nickname . ' is already in use. Choose a different name.';
        }
    }
   
    return array($fields,$errors);
};

I was not able to create a new user with a duplicate siren number. I've left the code so you can test it with the siren number 451829121 which comes from this user below.
hidden link

You won't be able to create another user with this number.

Thanks,
Shane

#1993767

You are right : it is impossible to create a new user with a duplicate siren number.

But the situation is not better : if you try to create a new user with a new, unused siren number, the same error message appears, saying that this siren number already exists... Impossible to register a new user with that role when that code is inserted in the functions.php.

I cannot understand why.

#1993789

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi Fred,

I've found the issue. My exact code that I sent you previously works. The problem was that on your development site you had this on line 239

        $siren = $_POST['siren']; // Gets value from form

When it should've been.

        $siren = $_POST['wpcf-siren']; // Gets value from form

Notice the use of the wpcf- prefix.

It should now be working and you can go ahead and test it to verify.

Thanks,
Shane

#1993809

Thanks a lot ! It works. I should have seen the mistake.
Have a great day.