If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!


  • 0
    wasuaje  8 years ago
    Hello there i had to make some changes: improve performance for big tables always return de id of table even if it is not selected previously add another param (string list) to accept your own list of fields to search for. Result returns None if you entered to the form the first time, so you can "capture" this case and decide even show or not the result later in your view Use it like this
    
    def search:
    frmsearch,results = dynamic_search(db[tabla],'descripcion, fecha_solicitud')
    
    if results <> None: 		
    	return dict(tabla=tabla, frmsearch=frmsearch,  lista=results)			
    else: 
    	return dict(tabla=tabla, frmsearch=frmsearch)
    
    
    The code
    
    def dynamic_search(table,strfields):
    	tbl = TABLE()
    	selected = []
    	ops = ['igual','no igual a','mayor que','menor que','comienza con','termina en','contiene']
    	#print table.fields
    	query = table.id > 0    
    	for field in table.fields:
    		if field in strfields:
    			chkval = request.vars.get('chk'+field,None)
    			txtval = request.vars.get('txt'+field,None)
    			opval = request.vars.get('op'+field,None)
    			row = TR(TD(INPUT(_type="checkbox",_name="chk"+field,value=chkval=='on')), \
    		             TD(field),TD(SELECT(ops,_name="op"+field,value=opval)), \
    		             TD(INPUT(_type="text",_name="txt"+field, _value=txtval)))
    			tbl.append(row)
    			if chkval:
    				if txtval:					
    					query &= build_query(table[field], opval,txtval)
    					selected.append(table[field]) 
    	
    	if len(selected) > 0:
    			selected.append(table.id) 
    			results = db(query).select(*selected)
    	else:
    		results = None
    	
    	form = FORM(tbl,INPUT(_type="submit"))
    	return form, results  
    
    

Commented on:

This creates a form that allows the user to dynamically search and select fields in a table

Hosting graciously provided by:
Python Anywhere