We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Selected Item by Routing Params with Paging/Sorting/Filtering

Hi,


I want to select a grid row in my functional component by a route param (primary key) with enabled paging, sorting and filtering.

How can I select a specific row on the page the item is located in general?

And how can I handle the set filter and sort settings that maybe have an effect on the item location in the array?


Thx much and greetings,
Bernd


19 Replies

PS Pavithra Subramaniyam Syncfusion Team March 23, 2023 06:30 AM UTC

Hi Bernd Parchmann,


Thanks for contacting Syncfusion support.


From your query, we understood that you want to select the Grid row and set the initial filter and sorting. If yes, you can achieve your requirement by using the “selectRow”, filterSettings, and “sortSettings” properties. Please refer to the below code example and documentation link for more information.


For selecting a row using Primary key

var index = grid.getRowIndexByPrimaryKey(10248); // 10248 is primary key

grid.selectRow(index);

 


https://ej2.syncfusion.com/react/documentation/api/grid/#selectrow


For setting filter

function App() {

  const filterOptions = {

    columns: [

      {

        field: 'ShipCity', matchCase: false,

        operator: 'startswith', predicate: 'and', value: 'reims'

      }

    ]

  };

  return <GridComponent dataSource={data} allowFiltering={true} filterSettings={filterOptions} height={273}>

    .   .  .

    <Inject services={[Filter]} />

  </GridComponent>;

}

 


https://ej2.syncfusion.com/react/documentation/grid/filtering/filtering#initial-filter



For setting sort

function App() {

  const sortingOptions = {

    columns: [{ field: 'EmployeeID', direction: 'Ascending' }]

  };

  return <GridComponent dataSource={data} allowSorting={true} sortSettings={sortingOptions} height={270}>

    .   .   .

    <Inject services={[Sort]} />

  </GridComponent>;

}

 


https://ej2.syncfusion.com/react/documentation/grid/sorting#initial-sort


If this doesn’t meet your requirement, please share the full Grid code example/runnable sample and a video of your requirement which will be helpful for providing a better solution as early as possible.


Regards,

Pavithra S



BP Bernd Parchmann March 23, 2023 06:38 AM UTC

Hi,

I know how to set initial filter and sort options. Thats not the problem.

The requirement is to set an "initial selected row/index" by id (id: string from route param) AND paging is active.

The problem: If the item is located on another page like the first, the index of the item is not found (-1).

Another problem is to calculate the page of the item (can be done with the page settings), but if sorting and filter are active, the order and amount isn't the same as the datasource array I get from my "data repository" (async http request).

How and with which data can I calculate the page, index and where I can set this setting (databound? useEffect?, ...)



PS Pavithra Subramaniyam Syncfusion Team March 24, 2023 02:53 PM UTC

Hi Bernd Parchmann,


From your query, we understood that you want to select a row based on the primary key which may be not on the current page. In the Grid component, we can select a row that is rendered in the DOM only. In paging, we render only the current page rows. So, you can dynamically select the page inside the “dataBound” event which will be triggered for every data action like paging, sorting, filtering, etc. So inside this event handler, we can search for the key in the current page records and if it presents, we can select the row by using the “selectRow” method. Please refer to the below code example, API, and sample link for more information.


 

const id = 10262;

 

const dataBound = () => {

  var index = -1;

  gridInstance.currentViewData.filter((e, i) => {

    if (e.OrderID == id) {

      index = i;

      return true;

    }

  });

  if (index != -1) {

    gridInstance.selectRow(index);

  }

};

 


API        : https://ej2.syncfusion.com/react/documentation/api/grid/#databound
   https://ej2.syncfusion.com/react/documentation/api/grid/#selectrow


Sample : https://stackblitz.com/edit/react-gehxth?file=index.js


Please get back to us if you need further assistance on this.


Regards,

Pavithra S





BP Bernd Parchmann March 27, 2023 08:53 AM UTC

sry,

I still don't know how to get the page where the item is located if some filters are active and/or the datasource is sorted... I need a sorted and filtered list to calculate the page.



PS Pavithra Subramaniyam Syncfusion Team March 31, 2023 11:42 AM UTC

Hi Bernd,


In the above solution, we don’t calculate the page initially. We check whether the id is present on the current page while doing the pagination and select the row dynamically. For example, if the id is present on the 4th page, then we can’t select the row on the 4th page at the initial rendering. So, while we navigate to each page, we check whether the id is present, reaching the 4th page turns the condition true, and based on that we select the row.


If the above doesn’t meet your requirement and you want to calculate the page number initially, please share the type of Grid data binding (local or remote, if remote data binding share the adaptor type) which will be easier to provide a better solution as early as possible.


Regards,

Pavithra S



BP Bernd Parchmann March 31, 2023 12:06 PM UTC

Hi Pavithra,

as the project has possibly changing datasets with huge amount (> 20k items), we need a generic way to locate the page of the item is located with possibly changing sortings and filters!


Currently I got all the items by a http request (json data) but I am open to use an adaptor. Requirement for the apaptor is the possibility in using our own created rest api which is using http requests (in Blazor I have already done this with an custom adaptor but wasn't able to reproduce the same in react).



PS Pavithra Subramaniyam Syncfusion Team April 6, 2023 09:29 AM UTC

Bernd,


In EJ2 Grid, there is no support for navigating to the page based on the key value. However, you can achieve your requirement by using the below workaround in which we have calculated the page number inside the dataBound event at the initial rendering, move to that page by using the “goToPage” method, and select that row using the “selectRow” method. Please refer to the below code example for more information.


const id = 10268;

var page = 1;

var isPagination = true;

var rowIndex = -1;

const dataBound = () => {

  if (isPagination) {

    isPagination = false;

    let query = grid.renderModule.data.generateQuery(); // get grid corresponding query

    for (var i = 0; i < query.queries.length; i++) {

      if (query.queries[i].fn == 'onPage') {

        query.queries.splice(i, 1); // remove page query to get all records

        break;

      }

    }

    new DataManager({ json: window.orderDatas })

      .executeQuery(query)

      .then((e) => {

        var index = -1;

        e;

        for (var i = 0; i < e.result.length; i++) {

          index = i;

          if (e.result[i].OrderID == id) break;

        }

        page = Math.floor(index / grid.pageSettings.pageSize) + 1;

        rowIndex = index % grid.pageSettings.pageSize;

        grid.goToPage(page);

      });

  }

  if (rowIndex > -1) {

    grid.selectRow(rowIndex);

    rowIndex = -1;

  }

}

 


Regards,

Pavithra S



BP Bernd Parchmann April 6, 2023 12:12 PM UTC

Unfortunately it isn't working. Maybe because grouping is enabled, too?


I opened the component without changing sorting or filtering and took an ID of an item from the second page and used it for the id property to select on load (your example). But the result of the calculated page if I tried again is 11, not 2...



PS Pavithra Subramaniyam Syncfusion Team April 11, 2023 11:41 AM UTC

Hi Bernd Parchmann,


Query#1: Unfortunately it isn't working. Maybe because grouping is enabled, too?


In our EJ2 Grid, there is no support for navigating Grid page based on the id value. So, the proposed solution is only a workaround for filtering and sorting features. Since the result of the grouped query will provide a nested data structure, the provided solution will not work for Grouped Grid. So it is not feasible to find page with Grouped Grid.

                          

Query#2: I opened the component without changing sorting or filtering and took an ID of an item from the second page and used it for the id property to select on load (your example). But the result of the calculated page if I tried again is 11, not 2...


To validate the issue could you please share an issue reproducible sample which will be helpful for us to provide a better solution as early as possible.


Regards,                                                                                                                                                                            

Pavithra S



BP Bernd Parchmann April 12, 2023 06:46 AM UTC

As Query#1 is not possible (find page if grouping is enabled) a review for Query#2 is useless...


In the Blazor API it was possible to achive this using a custom adaptor. Is there no similar solution in the React API?


Generally I guess this is a common usecase to find the page-index in the datasource doesn't matter if sorting, filtering, paging and/or grouping is enabled or not! At least I would expect a property like "currentDataSource" which is containing all the items of the datasource with the current filter, sortings and grouped to be able to calculate every index you want



PS Pavithra Subramaniyam Syncfusion Team April 13, 2023 12:41 PM UTC

Bernd,


Could you please share the Blazor solution for reference which will be helpful for us to validate the feasibility and provide a better solution as early as possible.



BP Bernd Parchmann April 17, 2023 04:16 PM UTC

Hi,


the Blazor solution is using the Syncfusion.Blazor.Data DataOperations class.

This is the example to filter:

      internal IQueryable<T> Filter<T>(IQueryable<T> loHis)
      {
         if (dataManagerRequest != null && dataManagerRequest.Where != null && dataManagerRequest.Where.Any())
         {
            loHis = DataOperations.PerformFiltering(loHis, dataManagerRequest.Where, dataManagerRequest.Where[0].Condition);
         }

         return loHis;
      }


The implementation for paging (.PerformSkip() .PerformTake()), search (.PerformSearching()) and sorting (PerformSorting()) are working similar in the controller.

Just the grouping is working a different on the client with the datasource I got from the request. This is the implemenation for grouping:

 public DataResult GroupData(DataManagerRequest dm, DataResult<TValue> dr)
      {
         if (dm.Group != null)
         {
            System.Collections.IEnumerable result = dr.Result;
            foreach (var group in dm.Group)
            {
               result = DataUtil.Group<TValue>(result, group, dm.Aggregates, 0, dm.GroupByFormatter);
            }
            return new DataResult() { Count = dr.Count, Result = result };
         }

         return new DataResult() { Count = dr.Count, Result = dr.Result };
      }



For React are Adaptors available, too. But till now I did not find a solution similar to the my Blazor solution...


Generally, is my usecase so special? With many datasets I guess paging is essential! And if I want to select an item I need to find the page the item is located WITH the current settings (sorting, filtering, grouping)!?

Without I cannot implement hyperlinks (with information in the route like ID) to another component to select an item by an identifier because I am not able to find the page!



PS Pavithra Subramaniyam Syncfusion Team April 20, 2023 11:14 AM UTC

Bernd,


In our EJ2 Grid, the grouped result will be in a complex structure. So, finding the key index with the grouped Grid will be complex and will have limitations with the data manager result. So, we can achieve your requirement by navigating through the page at initial rendering and checking whether the key is present on that page. If the key is available, we can stop the navigation and select that row. Or we continue to navigate the page. Could you please confirm whether this scenario is okay for your requirement? Based on your confirmation we will provide the sample with the above-mentioned scenario.



BP Bernd Parchmann April 21, 2023 05:25 AM UTC

Of course - if the performance is good - why not! I have >20k datasets that are initialy grouped by one property and sorted by two properties...



PS Pavithra Subramaniyam Syncfusion Team April 25, 2023 05:23 AM UTC

Bernd,


We have modified the sample to handle the grid grouping and navigate to the page where the id is present and select that row. Please refer to the below code example and the sample link for more information.


const dataBound = () => {

  if (isPagination) {

    isPagination = false;

    let query = gridInstance.renderModule.data.generateQuery(true); // get grid corresponding query

 

    new DataManager(gridInstance.dataSource)

      .executeQuery(query)

      .then((e) => {

        var index = -1;

        var rec =

          gridInstance.groupSettings.columns.length > 0

            ? e.result.records

            : e.result;

        for (var i = 0; i < rec.length; i++) {

          if (rec[i].OrderID == id) {

            index = i;

            break;

          }

        }

        page = Math.floor(index / gridInstance.pageSettings.pageSize) + 1;

 

        rowIndex = index % gridInstance.pageSettings.pageSize;

        gridInstance.goToPage(page);

        if (page == 1) {

          gridInstance.selectRow(rowIndex);

        }

      });

  }

  if (rowIndex > -1) {

    gridInstance.selectRow(rowIndex);

    rowIndex = -1;

  }

};

 


https://stackblitz.com/edit/react-zgjzmg?file=index.js


If you are facing any issues, please share an issue reproducible sample or try to reproduce the issue in the above sample which will be helpful for us to provide a better solution as early as possible.


Regards,

Pavithra S



BP Bernd Parchmann April 26, 2023 11:56 AM UTC

Thx for your example! As it seems it is working fine in my project (tested with TreeGrid)!


Could this be implemented as a default feature in your API?



PS Pavithra Subramaniyam Syncfusion Team May 5, 2023 11:29 AM UTC

Hi Bernd Parchmann,


Could you please confirm whether you want this feature in EJ2 TreeGrid or Grid component?


Regards,

Pavithra S



BP Bernd Parchmann replied to Pavithra Subramaniyam May 5, 2023 01:06 PM UTC

Hi,

YES, this should be a default feature for TreeGrid AND Grid!

And yes, too - I need this in TreeGrid and Grid!

Thx



PS Pavithra Subramaniyam Syncfusion Team May 8, 2023 04:30 PM UTC

Hi Bernd,


In EJ2 Grid, we will render only the current page records only. For remote data binding, we will fetch only the current page data from the server. So, routing to the page based on the key need to check on the entire dataset which is not supported in our default current architecture. So, we suggest using the already provided solution in your sample to achieve your requirement.


Loader.
Live Chat Icon For mobile
Up arrow icon