Default sort datagrid

What is the best way to set a default sort on a datagrid.
On Jmix 1, il was

<column id="MY_COLUMN" sort="DESCENDING"/>

Hello,

In Jmix 2, setting a default sort order for a DataGrid is done differently compared to Jmix 1. Instead of specifying the sort order directly in the XML for a column, you should define the sort order in the JPQL query used to load the data. This approach ensures that the data is sorted as desired when it is initially loaded into the DataGrid.
Here’s how you can set a default sort order in Jmix 2:

  1. Define the Sort Order in the JPQL Query: You can specify the default sort order in the JPQL query within the data loader. For example, if you want to sort by a column named MY_COLUMN in descending order, you would write the query as follows:
<data readOnly="true">
    <collection id="myEntitiesDc" class="com.company.myapp.entity.MyEntity">
        <loader id="myEntitiesDl">
            <query>
                <![CDATA[select e from MyEntity e order by e.myColumn desc]]>
            </query>
        </loader>
    </collection>
</data>
  1. Bind the DataGrid to the Data Container: Ensure that your DataGrid is bound to the data container that uses the loader with the specified sort order.
<layout>
    <dataGrid id="myDataGrid" width="100%" dataContainer="myEntitiesDc">
        <columns>
            <column property="myColumn"/>
            <!-- other columns -->
        </columns>
    </dataGrid>
</layout>
  1. Enable Multi-Sort if Needed: If you need to allow users to sort by multiple columns, you can enable multi-sort in the DataGrid by setting the multiSort attribute to true. You can also control the behavior of multi-sorting with multiSortOnShiftClickOnly and multiSortPriority attributes.
<dataGrid id="myDataGrid" width="100%" dataContainer="myEntitiesDc" multiSort="true">
    <columns>
        <column property="myColumn"/>
        <!-- other columns -->
    </columns>
</dataGrid>
1 Like