Sauter la navigation

[Résolu] Not allow to create CPT if custom field already exists.

Ce fil est résolu. Voici une description du problème et la solution proposée.

Problem: I have a Form that creates new posts in a custom post type. One of the custom fields holds a telephone number. I would like to prevent the Use from creating a post if the telephone number they submit already exists in the database as a telephone number for another post.

Solution: Use the Forms API hook cred_form_validate to inspect the submitted custom field value. Create a custom post query that also queries posts by that custom field value. If any posts are found in that query, display an error message on the telephone field.

Relevant Documentation:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate

This support ticket is created Il y a 3 années et 5 mois. 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)

Auteur
Publications
#2127687

Hello!

I have a CPT "recomendado".
CPT "recomendado" has a custom field "telephone".
I have a front end form to create "recomendados".

I want to not be allowed to create a new CPT "recomendado" if there is already a CPT "recomendado" with the same field "telephone" value.

Thanks!

#2128229

Shane
Supporter

Les langues: Anglais (English )

Fuseau horaire: America/Jamaica (GMT-05:00)

Hi Jesus,

Thank you for getting in touch.

In a case like this you will need to use custom coding to achieve. What I recommend doing is using our Validation hook to check the value against the database.
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate

With the validation hook you can prevent the form from being submitted. Now to achieve this you will perhaps need to query the database for the entered value and see if any posts are returned with that meta value and then fail the form.

Here is an example below of how you can query the posts database for the meta value.
https://wordpress.stackexchange.com/questions/144078/get-posts-by-meta-value/144079

Please let me know if this was able to point you in the right direction.

Thanks,
Shane

#2129079

I have tried but I have not been able to find the solution.


add_filter('cred_form_validate','tj_validation_telefono_recomendado',10,2);
function tj_validation_telefono_recomendado ($error_fields, $form_data)
{
    //field data are field values and errors
  	// list() va asignando asignando a las variables $fields y $errors los valores almacenados en el array $errors_fields
    list($fields,$errors)=$error_fields;

    //validate if specific form
    if ($form_data['id']==377 || $form_data['id']==335) {
      
      // Cogemos el valor del campo teléfono
      $telefono = strval($fields['wpcf-telefono-recomendado']['value']);
      
      // Realizamos una consulta a la base de datos para ver si existe el teléfono.
      // Listamos todos los CPT 'recomendado' que tengan el key 'wpcf-telefono-recomendado' con value '$telefono'
      $args = array(
        'post-type' => 'recomendado',
         'meta_query' => array(
             array(
                'key' => 'wpcf-telefono-recomendado',
                'value' => $telefono,
                'compare' => 'LIKE',
             )
         )
      );
      $query = new WP_Query($args);
      
      // Si $query ha devuelto algún resultado (Si no está vacía la query es que ya existe el teléfono)
      //empty($query)
        if (!empty($query))
        {
          //set error message for my_field
          $errors['telefono-recomendado']='Ya existe un recomendado con ese teléfono en nuestra Base de datos.';
        }

    }
    //return result
    return array($fields,$errors);
}

This is not working for me. Any idea? Thanks!

#2129099

Shane
Supporter

Les langues: Anglais (English )

Fuseau horaire: America/Jamaica (GMT-05:00)

Hi Jesus,

Would you mind allowing me to have admin access to the site as well as a link to the form so that I can have a look ?

I've enabled the private field for your next response.

Thanks,
Shane

#2129623

I think I already found the solution. It's works for me. How do you see it?

add_filter('cred_form_validate','tj_validation_telefono_recomendado',10,2);
function tj_validation_telefono_recomendado ($error_fields, $form_data)
{
    //field data are field values and errors
  	// list() va asignando asignando a las variables $fields y $errors los valores almacenados en el array $errors_fields
    list($fields,$errors)=$error_fields;

    //validate if specific form
    if ($form_data['id']==335) {
      
      // Cogemos el valor del campo teléfono
      $telefono = strval($fields['wpcf-telefono-recomendado']['value']);
      
      // Vamos a coger todos los post que tengan el número de teléfono que hemos introducido. Si hay alguno lanzamos error.
      $args = array(
		'meta_key' => 'wpcf-telefono-recomendado',
		'meta_value' => $telefono,
		'post_type' => 'recomendado',
		'post_status' => 'any',
		'numberposts'      => 1, // Con coger 1 nos vale para validar que el teléfono ya existe
      );
      // get_posts nos devuelve un array asociativo con todos los posts que cumplen las condiciones
      $posts = get_posts($args);
      
      // Debug
      //error_log( 'FIELDS ----------------------');
      //error_log( print_r( $fields, true)  );
      //error_log( 'TELÉFONO DEL RECOMENDADO ----------------------');
      //error_log( print_r( $telefono, true)  );
      //error_log( 'POSTS ----------------------');
      //error_log( print_r( $posts, true)  );
      
      // Si el array de posts no está vacío el número ya existe
        if (!empty($posts))
        {
          //set error message for my_field
          $errors['telefono-recomendado']='Ya existe un recomendado con ese teléfono en nuestra Base de datos. Para más información contacta con nosotros';
        }

    }
    //return result
    return array($fields,$errors);
}
#2131931

Hi Shane is on vacation this week so I'm checking on his outstanding tickets. Looks like you have found a good solution to validate the post before submission by checking for existing custom field values. I think this will work pretty well, though telephone numbers are often entered with various formatting characters that could make validation a pain.

#2132239

My issue is resolved now. Thank you!