Skip to content

Instantly share code, notes, and snippets.

@remcotolsma
Last active March 31, 2022 07:54
Show Gist options
  • Save remcotolsma/7801923 to your computer and use it in GitHub Desktop.
Save remcotolsma/7801923 to your computer and use it in GitHub Desktop.
Gravity Forms check on unique email and categoryf field.
<?php
/**
* Hooks into the "gform_validation" filter to test whether or not a new lead is a duplicate of another lead
* based upon their fields.
*
* @param mixed $validation_result
*
* @return mixed $validation_result
*/
function pronamic_gf_unique_email_and_category( $validation_result ) {
global $wpdb;
$form_id = 2;
$email_field_id = 2;
$category_field_id = 4;
$email = filter_input( INPUT_POST, 'input_' . $email_field_id , FILTER_SANITIZE_STRING );
$category = filter_input( INPUT_POST, 'input_' . $category_field_id, FILTER_SANITIZE_STRING );
if ( ! $email || ! $category ) {
$validation_result;
}
// This query counts the number of matching values between existing leads and the lead that is being submitted.
$number_leads = $wpdb->get_var( $wpdb->prepare( "
SELECT
COUNT( lead.id )
FROM
{$wpdb->prefix}rg_lead AS lead
LEFT JOIN
{$wpdb->prefix}rg_lead_detail AS detail_email
ON lead.id = detail_email.lead_id AND detail_email.field_number = %d
LEFT JOIN
{$wpdb->prefix}rg_lead_detail AS detail_category
ON lead.id = detail_category.lead_id AND detail_category.field_number = %d
WHERE
lead.form_id = %d
AND
detail_email.value = %s
AND
detail_category.value = %s
;",
$email_field_id,
$category_field_id,
$form_id,
$email,
$category
) );
if ( $number_leads > 0 ) {
$validation_result['is_valid'] = false;
foreach ( $validation_result['form']['fields'] as $field_key => $field ) {
if ( $field['id'] === $email_field_id ) {
$field['failed_validation'] = true;
$field['validation_message'] = __( 'Met dit e-mailadres is al gestemd in deze categorie.', 'twentythirteen' );
$validation_result['form']['fields'][ $field_key ] = $field;
}
}
}
return $validation_result;
}
add_filter( 'gform_validation_2', 'pronamic_gf_unique_email_and_category' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment