Home › Toolset Professional Support › [Resolved] Quiero que un campo sea unico
Problem:
How to validate CRED form for duplicate postmeta or custom field value
Solution:
You can use CRED hook cred_form_validate in order to validate your form when you submit the form and check if the custom field value for field "user" is already exists or not.
You can find proposed solution, in this case, with the following reply:
=> https://toolset.com/forums/topic/quiero-que-un-campo-sea-unico/#post-740544
Relevant Documentation:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate
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 |
---|---|---|---|---|---|---|
- | 10:00 – 13:00 | 10:00 – 13:00 | 10:00 – 13:00 | 10:00 – 13:00 | 10:00 – 13:00 | - |
- | 14:00 – 18:00 | 14:00 – 18:00 | 14:00 – 18:00 | 14:00 – 18:00 | 14:00 – 18:00 | - |
Supporter timezone: Asia/Kolkata (GMT+05:30)
Tagged: Setting up custom types, Toolset Forms, Types plugin
Related documentation:
This topic contains 9 replies, has 2 voices.
Last updated by pedroS-6 6 years, 7 months ago.
Assisted by: Minesh.
Tell us what you are trying to do? Tengo un formulario que crea una custom types llamada "denuncia". Quiero que un campo de el formulario llamado "usuario"sea unico. De modo que al rellenarlo, si ya existe, salte una llamada diciendo que ese campo ya existe y tenga que utilizar otro.
Is there any documentation that you are following?
Is there a similar example that we can see?
What is the link to your site?
Hello. Thank you for contacting the Toolset support.
I checked but Spanish support is not available for now. In order to give you quick help and guidance, I will try to help you in English. Hope this is OK.
You can use CRED hook cred_form_validate in order to validate your form when you submit the form and check if the custom field value for field "user" is already exists or not.
For example:
add_filter('cred_form_validate','func_validate_birthdate',10,2); function func_validate_birthdate($error_fields, $form_data){ //field data are field values and errors list($fields,$errors)=$error_fields; if ($form_data['id']==9999){ $args = array( 'meta_query' => array( array('key' => 'wpcf-user', 'value' => $_POST['wpcf-user'] )), 'post_type' => 'denuncia', 'posts_per_page' => -1 ); $posts = get_posts($args); //check if birthday value is already on the database if (count($posts) > 0){ //set error message for my_field $errors['wpcf-user']='add your error message here'; } } return array($fields,$errors); }
Where:
- Replace 9999 with your original form ID.
- Adjust error message as per your requirement
More info:
=> https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate
I'm afraid that my English is medium, and my computer knowledge worse. That's why I use toolset.
I copy the generated generated form and where I want to make the changes to see if you can prepare it and I copy it.
This is the field that I want to be unique, no one should have the same.
<div class="form-group">
<label><h1>Usuario*</h1>
Genere un Usuario de al menos 6 dígitos. Lo podrá usar para acceder a la página privada de seguimiento de su denuncia.</label>
[cred_field field='usuario-denuncia' post='denuncia' value='' urlparam='' class='form-control' output='bootstrap']
</div>
and it would be necessary to put an alert to warn that a different user has to add.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
[credform class='cred-form cred-keep-original']
[cred_field field='form_messages' value='' class='alert alert-warning']
<div class="form-group">
<label><h1>Usuario*</h1>
Genere un Usuario de al menos 6 dígitos. Lo podrá usar para acceder a la página privada de seguimiento de su denuncia.</label>
[cred_field field='usuario-denuncia' post='denuncia' value='' urlparam='' class='form-control' output='bootstrap']
</div>
<div class="form-group">
<label><h1>Contraseña*</h1>
Genere una contraseña de al menos 6 dígitos. La podrá usar para acceder a la página privada de seguimiento de su denuncia.</label>
[cred_field field='contrasena-denuncia' post='denuncia' value='' urlparam='' class='form-control' output='bootstrap']
</div>
<div class="form-group">
<label>Nombre y apellidos*:</label>
[cred_field field='nombre-y-apellidos-denuncia' post='denuncia' value='' urlparam='' class='form-control' output='bootstrap']
</div>
<div class="form-group">
<label>Teléfono*:</label>
[cred_field field='telefono-denuncia' post='denuncia' value='' urlparam='' class='form-control' output='bootstrap']
</div>
<div class="form-group">
<label>Correo*:</label>
[cred_field field='correo-denuncia' post='denuncia' value='' urlparam='' class='form-control' output='bootstrap']
</div>
<div class="form-group">
<label>¿Cual es su relación con Pullmantur?</label>
[cred_field field='relacion-con-sociedad-denuncia' post='denuncia' value='' urlparam='' select_text='--- not set ---' class='form-control' output='bootstrap']
</div>
<div class="form-group">
<label><h1>Describa aquí su denuncia</h1>
Indicando los datos que conozca:hecho denunciado, personas involucradas y su relación con Pullmantur, momento y lugar en que ocurrieron los hechos. Indique si la situación es conocida por su superior o cualquier otro detalle que considere relevante.</label>
[cred_field field='descripcion-general-de-los-hechos-denuncia' post='denuncia' value='' urlparam='' class='form-control' output='bootstrap']
</div>
<div class="form-group">
<label><h1>Archivos adjuntos</h1>
Si dispone de un documento o archivo que asista a su informe, puede cargar los tipos de archivos más comunes:</label>
[cred_field field='archivos-adjuntos-denuncia' post='denuncia' value='' urlparam='' output='bootstrap']
</div>
<div class="form-group">
<label> Estoy de acuerdo con los Términos y Condiciones para la formulación de esta denuncia.</label>
[cred_field field='terminos-y-condiciones-denuncia' post='denuncia' value='' urlparam='' output='bootstrap']
</div>
<div class="form-group">[cred_field field='recaptcha' value='' urlparam='' class='form-control' output='bootstrap']</div>
[cred_field field='form_submit' value='Enviar' urlparam='' class='btn btn-primary btn-lg' output='bootstrap']
[/credform]
Its Ok - I understand what you need and your English is fine to me.
I've adjusted the code according to your setup.
Add following code to your current theme's functions.php file and save the file.
add_filter('cred_form_validate','func_validate_birthdate',10,2); function func_validate_birthdate($error_fields, $form_data){ //field data are field values and errors list($fields,$errors)=$error_fields; if ($form_data['id']==9999){ $args = array( 'meta_query' => array( array('key' => 'wpcf-usuario-denuncia', 'value' => $_POST['wpcf-usuario-denuncia'] )), 'post_type' => 'denuncia', 'posts_per_page' => -1 ); $posts = get_posts($args); //check if birthday value is already on the database if (count($posts) > 0){ //set error message for my_field $errors['wpcf-usuario-denuncia']='add your error message here'; } } return array($fields,$errors); }
-- You just need to replace 9999 with your CRED form ID.
-- you need to replace error message with "add your error message here" in above code.
If you are not sure how to paste above code to functions.php file - please share access details and I'm happy to help you further.
If you agree to this, please use the form fields I have enabled below to provide temporary access details (wp-admin and FTP).
I have set the next reply to private which means only you and I have access to it.
Thanks for sharing access details but unfortunately when I tried to access wp-admin - the page does not load and I see following error on page:
ERR_TOO_MANY_REDIRECTS
Could you please fix this and send me working wp-admin access details.
Also, could you please share problem URL where I can see the CRED form you added.
Also, when I try to login to FTP - I get following error message:
La conexion a este servidor ha sido bloqueada en el firewall.
Please send me working wp-admin and FTP access details so I can proceed.
I will try to do it by myself. I do not understand this fragment
add_filter('cred_form_validate','func_validate_birthdate',10,2);
function func_validate_birthdate($error_fields, $form_data){
validate_birthdate', I do not use the date of birth at any time.
I just need that
"wpcf-usuario-denuncia" to be unique, that do not introduce another equal in Denuncias type
Well - you do not have to worry about that. There is no issue on those line but still if you want to change the function name.
Use following lines for those two lines:
add_filter('cred_form_validate','func_validate_usuario_denuncia',10,2); function func_validate_usuario_denuncia($error_fields, $form_data){
Yes, thank you very much. It has been a great help
Hi, to be able to make a single credit form field, you advised me to include in fuctions.php (public_html / pullmantur / wp-content / themes / dt-the7) the following code
add_filter('cred_form_validate','func_validate_usuario_denuncia',10,2);
function func_validate_usuario_denuncia($error_fields, $form_data){
//field data are field values and errors
list($fields,$errors)=$error_fields;
if ($form_data['id']==36925){
$args = array(
'meta_query' => array(
array('key' => 'wpcf-usuario-denuncia',
'value' => $_POST['wpcf-usuario-denuncia']
)),
'post_type' => 'denuncia',
'posts_per_page' => -1
);
$posts = get_posts($args);
//check if birthday value is already on the database
if (count($posts) > 0){
//set error message for my_field
$errors['wpcf-usuario-denuncia']='Usuario ya existente, por favor utilice un nuevo usuario, gracias';
}
}
return array($fields,$errors);
}
it works, but it makes it impossible to upload files on that form. Within the same fuctions.php, I have other codes like these
<?php
/**
* Vogue theme.
*
* @since 1.0.0
*/
// File Security Check
if ( ! defined( 'ABSPATH' ) ) { exit; }
/**
* Set the content width based on the theme's design and stylesheet.
*
* @since 1.0.0
*/
if ( ! isset( $content_width ) ) {
$content_width = 1200; /* pixels */
}
/**
* Initialize theme.
*
* @since 1.0.0
*/
require( trailingslashit( get_template_directory() ) . 'inc/init.php' );
//* Excluye páginas específicas de los resultados de búsqueda en WordPress. Las estáticas y las del formulario de denuncia de las empresas
function filtro_paginas_especificas( $query ) {
if ( $query->is_search && $query->is_main_query() ) {
$query->set( 'post__not_in', array( 35563,35532,35542,35534,35536,35538,35544,35540,35939 ) );
}
}
add_filter( 'pre_get_posts', 'filtro_paginas_especificas' );
add_filter('cred_form_validate','func_validate_usuario_denuncia',10,2);
function func_validate_usuario_denuncia($error_fields, $form_data){
//field data are field values and errors
list($fields,$errors)=$error_fields;
if ($form_data['id']==36925){
$args = array(
'meta_query' => array(
array('key' => 'wpcf-usuario-denuncia',
'value' => $_POST['wpcf-usuario-denuncia']
)),
'post_type' => 'denuncia',
'posts_per_page' => -1
);
$posts = get_posts($args);
//check if birthday value is already on the database
if (count($posts) > 0){
//set error message for my_field
$errors['wpcf-usuario-denuncia']='Usuario ya existente, por favor utilice un nuevo usuario, gracias';
}
}
return array($fields,$errors);
}
It also interferes with cred, its update.
What is the problem?