is it possible to add a new column when its rendering?

is it possible to add a new column when its rendering?

maurocataniamaurocatania Posts: 3Questions: 1Answers: 0

i have this:

for (i = 0; i < columnsDef.length; i++) {
columnEdit = clone(columnsDef[i]);

                if (columnEdit.mData === "chk") {
                    let btnDisparador;
                    $('[id^="accion_"]').each(function () {
                        let title = $(this).attr("title");
                        if (title && title.toLowerCase().includes("editar")) {
                            btnDisparador = this;
                        }
                    });
                    if (response.EdicionAutomatica) {
                        if (response.EdicionAccionIndividual) {
                            columnEdit.mRender = function (data, type, full, meta) {
                                let sData = data;
                                sData = '<div style="display: flex;"> <input type="checkbox" name="id[]">'
                                    + '<button id="btnConfirmarEdicionIndiv_' + meta.row + '"title = "Confirmar edición de la fila"'
                                    + 'type = "button" class="btn btn-accion btn-block btn-flat btnConfirmarEdicionIndiv_"'
                                    + 'style = "height:23px;width:23px;font-size:small; font-weight:bold; background-color:white; display:inline;min-height:23px; margin-top: 5px; margin-right: 5px; margin-bottom: 5px; margin-left: 5px;" disabled > '
                                    + '<img src="Imagenes/Globales/success.png" alt="" height="15px" width="15px"></button>'
                                    + '<button id="btnCancelarEdicionIndiv_' + meta.row + '"title = "Cancelar edición de la fila" onclick="cancelarEdicionIndividual(this,' + idVista + ')"'
                                    + 'type = "button" class="btn btn-accion btn-block btn-flat btnCancelarEdicionIndiv_"'
                                    + 'style = "height:23px;width:23px;font-size:small; font-weight:bold; background-color:white; display:inline;min-height:23px; margin-top: 5px; margin-right: 5px; margin-bottom: 5px; margin-left: 5px;" disabled > '
                                    + '<img src="Imagenes/Globales/cancelar.png" alt="" height="15px" width="15px"></button>'
                                    + '</div>'

                                $('[id^="btnConfirmarEdicionIndiv_"]').each(function () {
                                    $(this).prop('onclick', null).off('click');
                                    $(this).click({ btnAccion: btnDisparador.id, contexto: contexto }
                                        , function (event) {
                                            confirmarEdicion(document.getElementById(event.data.btnAccion), event.data.contexto, false, btnDisparador, true, $(this));
                                            $('#panel_datos_' + idVista).data('editando', false);
                                        });
                                });

                                return sData;
                            }

                        }

}

basically i'm just adding a couple of buttons in the column where the check is. The thing is, i dont like it. I'm trying to add a new column to put the buttons in, but i'm not sure how. These buttons are only used in very rare ocassions, so i wouldnt want them to be there always, that's why i'm trying to add them dynamically. Is it possible?

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin

    You are setting up the columnDefs variable to pass to columnDefs on initialisation? That looks fine to me. I'd use render and data rather than the legacy mRender and mData, but otherwise, I think that is okay.

    Allan

  • maurocataniamaurocatania Posts: 3Questions: 1Answers: 0

    i get columnDefs from a controller (i'm using MVC) and then i edit it and do this:

    if (editarEnGrilla === true) columnsDef = columnsDefEdit;

            table = $('#tbl_vista_' + idVista).DataTable({
                sScrollY: "10vh",
                sScrollX: "100%",
                sScrollXInner: grillaWidth,
                bFilter: true,
                bAutoWidth: response.AutoWidth,
                bJQueryUI: true,
                bPaginate: bMuestraPaginado,
                iDisplayLength: iPaginado,
                bProcessing: true,
                iSearchDelay: 1000,
                oLanguage: {
                    sSearch: "Buscar en vista",
                    sEmptyTable: "No existen registros para mostrar.",
                    sLengthMenu: "&nbsp;Mostrar &nbsp;&nbsp; _MENU_&nbsp; registros por página.",
                    sZeroRecords: "No existen registros para mostrar.",
                    sInfo: "Página &nbsp;_PAGE_&nbsp; de &nbsp;_PAGES_",
                    sInfoEmpty: "No existen registros para mostrar.",
                    sInfoFiltered: "(filtrado a partir de &nbsp;_MAX_&nbsp; registros en total)",
                    sLoadingRecords: "Por favor espere. Cargando registros...",
                    decimal: ",",
                    thousands: ".",
                    oPaginate: {
                        "sFirst": "<<",
                        "sLast": ">>",
                        "sNext": ">",
                        "sPrevious": "<"
                    }
                },
                aoColumns: columnsDef,
                aaData: oDatos,
                sPaginationType: "full_numbers",
                "rowCallback": function (row, data, index) {
                    if (data.BackgroundColor) {
                        $('td', row).css("background-color", data.BackgroundColor);
                    }
                    if (data.TextColor) {
                        $('td', row).css("color", data.TextColor);
                    }
                },
                "fnDrawCallback": function (oSettings) {
                    var i = 0;
                    var j = 0;
                    //Setea los valores del data-row-index y data-column-index 
                    //para poder ubicar las celdas por fila y columna después de ordenar o agregar filas
                    $('#tbl_vista_' + idVista + ' tbody tr').each(function () {
    
                        $(this).children("td").each(function () {
                            $(this).children().data('row-index', i);
                            $(this).children().data('column-index', j);
                            j++;
                        });
                        j = 0;
                        i++;
                    });
                    $('#tbl_vista_' + idVista).css('margin-left', '0');
                },
                "headerCallback": function (thead, data, start, end, display) {
                    if ($(thead).find('th:first')) {
                        var checkAll = $(thead).find('th:first').find('input[name="select_all"]');
                        if (checkAll.length > 0) {
                            checkAll.parent().find('span').remove();
                            checkAll.closest('div').css('padding', '0px');
                            checkAll.closest('th').css('padding', '0px');
                            checkAll.closest('th').css('width', '34px!important');
                            checkAll.closest('th').css('max-width', '34px');
                        }
                        checkAll = null;
                        delete checkAll;
                    }
                },
                sDom: "<'H'l<'#infoRegistros'>f>rt<'F'ip><'clear'>",
                order: []
            });
    

    a lot of this code isn't mine (i'm guessing someone at my work who doesn't work here anymore did it) and i need to modify it. In columnsDefEdit there are all of the edits made in mRender (i'm actually just guessing cause i dont really know how Data Table works, but i'm pretty sure the changes are all in mRender as shown in my question). The thing is, this is the result:

    the buttons in the table are one of the edits made. I want to make a new column for them, cause right now they are "sharing" the column with the checkbox. I dont really know how to do this :(

  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin
    Answer ✓

    I'd add it to the columnDefs array - e.g.

    if (editarEnGrilla === true) {
      columnsDef.push({
        title: 'Edit',
        data: null,
        render: function (data, type, row) {
          // create and return the buttons
        },
        target: columnsDef.length
      });
    }
    

    Note in particular the use of target: columnsDef.length - that will resolve to the length of the array before the new column is added, thus adding an extra column.

    Allan

  • maurocataniamaurocatania Posts: 3Questions: 1Answers: 0

    thank you so much! it worked :blush:

Sign In or Register to comment.