Tuesday, October 23, 2012

web2py grid with export dropdown

I just want to share the code that Paolo Caruccio created to show the export dropdown for grid instead of links. It looks very clean and this should be the default for grid layout!

web2py forum link
https://groups.google.com/forum/?fromgroups=#!topic/web2py/HsFWsQmGONM

To test, create new app and add/edit as follows.

Model

db.define_table('Category',
    Field('Code', 'integer'),
    Field('Name'),
    format='%(Name)s')

Controller

def index():
    query = db.Category.id >0
    grid = SQLFORM.grid(query,csv=True,paginate=10)
    return dict(grid=grid)

View


{{extend 'layout.html'}}
{{
if not request.args:

 w2p_grid_tbl = grid.element('table')
 if w2p_grid_tbl:
 original_export_menu = grid.element('div.w2p_export_menu')
 export_menu_links = original_export_menu.elements('a')
 export_menu_items = []
 for link in export_menu_links:
 item = LI(link)
 export_menu_items.append(item)
 pass
 new_export_menu = DIV(
                      A( T('Exports'),
                         SPAN(_class='caret'),
                         _href='#',
                         _class='btn dropdown-toggle',
                         **{'_data-toggle':"dropdown"}
                        ),
                      UL(*export_menu_items,
                         _class='dropdown-menu'
                        ),
                    _class='w2p_export_menu btn-group'
                    )
 export_menu = grid.element('div.w2p_export_menu',replace=new_export_menu)
 pass
pass
}}
{{=grid}}


Before
After