Sortable option for reference fields

35 Views Asked by At

I've been developing a project in which users can order food. I've done a table in which I display the users' data, and also, a column showing the count of orders that that user has acomplished.

I've used the ReferenceManyCount component which is exactly the component I need to develop this feature, because, it shows the number of orders, and also, can be used as a link, that redirects to the order's resource with all the filters set, which is great. The problem relies in that that column can't be sorted, and that's critical. If the database grows huge, it should be able to sort by order count, and that can't be done yet.

I've tried using sortable prop, but that ain't work.

Any idea on how to solve this?

Thanks in advance.

<ReferenceManyCount
sortable={true}
label="Orders"
reference="Orders"
target="userid"
link
...

In the documentation states that also accepts the common field props. Therefore, sortable is a correct prop to use. But that prop is not doing anything.

1

There are 1 best solutions below

1
slax57 On

Inside a <List>, when you choose to sort by a field, e.g. <TextField source="name" />, React Admin will use the source prop of the field to build the sort parameter passed to the dataProvider.

For instance, it will call:

dataProvider.getList("products", {
    pagination: { page: 1, perPage: 10 },
    sort: { field: 'name', order: 'ASC' }, // because source is 'name'
    filter: {},
});

It's important to understand that React Admin does not perform the sorting of the data -- your database does.

So your API needs to understand the sort parameter ({ field: 'name', order: 'ASC' }) and translate that into a database query parameter.

Now, if you need to order by a count, it's not as straightforward as sorting by a field, because the data needs to be computed before sorting. Again, this needs to be done by the database.

Depending on your dataProvider, you may be able to call getList with something like the following to sort on the count:

dataProvider.getList("products", {
    pagination: { page: 1, perPage: 10 },
    sort: { field: 'orders_count', order: 'ASC' }, // 'orders_count' depends on the dataProvider in use
    filter: {},
});

If that is the case, all you need to do then is change your field to:

<ReferenceManyCount
  sortBy="orders_count"
  label="Orders"
  reference="Orders"
  target="userid"
  link
/>

But again, you need to make sure your dataProvider supports it, and check its documentation to know what to use in the sortBy prop.

Hope this helps.