Show only other children of parent in Grid View

In my app, Customers (Parent) have Dispatches (Children). When the user is on a details page of a specific Dispatch, I want to have a grid view showing other recent (last six months) Dispatches of the parent Customer. How can I exclude the Dispatch currently being viewed from the grid view of other Dispatches for the same Customer. Ideally, this grid view would return no results and show the Empty Grid Text if the dispatch being viewed is the only one in the last six months.

Hey @Spencer1,
I assume you already know that you can add a grid that ‘displays Dispatch records connected to the same Customer connected to this page’s Dispatch’.

This little JS snippet should filter out the current page’s record ID from the nominated grid.
Replace scene_xx with the scene your grid is on, and view_xx with the grid view you want to filter:

$(document).on(`knack-scene-render.scene_xx`, async function (event, scene) {
  
  const gridViewKey = 'view_xx';
  const recordId = Knack.hash_id;
  const $view = $(`#${gridViewKey}`);
  $view.find(`tbody tr#${recordId}`).remove(); // Remove row from grid initially due to lag-time
  const filters = [
    {field: 'id', operator: 'is not', value: recordId}
  ]
  Knack.views[gridViewKey].handleChangeFilters(filters); // Apply filters on grid

});

This will filter the grid when the scene finishes rendering. The reason we don’t trigger it on a view or records render is that it will keep re-rendering perpetually.

Constraints:

  • You can’t enable ‘add filters’ to your grid of ‘related dispatches’, otherwise it removes the filtering of the same record.
  • The record may be visible for the time it takes to load the page, depending on how intense the page load is

PS: I only just discovered today you can add custom filters on the id field of a record, which is handy for this and any API calls!

2 Likes

Thank you @StephenChapman !
Could other filters be added to this code to replace the ones that have previously been added in the builder, but may no longer work?
Because I only want to return Dispatches in the last 6 months, I currently have two:
Show records that match any:
Authorization Date is during the previous 6 months
Authorization date is today or after

I recognize the filter would need to become “And” rather than “Or/Any”. I could build the date range filter into a single field in the Dispatches Table, such as True/False set by conditional rules. But I would still need to add one more criteria to the filter in your function, such as:
Last Six Months is True

@Spencer1, yes you can have filters set up in the grid view’s Source that won’t be impacted when the record ID is filtered out. Like so:

Thanks so much. Now I understand the nuance. Filters can be setup in the builder, but if a user changes filters, then it won’t filter out the record ID.

1 Like