Hi,

As you all know, SQLFORM.grid search does not support searching for 
multiple words - it throws an error "Invalid Query"
Searching for multiple words may be a common requirement.
I looked thru various older posting on this group, but none worked for me 
AS IS (Possiblly because they were old - it worked with whatever was 
current version of web2py at the time of original post) This one came the 
closest : https://groups.google.com/forum/?fromgroups=#!topic/web2py
/9_1ECdKHKUo

Here is the version that worked for me: (web2py Version 2.3.2 (2012-12-17 
15:03:30) stable)

#Referred to the web2py implementation of search (gluon/sqlhtml.py:def 
grid())
#Modified to support multiple words
def search_query(fields, keywords):
    if isinstance(keywords, (tuple, list)):
        keywords = keywords[0]
        request.vars.keywords = keywords
    key = keywords.strip()
    if key and not '"' in key and not "'" in key:
        SEARCHABLE_TYPES = ('string', 'text', 'list:string')
        words = key.split(' ') if key else []
        filters = []
        for field in fields:
            if field.type in SEARCHABLE_TYPES:
                all_words_filters = []
                for word in words:
                    all_words_filters.append(field.contains(word))
                filters.append(reduce(lambda a, b: (a & b),all_words_filters
))
        parts = filters
    else:
        parts = None
    if parts:
        return reduce(lambda a, b: a | b, parts)
    else:
        return None

Why "&" in the first reduce ? Because if I use "|" then search results are 
too wide. e.g. if I typed "web2py is great" - then using "|" would return 
all the matches containing the word "is" even if "web2py" and "great" are 
missing. 
Off course using "&" isn't fool proof either since it will match a record 
having text "web2py is not great" as well (since all three words are 
present) 

One big change from what previous posts having been saying is that I did 
NOT override the search widget. Search widgets works well as is.
Only difference is that I assigned the above function to "searchable" 
parameter when calling the SQLFORM.grid like

grid = SQLFORM.grid(query,create=True, searchable=search_query) #Use other 
params as required

I came to realize this after I looked at web2py code (gluon/sqlhtml.py) 
where if "searchable" is callable - then it is called. I somehow used to 
think that it is a boolean (True/False)

I hope this helps someone

-Mandar

-- 

--- 
You received this message because you are subscribed to the Google Groups 
"web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to web2py+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to