Saltar navegación

[Resuelto] Field validation of post form

Este hilo está resuelto. Aquí tiene una descripción del problema y la solución.

Problem: I would like to add custom validation to a Form that tests to see if any other post has the same custom field value. If so, an error should be displayed.

Solution: Use the Forms validation API to query posts by meta key and value:

add_filter( 'cred_form_validate', 'require_unique_doc_num_validation', 10, 2 );
function require_unique_doc_num_validation( $data, $form_data ) {
  $forms = array( 63, 456 );     // a comma-separated list of form IDs you want to validate
  $post_type_slug = 'document-master-list';       // your document cpt slug
  $field_slug = 'document-number';    // the field slug of the unique number from wp-admin
  $error_message = 'Unique document number is required'; // the error message you want to display
    
  // you should not edit anything below this line
   list($fields,$errors)=$data;
  if ( in_array( $form_data['id'], $forms ) ) {
     
    if ( !isset($fields['wpcf-' . $field_slug]['value'])) {
      $errors[$field_slug] = $error_message;
    } else {
      $doc_args = array(
        'post_type' => $post_type_slug,
        'numberposts' => -1,
        'meta_query' => array( 
          array(
            'key' => 'wpcf-' . $field_slug,
            'value' => $fields['wpcf-' . $field_slug]['value']
          ) 
        ),
      );
      $matching_docs = get_posts( $doc_args );
    if ( count($matching_docs) > 0 ) {
        $errors[$field_slug] = $error_message;
      }
    }
  }
  $data =array($fields,$errors);
  return $data;
}

Relevant Documentation:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate
https://developer.wordpress.org/reference/functions/get_posts/

This support ticket is created hace 6 años, 1 mes. 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
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

Este tema contiene 9 respuestas, tiene 2 mensajes.

Última actualización por AndreG3332 hace 6 años.

Asistido por: Christian Cox.

Autor
Mensajes
#1152421

i have a Cpt call document master list. One of the fields is document number. I need to have this field be unique as it will be the main identifier of the list of documents. I am using the post forms and I have searched for this but the information on hand just confuses me big time. Not proficient in PHP, but can manipulate php if I understand the construct. There will be a few fields where I will need to do this, so if somebody could guide me through one sample I can then manipulate it for future fields also.

#1152753

Here's an example of using cred_form_validate to be sure no other posts have the same unique numeric value. Add this code to your child theme's functions.php file, or create a new snippet in Toolset > Settings > Custom Code:

add_filter( 'cred_form_validate', 'require_unique_doc_num_validation', 10, 2 );
function require_unique_doc_num_validation( $data, $form_data ) {
  $forms = array( 123, 456 );     // a comma-separated list of form IDs you want to validate
  $post_type_slug = 'book';       // your document cpt slug
  $field_slug = 'book-number';    // the field slug of the unique number from wp-admin
  $error_message = 'Unique document number is required'; // the error message you want to display

  // you should not edit anything below this line

  if ( in_array( $form_data['id'], $forms ) ) {
    list($fields,$errors)=$data;
    if ( !isset($fields['wpcf-' . $field_slug]['value'])) {
      $errors[$field_slug] = $error_message;
    } else {
      $doc_args = array(
        'post_type' => $post_type_slug,
        'numberposts' => -1,
        'meta_query' => array(
          'key' => 'wpcf-' . $field_slug,
          'value' => $fields['wpcf-' . $field_slug]['value'],
          'compare' => '=',
          'type' => 'numeric'
        ),
      );
      $matching_docs = get_posts( $doc_args );
      if ( count($matching_docs) > 0 ) {
        $errors[$field_slug] = $error_message;
      }
    }
  }
  $data =array($fields,$errors);
  return $data;
}

Change 123, 456 to be a comma-separated list of numeric Form IDs where you want to apply this validation. Usually this is one Form for creating the posts and another for editing the posts, but you may have only one, or more than two. Change book to match the slug of your document custom post type. Change book-number to match the slug of the custom field that contains the unique number. Let me know if you have questions about this.

#1154601

Hi Christiaan,

Thx for your code above. I tried it but right now it is not allowing for any new numbers to be added, it gives with every new entry number the unique error.

Here is the code as I have it at the moment.

add_filter( 'cred_form_validate', 'require_unique_doc_num_validation', 10, 2 );
function require_unique_doc_num_validation( $data, $form_data ) {
  $forms = array( 63, 456 );     // a comma-separated list of form IDs you want to validate
  $post_type_slug = 'document-master-list';       // your document cpt slug
  $field_slug = 'document-number';    // the field slug of the unique number from wp-admin
  $error_message = 'Unique document number is required'; // the error message you want to display
 
  // you should not edit anything below this line
 
  if ( in_array( $form_data['id'], $forms ) ) {
    list($fields,$errors)=$data;
    if ( !isset($fields['wpcf-document-number' . $field_slug]['value'])) {
      $errors[$field_slug] = $error_message;
    } else {
      $doc_args = array(
        'post_type' => $post_type_slug,
        'numberposts' => -1,
        'meta_query' => array(
          'key' => 'wpcf-document-number' . $field_slug,
          'value' => $fields['wpcf-document-number' . $field_slug]['value'],
          'compare' => '=',
          'type' => 'numeric'
        ),
      );
      $matching_docs = get_posts( $doc_args );
      if ( count($matching_docs) > 0 ) {
        $errors[$field_slug] = $error_message;
      }
    }
  }
  $data =array($fields,$errors);
  return $data;
}

My number format will generally be "own-001" as document number if that will have any impact.

#1154818

Sorry, I was under the impression the number would be...well, just a number. The "own-001" format does contain a number but is actually a string because it has some non-numeric characters. So you'll have to remove type="numeric" from the meta_query code and update the field slugs. Try this instead:

add_filter( 'cred_form_validate', 'require_unique_doc_num_validation', 10, 2 );
function require_unique_doc_num_validation( $data, $form_data ) {
  $forms = array( 63, 456 );     // a comma-separated list of form IDs you want to validate
  $post_type_slug = 'document-master-list';       // your document cpt slug
  $field_slug = 'document-number';    // the field slug of the unique number from wp-admin
  $error_message = 'Unique document number is required'; // the error message you want to display
  
  // you should not edit anything below this line
  
  if ( in_array( $form_data['id'], $forms ) ) {
    list($fields,$errors)=$data;
    if ( !isset($fields['wpcf-' . $field_slug]['value'])) {
      $errors[$field_slug] = $error_message;
    } else {
      $doc_args = array(
        'post_type' => $post_type_slug,
        'numberposts' => -1,
        'meta_query' => array(
          'key' => 'wpcf-' . $field_slug,
          'value' => $fields['wpcf-' . $field_slug]['value'],
          'compare' => '='
        ),
      );
      $matching_docs = get_posts( $doc_args );
      if ( count($matching_docs) > 0 ) {
        $errors[$field_slug] = $error_message;
      }
    }
  }
  $data =array($fields,$errors);
  return $data;
}

If this doesn't solve the problem, I'll need to take a closer look.

#1155237

Hi Christian, Thx for your reply. I have done as you suggested but I am still not able to add any new documents when that code is active.

Here is the code that I tried to use

add_filter( 'cred_form_validate', 'require_unique_doc_num_validation', 10, 2 );
function require_unique_doc_num_validation( $data, $form_data ) {
  $forms = array( 63, 456 );     // a comma-separated list of form IDs you want to validate
  $post_type_slug = 'document-master-list';       // your document cpt slug
  $field_slug = 'document-number';    // the field slug of the unique number from wp-admin
  $error_message = 'Unique document number is required'; // the error message you want to display
   
  // you should not edit anything below this line
   
  if ( in_array( $form_data['id'], $forms ) ) {
    list($fields,$errors)=$data;
    if ( !isset($fields['wpcf-document-number' . $field_slug]['value'])) {
      $errors[$field_slug] = $error_message;
    } else {
      $doc_args = array(
        'post_type' => $post_type_slug,
        'numberposts' => -1,
        'meta_query' => array(
          'key' => 'wpcf-document-number' . $field_slug,
          'value' => $fields['wpcf-document-number' . $field_slug]['value'],
          'compare' => '='
        ),
      );
      $matching_docs = get_posts( $doc_args );
      if ( count($matching_docs) > 0 ) {
        $errors[$field_slug] = $error_message;
      }
    }
  }
  $data =array($fields,$errors);
  return $data;
}

#1155580

You shouldn't have "wpcf-document-number" anywhere in your code. Please copy and paste the entire code I provided in my last comment, without any modifications.

#1156005

I did copy and paste your code without any changes and I am still getting the same error.

You can test it here:
Add any random alphanumeric code as a document nr
enlace oculto

#1157194

Permission denied error for me. Can you provide login credentials?

#1157337

Okay I think I have updated the code with this correct syntax:

add_filter( 'cred_form_validate', 'require_unique_doc_num_validation', 10, 2 );
function require_unique_doc_num_validation( $data, $form_data ) {
  $forms = array( 63, 456 );     // a comma-separated list of form IDs you want to validate
  $post_type_slug = 'document-master-list';       // your document cpt slug
  $field_slug = 'document-number';    // the field slug of the unique number from wp-admin
  $error_message = 'Unique document number is required'; // the error message you want to display
   
  // you should not edit anything below this line
   list($fields,$errors)=$data;
  if ( in_array( $form_data['id'], $forms ) ) {
    
    if ( !isset($fields['wpcf-' . $field_slug]['value'])) {
      $errors[$field_slug] = $error_message;
    } else {
      $doc_args = array(
        'post_type' => $post_type_slug,
        'numberposts' => -1,
        'meta_query' => array( 
		  array(
            'key' => 'wpcf-' . $field_slug,
            'value' => $fields['wpcf-' . $field_slug]['value']
          ) 
		),
      );
      $matching_docs = get_posts( $doc_args );
	if ( count($matching_docs) > 0 ) {
        $errors[$field_slug] = $error_message;
      }
    }
  }
  $data =array($fields,$errors);
  return $data;
}

Please test it out now and let me know if the problem is not resolved.

#1157595

My issue is resolved now. Thank you!