React Grid Cell Editing

    The Ignite UI for React Cell Editing in React Grid provides a great data manipulation capability of the content of individual cells within the React Grid component and comes with powerful API for React CRUD operations. It is a fundamental feature in apps like spreadsheets, data tables, and data grids, allowing users to add, edit, or update data within specific cells. By default, the Grid in Ignite UI for React is used in cell editing. And due to the default cell editing template, there will be different editors based on the column data type Top of Form.

    Além disso, você pode definir seus próprios modelos personalizados para ações de atualização de dados e substituir o comportamento padrão para confirmar e descartar quaisquer alterações.

    React Grid Cell Editing and Edit Templates Example

    Edição de células

    Editing through UI

    Você pode entrar no modo de edição para uma célula específica, quando uma célula editável estiver em foco de uma das seguintes maneiras:

    • no clique duplo;
    • em clique único - Um clique único entrará no modo de edição somente se a célula selecionada anteriormente estava no modo de edição e a célula selecionada atualmente for editável. Se a célula selecionada anteriormente não estava no modo de edição, um clique único selecionará a célula sem entrar no modo de edição;
    • na tecla pressione Enter;
    • ao pressionar a tecla F2;

    Você pode sair do modo de edição sem confirmar as alterações de uma das seguintes maneiras:

    • ao pressionar a tecla Escape;
    • quando você executa operações de classificação, filtragem, pesquisa e ocultação;

    Você pode sair do modo de edição e confirmar as alterações de uma das seguintes maneiras:

    • na tecla pressione Enter;
    • ao pressionar a tecla F2;
    • ao pressionar a tecla Tab;
    • on single click to another cell - when you click on another cell in the IgrGrid, your changes will be submitted.
    • Operações como paginação, redimensionamento, fixar ou mover sairão do modo de edição e as alterações serão enviadas.

    [!Note] The cell remains in edit mode when you scroll vertically or horizontally or click outside the IgrGrid. This is valid for both cell editing and row editing.

    Editing through API

    You can also modify the cell value through the IgrGrid API but only if primary key is defined:

    function updateCell() {
        grid1Ref.current.updateCell(newValue, rowID, 'ReorderLevel');
    }
    

    Outra maneira de atualizar a célula é diretamente através do método update da Cell:

    function updateCell() {
        const cell = grid1Ref.current.getCellByColumn(rowIndex, 'ReorderLevel');
        // You can also get cell by rowID if primary key is defined
        // cell = grid1Ref.current.getCellByKey(rowID, 'ReorderLevel');
        cell.update(70);
    }
    

    Cell Editing Templates

    Você pode ver e aprender mais sobre modelos de edição de células padrão no tópico de edição geral.

    Se você quiser fornecer um modelo personalizado que será aplicado a uma célula, você pode passar esse modelo para a própria célula ou para seu cabeçalho. Primeiro crie a coluna como você normalmente faria:

    <IgrColumn
        field="race"
        header="Race"
        dataType="String"
        editable="true"
        name="column1"
        id="column1">
    </IgrColumn>
    

    e passe os modelos para esta coluna no arquivo index.ts:

    public webGridCellEditCellTemplate = (e: { dataContext: IgrCellTemplateContext; }) => {
        let cellValues: any = [];
        let uniqueValues: any = [];
        const cell = e.dataContext.cell;
        const colIndex = cell.id.columnID;
        const field: string = this.grid1.getColumnByVisibleIndex(colIndex).field;
        const key = field + "_" + cell.id.rowID;
        let index = 0;
        for (const i of this.roleplayDataStats as any) {
          if (uniqueValues.indexOf(i[field]) === -1) {
            cellValues.push(
              <>
                <IgrSelectItem
                  selected={e.dataContext.cell.value == i[field]}
                  value={i[field]}
                  key={key + "_" + index}
                >
                  <div key={key + "_" + index}>{i[field]}</div>
                </IgrSelectItem>
              </>
            );
            uniqueValues.push(i[field]);
          }
          index++;
        }
        return (
          <>
            <IgrSelect
              key={key}
              change={(x: any) => {
                setTimeout(() => {
                  cell.editValue = x.value;
                });
              }}
            >
              {cellValues}
            </IgrSelect>
          </>
        );
      };
    

    Uma amostra funcional do acima pode ser encontrada aqui para referência futura:

    Grid Excel Style Editing

    Usar a Edição de Estilo do Excel permite que o usuário navegue pelas células da mesma forma que faria usando o Excel e edite-as rapidamente.

    Implementing this custom functionality can be done by utilizing the events of the IgrGrid. First we hook up to the grid's keydown events, and from there we can implement two functionalities:

    • Modo de edição constante
    function keydownHandler(event) {
      const key = event.keyCode;
      const grid = grid1Ref.current;
      const activeElem = grid.navigation.activeNode;
    
      if ((key >= 48 && key <= 57) ||
          (key >= 65 && key <= 90) ||
          (key >= 97 && key <= 122)) {
            // Number or Alphabet upper case or Alphabet lower case
            const columnName = grid.getColumnByVisibleIndex(activeElem.column).field;
            const cell = grid.getCellByColumn(activeElem.row, columnName);
            if (cell && !grid.crudService.cellInEditMode) {
                grid.crudService.enterEditMode(cell);
                cell.editValue = event.key;
            }
        }
    }
    
    • Navegação Enter / Shift+Enter
    if (key == 13) {
        let thisRow = activeElem.row;
        const column = activeElem.column;
        const rowInfo = grid.dataView;
    
        // to find the next eligible cell, we will use a custom method that will check the next suitable index
        let nextRow = getNextEditableRowIndex(thisRow, rowInfo, event.shiftKey);
    
        // and then we will navigate to it using the grid's built in method navigateTo
        grid1Ref.current.navigateTo(nextRow, column, (obj) => {
            obj.target.activate();
            grid1Ref.current.clearCellSelection();
        });
    }
    

    As principais partes para encontrar o próximo índice elegível seriam:

    //first we check if the currently selected cell is the first or the last
    if (currentRowIndex < 0 || (currentRowIndex === 0 && previous) || (currentRowIndex >= dataView.length - 1 && !previous)) {
    return currentRowIndex;
    }
    // in case using shift + enter combination, we look for the first suitable cell going up the field
    if (previous) {
    return  dataView.findLastIndex((rec, index) => index < currentRowIndex && this.isEditableDataRecordAtIndex(index, dataView));
    }
    // or for the next one down the field
    return dataView.findIndex((rec, index) => index > currentRowIndex && this.isEditableDataRecordAtIndex(index, dataView));
    

    Confira o exemplo completo para referência futura:

    React Grid Excel Style Editing Sample

    Os principais benefícios da abordagem acima incluem:

    • Modo de edição constante: digitar enquanto uma célula estiver selecionada entrará imediatamente no modo de edição com o valor digitado, substituindo o existente
    • Quaisquer linhas sem dados são ignoradas ao navegar com Enter / Shift+Enter. Isso permite que os usuários percorram rapidamente seus valores.

    CRUD operations

    [!Note] Please keep in mind that when you perform some CRUD operation all of the applied pipes like filtering, sorting and grouping will be re-applied and your view will be automatically updated.

    The IgrGrid provides a straightforward API for basic CRUD operations.

    Adding a new record

    The IgrGrid component exposes the addRow method which will add the provided data to the data source itself.

    // Adding a new record
    // Assuming we have a `getNewRecord` method returning the new row data.
    const record = getNewRecord();
    grid1Ref.current.addRow(record);
    

    Updating data in the Grid

    A atualização de dados na grade é obtida por meio dos métodos updateRow e updateCell mas somente se a PrimaryKey para a grade for definida. Você também pode atualizar diretamente uma célula e/ou um valor de linha por meio de seus respectivos métodos de atualização.

    // Updating the whole row
    grid1Ref.current.updateRow(newData, this.selectedCell.cellID.rowID);
    
    // Just a particular cell through the Grid API
    grid1Ref.current.updateCell(newData, this.selectedCell.cellID.rowID, this.selectedCell.column.field);
    
    // Directly using the cell `update` method
    selectedCell.update(newData);
    
    // Directly using the row `update` method
    const row = grid1Ref.current.getRowByKey(rowID);
    row.update(newData);
    

    Deleting data from the Grid

    Tenha em mente que o método deleteRow removerá a linha especificada somente se uma primaryKey for definida.

    // Delete row through Grid API
    grid1Ref.current.deleteRow(selectedCell.cellID.rowID);
    // Delete row through row object
    const row = grid1Ref.current.getRowByIndex(rowIndex);
    row.del();
    

    Cell Validation on Edit Event

    Using the IgrGrid's editing events, we can alter how the user interacts with the IgrGrid.

    Neste exemplo, validaremos uma célula com base nos dados inseridos nela vinculando-a ao evento CellEdit. Se o novo valor da célula não atender aos nossos critérios predefinidos, impediremos que ela alcance a fonte de dados cancelando o evento.

    A primeira coisa que precisamos fazer é vincular ao evento da grade:

    <IgrGrid cellEdit={handleCellEdit}>
    </IgrGrid>
    

    O CellEdit emite sempre que qualquer valor de célula está prestes a ser confirmado. Em nossa definição de CellEdit, precisamos ter certeza de que verificamos nossa coluna específica antes de tomar qualquer ação:

    function handleCellEdit(s: IgrGridBaseDirective, args: IgrGridEditEventArgs): void {
        const column = args.detail.column;
    
        if (column.field === 'UnitsOnOrder') {
            const rowData = args.detail.rowData;
            if (!rowData) {
                return;
            }
            if (args.detail.newValue > rowData.UnitsInStock) {
                args.detail.cancel = true;
                alert("You cannot order more than the units in stock!");  
            }
        }
    }
    

    Se o valor inserido em uma célula na coluna Unidades Encomendadas for maior que a quantidade disponível (o valor em Unidades em Estoque), a edição será cancelada e o usuário será alertado sobre o cancelamento.

    The result of the above validation being applied to our IgrGrid can be seen in the below demo:

    Styling

    Além dos temas predefinidos, a grade pode ser ainda mais personalizada ao definir algumas das propriedades CSS disponíveis. Caso você queira alterar algumas das cores, precisa definir uma classe para a grade primeiro:

    <IgrGrid className="grid"></IgrGrid>
    

    Em seguida, defina as propriedades CSS relacionadas para essa classe:

    .grid {
        --ig-grid-edit-mode-color: orange;
        --ig-grid-cell-editing-background: lightblue;
    }
    

    Styling Example

    API References

    Additional Resources