Hide AG-Grid column when parameter is not in JSON

23 views Asked by At

I'm a Ruby on Rails developer who is trying to learn Stimulus JS. I've got table which is build via AG-Grid. The table is created based on the sent JSON from the controller. Below is an example of Stimulus JS controller which I'm using:

import { Controller } from 'stimulus';
import Rails from '@rails/ujs';
import * as AgGrid from 'ag-grid-community';
import {
  DEFAULT_GRID_OPTIONS,
  buildColumnDefs,
  GridDatasource,
  updateColumnPositionsInCookies,
} from 'core/utils/grid';

const columnOptions = {
  columnDefs: {
    (...) some other columns
    account_name: { cellClass: 'font-mono', cellRenderer: 'flexCellRenderer', sortable: false },
    (...) some other columns
  },
  cookiesName: 'hellgate_settlements_reports_columns_positions',
  defaultSorting: [
    (...) some other columns
    'account_name',
    (...) some other columns
  ],
};

function buildGrid(gridElement) {
  const {indexUrl, paginationPageSize, i18nJson} = gridElement.dataset
  const options = {
    ...DEFAULT_GRID_OPTIONS,
    cacheBlockSize: paginationPageSize,
    maxConcurrentDatasourceRequests: 2,
    columnDefs: buildColumnDefs(columnOptions, i18nJson),
    datasource: new GridDatasource({ indexUrl }),
    onColumnMoved(params) { updateColumnPositionsInCookies(columnOptions, params) },
  }
  return new AgGrid.Grid(gridElement, options);
}

export default class extends Controller {
  connect() {
    const gridElement = this.element.querySelector('#hellgateSettlementsGrid');

    if (gridElement) {
      this.gridObject = buildGrid(gridElement)
    }
  }

  disconnect() {
    if (this.gridObject) {
      this.gridObject.destroy();
    }
  }
}

I want to hide account_name column when account_name doesn't exists in JSON - example below:

/ json without account_name, the Account Name column should not be visible

{
  "next_page": null,
  "records": [
    {
      "items_size": "13",
      "report_id": "960ffbad-396d-43ed-94b0-34c1df28e4e5",
      "start_date": "2024-01-15 01:01:53 UTC"
    }
  ]
}

/ json with account_name, the Account Name column is present
{
  "next_page": null,
  "records": [
    {
      "account_name": "platform",
      "items_size": "13",
      "report_id": "960ffbad-396d-43ed-94b0-34c1df28e4e5",
      "start_date": "2024-01-15 01:01:53 UTC"
    }
  ]
}

Is it possible to do that?

0

There are 0 answers