A GravityView customer had a form on his site containing a Multiselect field of all the US states. The problem was that their search results for the state “Kansas” were also matching the state “Arkansas“. This wasn’t good. If the field were an Address field, it would have been easy, but the field was a Multiselect. So why was this a problem? Gravity Forms Search API allows you to define a search “operator” for search fields. A few search operators include:
contains
– The default operator: does the field value contain any of the search valueis
– The search exactly matches the valuein
– Is the search value one of an array of itemsnot in
– Exclude the value from search results
Gravity Forms restricts List and Multiselect fields to the contains
operator
Multiselect fields store their data in a different way than most fields: they convert the choices into a single text string (formatted as JSON), so multiple values would be stored like this: ["Colorado","Arkansas","Texas"]
List fields with columns also store their data this way. List fields without columns “serialize” the data, which stores the values in a different, but similar, format: a:3:{i:0;s:8:"Colorado";i:1;s:8:"Arkansas";i:2;s:5:"Texas";}
Gravity Forms doesn’t allow using the “in” or “not in” search operators for these two field types. This has made exact-match searches impossible, but I realized: we just need to add quotes to either side of the search, and contains
will work!. I added the code below to our customer’s site, and voilá: searches now distinguish Arkansas from Kansas.
For developers working with GravityView
The plugin file must be modified before adding it to your site! You need to define your own form ID and form field IDs. Download the mini-plugin for GravityView – Define the form & field IDs that should be exact-matched, and the plugin will add quotes around the fields you want to exact-match.
For developers working with Gravity Forms API
If you’re working with Gravity Forms API directly using the GFAPI::get_entries()
method, you’ll need to change your search criteria array to add the quotes: Before:
$search_criteria['field_filters'][] = array(
'key' => '1',
'operator' => 'contains',
'value' => 'Kansas'
);
After:
$search_criteria['field_filters'][] = array(
'key' => '1',
'operator' => 'contains',
'value' => '"Kansas"'
);
I hope this helps!