Date Error When Adding Row

Date Error When Adding Row

klermannklermann Posts: 277Questions: 67Answers: 1
edited May 2018 in Free community support

Hello Allan, I'm using the code below to add a new row in the datatable and when I throw the rendering of the date the line is added normally and when it has rendered the date error indefined. Can you help?

Input of error:

{ 
                    data: "dataDespesa"/*,
                    mRender: function(data){
                        dataDay = data.dayOfMonth < 10 ? '0' + data.dayOfMonth : data.dayOfMonth;
                        dataMonth = data.monthValue < 10 ? '0' + data.monthValue : data.monthValue;
                        dataObj = dataDay + '/' + dataMonth + '/' + data.year
                        var dt = new Date(dataObj);
                        var options = {  day: 'numeric', weekday: 'long', month: 'long',};
                        //return dt.toLocaleDateString('pt-BR', options);
                        return dataObj;
                    }*/
                },

Code add row:

function appendRow(pagamento, descricaoDespesa, dataDespesa, grupos, conta, categoria, valorDespesa, cor) {
           var t = $('#despesasTable').DataTable();
           var node = t.row.add([
               pagamento,
               descricaoDespesa,
               dataDespesa,
               grupos,
               conta,
               categoria,
               valorDespesa,
               cor,
           ]).draw().node();
           var detail_row = '';

           detail_row = '<h3>Custom HTML</h3>';
           $(node).addClass('result-row');
           node = node.outerHTML += detail_row;
           $(node).hide().fadeIn('normal');
        }

         $('#btnInsert').click(function() {
           appendRow(null, null, null, null, null, null, '3000', null, null);
        });`

Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

This question has accepted answers - jump to:

Answers

  • allanallan Posts: 63,332Questions: 1Answers: 10,436 Site admin

    It looks like you are adding an array of data, but you are telling DataTables to expect an object (through the use of the columns.data option).

    See the manual for more information.

    Allan

  • klermannklermann Posts: 277Questions: 67Answers: 1

    Alan, my problem is that I need to add just one row to the datatable at time of excution, in order to insert some data in this line ... How can I do it?

  • klermannklermann Posts: 277Questions: 67Answers: 1

    Even if I use this example the same error happens, and I have to disable the rendering of the date for the example to work, after that the table data does not just show the example.
    `$(document).ready(function() {
    var t = $('#example').DataTable();
    var counter = 1;

    $('#addRow').on( 'click', function () {
        t.row.add( [
            counter +'.1',
            counter +'.2',
            counter +'.3',
            counter +'.4',
            counter +'.5'
        ] ).draw( false );
    
        counter++;
    } );
    
    // Automatically add a first row of data
    $('#addRow').click();
    

    } );`

  • Tester2017Tester2017 Posts: 145Questions: 23Answers: 17

    Oi Klerman,

    What is the exact error message you are receiving? I am adding rows on the fly too and without any problems. So the message must give some kind of hint.

  • kthorngrenkthorngren Posts: 21,246Questions: 26Answers: 4,929

    As Allan indicated you are using columns.data so you need to add the row as an object not an array. Something like the first example here:
    https://datatables.net/reference/api/row.add()#Examples

    Kevin

  • klermannklermann Posts: 277Questions: 67Answers: 1

    I gotta add it here! And now, how do I make the cell date empty, because when I add a row the date field shows in cell: undefined / undefined / undefined, and I do not need to show any information in the cell!

  • allanallan Posts: 63,332Questions: 1Answers: 10,436 Site admin
    Answer ✓

    As I said above, you need to pass in an object to row.add(), not an array:

    t.row.add( {
      dataDespesa: ...
      ...
    } );
    

    Allan

  • klermannklermann Posts: 277Questions: 67Answers: 1

    Allan I passed the object and managed to add the line. Now the question is and how can I send the empty date cell because even though I'm sending an empty string, when it displays in the datatable it is shown like this: undefined / undefined / undefined /, but I need to be empty

  • allanallan Posts: 63,332Questions: 1Answers: 10,436 Site admin
    edited May 2018

    Simply give it an an empty string. dateProperty: ''.

  • klermannklermann Posts: 277Questions: 67Answers: 1

    Even passing an empty string, I get undefined return!


    t.row.add({ pagamento : '', descricaoDespesa : '', dataDespesa : '', grupos : '', conta : '', categoria : '', valorDespesa : '30000', cor : '', }).draw()

  • kthorngrenkthorngren Posts: 21,246Questions: 26Answers: 4,929
    edited May 2018

    Post your full Datatables init code and your code to add the row so we can see what you are doing.

    Kevin

  • klermannklermann Posts: 277Questions: 67Answers: 1

    editor = new $.fn.dataTable.Editor({ ajax: { dataType: "JSON", contentType: 'application/json', data: function ( d ) { var obj; for (var key in d.data) { obj = d.data[key]; break; } return JSON.stringify( obj ); }, create: { type:"POST", url: "/financeiro/despesas/listOne" }, edit: { type: "POST", url: "/financeiro/despesas/listOne_id_" }, remove: { type: "POST", url: "/financeiro/despesas/listOne_id_" } }, table: "#despesasTable", template: '#form-group-editor', idSrc: "id", i18n: { error: { system: '<div class="alert alert-danger alert-dismissible" role="alert">' + '<button type="button" class="close" data-dismiss="alert" aria-label="close">' + '<span aria-hidden="true">x</span></button> Ocorreu um erro! Atualize a página e refaça a operação!</div>' } }, fields: [ { name: "descricaoDespesa", attr: { placeholder: 'Descrição da despesa' }, "type": "autoComplete", "opts": { minLength: 1, source: function( request, response ) { $.getJSON( "/financeiro/despesas/getPalavraDespesas", request, function( data, status, xhr ) { response( data ); }); } } }, { name: "dataDespesa", type: "datetime", opts: { minDate: new Date('2000-01-01'), maxDate: new Date('2050-12-31'), format: 'DD/MM/YYYY', locale : 'pt-br', showTodayButton : true, showClear : true } }, { name: "pagamento", type: "recebida", def: 0 }, { name: "valorDespesa", id: "receitaValor", type: "money" }, { name: "cor", id: "receitaCor", type: "receitasCor", def: "#FF9562" }, { name: "grupos", id: "grupos", fieldInfo: 'Sua despesa pode ser atribuída a um grupo!', type: "grupos" }, { name: 'minhasContas[].id', type: "select2", "opts": { "placeholder": "Selecione a Conta", "allowClear": true } }, { name: 'tipoDespesas[].id', "type": "select2", "opts": { "placeholder": "Selecione um categoria", "tags": false, "allowClear": true } }, { name: "despesaFixa", type: "despesaFixa", def: 0 }, { name: "repetirLancDespesa", type: "condition", def: 0 }, { name: "despesaFixaQuantidade", id: "despesaFixaQuant", type: "spinner" }, { name: "despesaFixaTempo", id: 'despesaFixaTempo', type: 'select2', "opts": { "placeholder": "Período", "allowClear": true } }, { name: "addObservacao", id: "addObservacao", type: "textarea", attr: { placeholder: 'Adicionar observação' } } ] });

  • Tester2017Tester2017 Posts: 145Questions: 23Answers: 17

    What if you change locale : 'pt-br', in locale : 'pt-BR', ?

  • allanallan Posts: 63,332Questions: 1Answers: 10,436 Site admin

    That's your Editor initialisation. The problem appears to be that you have a formatter for that column in your DataTable initialisation - although without being able to see that code I can't say for sure. My guess is that whatever formatter you have there isn't correctly handling an empty string.

  • klermannklermann Posts: 277Questions: 67Answers: 1
    edited May 2018

    The problem is here:

    `{
                         name: "dataDespesa",
                         type: "datetime",
                         opts: {
                            minDate: new Date('2000-01-01'),
                            maxDate: new Date('2050-12-31'),
                            format: 'DD/MM/YYYY',
                            locale : 'pt-BR',
                            showTodayButton : true,
                            showClear : true
                         }
                      }` 
    or here:
    `{ 
                        data: "dataDespesa",
                        mRender: function(data, type, row){
                            dataDay = data.dayOfMonth < 10 ? '0' + data.dayOfMonth : data.dayOfMonth;
                            dataMonth = data.monthValue < 10 ? '0' + data.monthValue : data.monthValue;
                            dataObj = dataDay + '/' + dataMonth + '/' + data.year
                            var dt = new Date(dataObj);
                            var options = {  day: 'numeric', weekday: 'long', month: 'long',};
                            //return dt.toLocaleDateString('pt-BR', options);
                            return dataObj;
                        }
                    },`
    

    or in the formatting file that I use the bootstrap.

    EDIT: Updated code to use Markdown code formatting.

  • Tester2017Tester2017 Posts: 145Questions: 23Answers: 17

    Klerman, in your render function put a console.log to see what values you are generating.

  • kthorngrenkthorngren Posts: 21,246Questions: 26Answers: 4,929
    Answer ✓

    You didn't post you row add code but I suspect the problem is you don't have fields like dataDespesa.dayOfMonth, dataDespesa.monthValue or dataDespesa.year which presumably you do in the original data. This is causing the undefined. You can check to see if dataDespesa is blank and return it if so otherwise format your date field.

    Also, please use the Markdown code formatting.

    Kevin

  • klermannklermann Posts: 277Questions: 67Answers: 1

    Perfect your suggestion kthorngren. Thanks for All!

This discussion has been closed.