[M3] Sort Datagrid (new material design theme)

Hi,

Would someone please advice me how to make a Datagrid sortable by clicking on a column in the Datagrid header?

Drag and dropping a Datagrid on to the form and then trying to drag and drop eg a Link to one of the header columns does not seem to work.

Also adding the Datagrid header and a repeating panel seperatly on to a form does not work either :confused:

Am i missing anything?

What I usually do is this:

  1. Add the DataGrid;
  2. Add a DataGridRow as the first row of the DataGrid;
  3. Set “auto_header” to False in the DataGrid;
  4. Add links to each column of the DataGridRow that will act as the new header;
  5. To each link click event, add logic to sort the items of the RepeatingPanel inside the DataGrid and reset the items properties to the sorted list.

This usually works for me.

This is how it looks in the editor:

The structure (Grid in red, header in green)
image

This is running:

The click event (is generic)

def header_sort_link_click(self, **event_args):
        """This method is called when the link in the header is clicked"""
        sender = event_args['sender'] # Gets wich header was clicked
        # .... add logic to get which key to sort based on the sender
        event_args['sender'].icon = 'fa:arrow-down-short-wide' if not rev else 'fa:arrow-down-wide-short' # Shows an icon for sorting asc or desc
        items = sorted(self.repeating_panel.items, key= lambda f: f[key], reverse=rev)
        self.repeating_panel.items = items

Hope it helps.

3 Likes

Thank you very much!! I will definitely try that :slight_smile:

1 Like

The DataGridJson custom component uses @gabriel.duro.s’s trick and automatically adds the header row with clickable column headers, takes care of the click event management and ordering, and a adds a little icon that shows which column is the table ordered by.

If you are trying to show something very simple, this could do the job.

Pros: it’s all automatic, you don’t even need to create template rows.
Cons: it’s all automatic, you can’t even create template rows.

3 Likes

I’ve been forever thinking of doing something like this, but always let go. When “custom components as containers” and thee live updates in the editor were announced I thought of going back to this idea again to create a CustomDataGrid, but other stuff always get in the way.

The idea of the DataGridJson custom component was to avoid the proliferation of templates and the spreading of code across multiple forms.

With a DataGridJson all the event handlers are in one place, the main form, and there are no templates. If all you need is showing texts and links, it does the job very well.

Now that custom component management has improved, it may be time to create a DataGridWithSortableHeaders… :slight_smile:

2 Likes

I just tried it, and it worked like a charm!! Thank you very much :slight_smile:

1 Like