I wanted to share with you a small piece of code that allows displaying or hiding columns responsively. I’m new to Anvil, and I find so many resources here on this forum, it’s great!
My goal was to hide certain columns (containing rather long texts) in a datagrid in responsive mode when the screen width is too small. And to restore them if the screen becomes larger or if the user flips their smartphone horizontally. For that, I relied on the documentation: link to the documentation.
However, when re-displaying columns, the restored columns ended up on the right side of the table. So it was necessary to save their position in order to restore the column to its initial state.
This works for me. I hope I hadn’t reinvented the wheel and that it might help.
Example of code inside a form. Just need to pass the names of the columns:
# assuming that datagrid "self.candidates_grid" have several column with 'Description' and 'Notes'
self.candidates_grid_responsive = ColumnsToShowHide_in_datagrid(self.candidates_grid)
# if on mobile
self.candidates_grid_responsive.hide_columns('Description', 'Notes')
# il on larger screens
self.candidates_grid_responsive.show_columns('Description', 'Notes')
Here is the class:
class ColumnsToShowHide_in_datagrid:
def __init__(self, datagrid):
self.datagrid = datagrid
self.hidden_columns = []
def hide_columns(self, *column_names):
columns_to_hide = []
for column_name in column_names:
column_to_hide = next((column for column in self.datagrid.columns if column['title'] == column_name), None)
if column_to_hide:
column_index = self.datagrid.columns.index(column_to_hide)
columns_to_hide.append((column_to_hide, column_index))
else:
print(f"[ColumnsToShowHide_in_datagrid.hide] Column '{column_name}' not found.")
for column, index in columns_to_hide:
self.hidden_columns.append((column, index))
self.datagrid.columns.remove(column)
self.datagrid.columns = self.datagrid.columns
def show_columns(self, *column_names):
columns_to_show = []
for column_name in column_names:
for column, index in self.hidden_columns:
if column['title'] == column_name:
columns_to_show.append((column, index))
break
else:
print(f"[ColumnsToShowHide_in_datagrid.show] Column '{column_name}' not found in hidden columns.")
for column, index in columns_to_show:
self.hidden_columns.remove((column, index))
self.datagrid.columns.insert(index, column)
self.datagrid.columns = self.datagrid.columns