I have 4 fields in a table
ID | Name | EAN | HAN
These are properties in one of my entity So, How do I configure entity with searchFilter so that When I search a string it should check for it in all 4 columns and return the matched results.
For example :- if I search "car" it will match in name property and return but when I type id say "219" it will match in id property and return me accordingly.
I want to achieve this using api-platform only and my project is in symfony.
So, search should look in all 4 fields and then return result.
You can archieve this with a custom filter that combines those criteria with OR. I made one for chapter 6 Sorting and Custom Filter of my tutorial. I include its code below.
You can configure which properties it searches in the ApiFilter tag. In your case that would be:
A query string like:
will search all properties specified case insensitive LIKE %car% (You do need to url-encode the parameter value if you create the query string programatically)
You can also configure the parameter name in the ApiFilter tag. For example:
will allow a query string like:
I had to decide how this filter would combine with other filters. For compatibility with the existing filters i used AND. So if you for example also add a standard DateFilter to the same Entity class you will be able to search for some words in the specified fields AND after a specified date but not OR after a specified date. For example:
It splits the search string into words and searches each of the properties for each word, so
will search in all specified properties both .. LIKE %car% OR .. LIKE %219%
Yes, it does assume that all properties are of type string, or that your database supports LIKE for other property types (MySQL does, Postgres does not, so if ID is an int, this will not work with Postgres). The filter does sort by relevance (that's why it's called SimpleSearchFilter).
Of course you can change the code at will, adding different handling for properties with other data types will not be too hard if you know how to use the metadata from Doctrine.
Here is the code (for apip 3.0):
Due to the constructor argument "searchParameterName" the service needs configuration in api/config/services.yaml