As I get in a field the data from another field inside the editor

As I get in a field the data from another field inside the editor

klermannklermann Posts: 277Questions: 67Answers: 1

Hello Allan as I get in a field the data from another field inside the editor. I need to retrieve information that comes from the bank in another field so that the user does not edit this information! Look:
fields: [ { name: "dataDespesa" }, { name: "dataDespesa2"} ]

I want to retrieve in field dateDespesa2 of hidden type the data of the field dataDespesa

This question has accepted answers - jump to:

Answers

  • rf1234rf1234 Posts: 2,806Questions: 85Answers: 406
    edited May 2018 Answer ✓
    var Editor = new $.fn.dataTable.Editor( {
    ...
    },
    table: "#yourTable",
    fields: [ {
    { name: "dataDespesa"  },
    { type: "hidden", 
      name: "dataDespesa2"}
    ....
    ]
    
    Editor.on('open', function(e, mode, action) {
       if ( action === 'edit' ) {
            this.set( { 'dataDespesa2': this.val('dataDespesa') } );
        }
    })
    
    

    "on open" or whatever is the suitable event for you.

    You probably had this text translated with Google. I guess from Portuguese. Unfortunately Google isn't very good at that. I would try this:
    https://www.deepl.com/translator
    Much better!

  • klermannklermann Posts: 277Questions: 67Answers: 1

    Now the date value in the table is not updated ... but the example is what I need!

  • rf1234rf1234 Posts: 2,806Questions: 85Answers: 406

    not sure whether I understand what you mean ... if you want to keep having updates of the field whenever the user does something you would need to use "dependent". Like this:

    ....
    Editor.dependent('dataDespesa', function (val, data, callback) {
        Editor.set( { 'dataDespesa2': val } );
    })
    
  • klermannklermann Posts: 277Questions: 67Answers: 1

    The first example I suggested serves, fits, I will use very well. But when I click to update and send the data, in the table (in the list) the field that edits is not updated, the cell that has the data that I update continues with the same information!

  • rf1234rf1234 Posts: 2,806Questions: 85Answers: 406

    that sounds like a different problem and I suggest you post your entire code. Front end and server side. Otherwise I don't see a chance to figure this out.

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

    Look:

    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: "dataDespesa2",
                          type: "hidden"
                      },
                      {
                          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'
                            }
                      }
                ]
            });
    

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

  • klermannklermann Posts: 277Questions: 67Answers: 1
    edited May 2018
    var oTable = $('#despesasTable').DataTable({
                ajax: "/financeiro/despesas/listAll",
                responsive: true,
                iDisplayLength: pageLength,
                order: [ 2, 'desc' ],
                /*footerCallback: function( tfoot, data, start, end, display ) {
                    var api = this.api();
                    console.log($( api.column( 5).footer() ));
                    $( api.column( 5 ).footer() ).html(
                        api.column( 5 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                  },
                //displayLength: 25,
                drawCallback: function ( settings ) {
                    var api = this.api();
                    var rows = api.rows( {page:'current'} ).nodes();
                    var last=null;
                    api.column(5, {page:'current'} ).data().each( function ( group, i ) {
                        if ( last !== group ) {
                            $(rows).eq( i ).before(
                                '<tr class="group bg-blue-grey-50"><td colspan="9">'+group+'</td></tr>'
                            );   
                            last = group;
                        }
                    } );
                },*/
                dom: '<"#.row pl-15 page-head"B<"mt--12"f>><"row"<"col-sm-12"tr>><"row"<"col-sm-5 font-size-12"i><"col-sm-7"p>>',
                bProcessing : true,
                serverSide: false,
                lengthMenu: [
                     [ -1,  10, 20, 30, 50, 100, 200],
                     [ 'Todos', '10 itens', '20 itens', '30 itens', '50 itens', '100 itens', '200 itens' ]
                ],"columnDefs": [
                    { targets: 0, width: '2%'  },
                    { targets: 1, width: '15%' },
                    { targets: 2, width: '10%' },
                    { targets: 3, width: '15%' },
                    { targets: 4,  width:'15%' },
                    { targets: 5, width: '15%' },
                    { targets: 6, width: '10%' },
                    { targets: 7, width: '2%' },
                    { targets: 8, width: '5%'  }
                    ],
                "columns": [
                    { "data": "pagamento",
                        render: function(data, type, row){
                            if(data === ""){
                                  return "";
                            }
                            if ( type === 'display' ) {
                                 return '<div class="checkbox-custom checkbox-default text-left">' +
                                        '<input type="checkbox" class="checkbox-default">' + 
                                        '<label class="mt--5"><span class="verify"></span></label></div>'
                            } 
                            return data;
                        }
                    },
                    { "data": "descricaoDespesa",
                        "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                            $(nTd).html("<div class='text-truncate-last-despesas-max'>" + oData.descricaoDespesa + "</div>");
                            
                        }
                    },
                    { 
                        data: "dataDespesa",
                        mRender: function(data, type, row){
                            if(data === ""){
                                return "";
                            }
                            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;
                        }
                    },
                    { "data": "grupos",
                        render: function(data, type, row){
                              if(data === ""){
                                  return "";
                              }
                              var nomeGrupo = "";
                              if(data == 1) nomeGrupo = 'Essencial'; 
                              if(data == 2) nomeGrupo = 'Importante'; 
                              if(data == 3) nomeGrupo = 'Supérfluo'; 
                              var grupo = "<a class='hightlight' href='../grupos/'>" + nomeGrupo +
                              " <i class='fa fa-external-link font-size-10' aria-hidden='true'></i></a>";
                              return grupo;
                      }
                    },
                    { "data": "minhasContas[0].nomeMinhasContas" },
                    { "data": "tipoDespesas[0].nomeTipoDespesas" },
                    { "data": "valorDespesa",
                        mRender: $.fn.dataTable.render.number('.', ',', 2, 'R$ ')
                    },
                    { data: "cor", 
                        orderable: false,
                        mRender: function(data, type, full, meta){
                            return '<span class="badge badge-radius" style="background-color:' + data + '"><i class="icon" aria-hidden="true"></i></span>';
                        }
                    },
                    {
                        data: null,
                        orderable: false,
                        className: "center",
                        defaultContent: '<a href="" class="editor_edit"><i class="icon wb-edit font-size-12 blue-grey-400" aria-hidden="true"></i></a> ' +
                        ' <a href="" class="editor_remove"><i class="icon wb-trash font-size-12 blue-grey-400" aria-hidden="true"></i></a>'
                    }
                ],
    
  • klermannklermann Posts: 277Questions: 67Answers: 1
    edited May 2018
    select: "single",
                buttons: [
                     {  extend:     "create", 
                        editor:     editor, 
                        formButtons: [
                            {
                                label: 'Cancelar',
                                fn: function () { this.close(); },
                            },
                            'Inserir despesas  <i class="icon fa-plus"></i>',
                        ],
                        formMessage: '<i class="icon wb-info-circle" aria-hidden=""></i> Entre com os dados para criar uma nova despesa.',
                        text:       '<a data-tooltip="Clique para criar uma Despesa" class="white text-break"><i class="icon fa-plus"></i></a>',
                        titleAttr:  'Criar Despesa',
                        className: classeBtnEditor
                    },
                    {   extend: "edit",
                        editor: editor,
                        formButtons: [
                            {
                                label: 'Cancelar',
                                fn: function () { this.close(); }
                            },
                            'Editar despesas  <i class="icon fa-edit"></i>'
                        ],
                        text:       '<a data-tooltip="Clique para editar a Despesa" class="white text-break"><i class="icon fa-edit"></i></a>',
                        titleAttr:  'Editar despesas',
                        className: classeBtnEditor
                    },
                    {   extend: "remove",
                        editor: editor,
                        formMessage: function ( e, dt ) {
                            var rows = dt.rows( e.modifier() ).data().pluck('descricaoDespesa');
                            return '<div class="red-800">Você tem certeza que deseja remover essa Despesa? </br>'+
                                'Não é possível sua recuperação! </div><b>' + rows.join() + '</b> <i class="icon fa-trash-o"></i>';
                        },
                        formButtons: [
                            {
                                className: 'btn btn-danger',
                                label: 'Cancelar',
                                fn: function () { this.close(); }
                            },
                            'Remover despesa  <i class="icon fa-trash-o"></i>'
                        ],
                        text:       '<a data-tooltip="Clique para remover a Despesa" class="white text-break"><i class="icon fa-trash-o"></i></a>',
                        titleAttr:  'Excluir Despesa',
                        className: classeBtnEditor,
                        exportOptions: {
                            columns: [ 1, ':visible' ]
                        }
                    }, 
                    {   extend:     'pageLength',
                        text:      '<a data-tooltip="Listar itens da tabela" class="text-break"><i class="icon wb-list ' + corIcon + '"></i></a>',
                        titleAttr:  'Listar itens',
                        className:  classeBtn
                    },
                    {
                        text:       '<a data-tooltip="Atualizar itens da tabela" class="text-break"><i class="icon fa-refresh ' + corIcon + '"></i></a>',
                        titleAttr:  'Atualizar itens',
                        className: classeBtn,
                        action: function ( e, dt, node, config ) {
                            dt.ajax.reload();
                        }
                    },
                    {
                        extend:    'copyHtml5',
                        text:       '<a data-tooltip="Copia os dados para a área de transferência" class="text-break"><i class="fa fa-files-o ' + corIcon + '"></i></a>',
                        titleAttr: 'Copiar',
                        exportOptions: positionExport,
                        message:   messageFiles,
                        className: classeBtn
                    },
                    {
                        extend:    'excel',
                        text:      '<a data-tooltip="Exportar para Excel no formato [.xls]" class="text-break"><i class="fa fa-file-excel-o ' + corIcon + '"></i></a>',
                        titleAttr: 'Excel',
                        exportOptions: positionExport,
                        customize: function(xlsx) {
                            var sheet = xlsx.xl.worksheets['sheet1.xml'];
                            $('row:odd c', sheet).attr( 'f', '43');
                            
                        },
                        message:   messageFiles,
                        className: classeBtn,
                        enabled: verifyPerfil
                    },
                    {
                        extend:    'pdfHtml5',
                        text:      '<a data-tooltip="Exportar para PDF no formato [.pdf]" class="text-break"><i class="fa fa-file-pdf-o ' + corIcon + '"></i></a>',
                        orientation: 'portrait',
                        titleAttr: 'Exportar (download) para PDF',
                        filename: 'relatorio_despesas_clipboard',
                        exportOptions: positionExport,
                        customize: function(doc){
                            exportPdf(doc);                     
                        },
                        message:   messageFiles,
                        className: classeBtn,
                        enabled: verifyPerfil
                    },
                    {
                        extend:    'pdfHtml5',
                        text:      '<a data-tooltip="Exportar para PDF no formato [.pdf]. Abre no navegador" class="text-break"><i class="fa fa-file-pdf-o ' + corIcon + '"></i></a>',
                        titleAttr: 'Abrir PDF no navegador',
                        download: 'open',
                        filename: 'relatorio_despesas_clipboard',
                        exportOptions: positionExport,
                        customize: function(doc){
                            exportPdf(doc);                     
                        },
                        message:   messageFiles,
                        className: classeBtn,
                        enabled: verifyPerfil
                    },
                    {
                        extend:    'print',
                        text:      '<a data-tooltip="Imprimir dados. Abre no navegador. Clique [CTRL + P]" class="text-break"><i class="fa fa-print ' + corIcon + '"></i></a>',
                        autoPrint: true,
                        exportOptions: positionExport,
                        customize: function (win) {
                            $(win.document.body).find('table').addClass('display').css('font-size', '14px');
                            $(win.document.body).find('tr:nth-child(odd) td').each(function(index){
                                $(this).css('background-color','#F1F4F5');
                            });
                            $(win.document.body).find('h3').css('text-align','center');
                        },
                        titleAttr: 'Inprimir',
                        message:   messageFiles,
                        className: classeBtn,
                        enabled: verifyPerfil
                    }
                 ],
                 rowCallback: function ( row, data ) {
                        var verify = $('.verify', row);
                        $('input.checkbox-default', row).prop( 'checked', data.pagamento == '1' );
                        if(data.pagamento == true){
                            verify.html('<span class="font-size-12 teal-500">Paga!</span>');
                        }else if(data.pagamento == false){
                            verify.html('<span class="font-size-12 red-500">Pendente</span>');
                        }
                 },
                 drawCallback: function(){
                     var api = this.api();
                    nb_cols = 6;
                    j = 6;
                    while(j <= nb_cols){
                        var pageTotal = api.column(j, { page: 'current'} ).data().sum();
                        $('#despesasTable tfoot tr:eq(0) th:eq('+j+')').html( "R$ " + Math.round(pageTotal * 100) / 100);
                        j++;
                    } 
                 }
            });
    

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

  • rf1234rf1234 Posts: 2,806Questions: 85Answers: 406

    Sorry, I cannot read it that way without using Markdown. But maybe somebody else can find the error?

  • allanallan Posts: 61,665Questions: 1Answers: 10,096 Site admin

    That's a whole lot of code! But I don't see @rf1234's suggestion of dependent() anywhere in it. That is exactly what I would suggest as well.

    Also, I've formatted your code using Markdown now. Details on how to highlight code using markdown can be found in this guide. It would be useful if you could use that please.

    Allan

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

    I just follow the recommended to format the code, and every time I publish the code comes out distorted, I am unable to do anything for formatting since I have only this way to format.
    Code

  • tangerinetangerine Posts: 3,348Questions: 36Answers: 394

    The "recommended" is to format the code using Markdown.
    A link is provided for your convenience.

  • rf1234rf1234 Posts: 2,806Questions: 85Answers: 406
    edited May 2018

    Hi klermann,

    to be honest I have no idea what is wrong with your code. I'd take a look at what you really send to the server. If the update isn't in those data you know it's a front end problem. Otherwise you can try to debug the back end ...

    Sorry for not being able to help more ...

    Regarding the code formatting. All I do is copy and paste those three backticks that you find below. I put them before and after my code. That's usually good enough ...

  • klermannklermann Posts: 277Questions: 67Answers: 1

    Hi rf1234,
    solved here, thanks for help!

  • klermannklermann Posts: 277Questions: 67Answers: 1

    Hello rf1234, I once asked myself a question about the same question. As I have a checkbox inside the datatable that does not have the same behavior as the Editor to populate the values, how do I solve this problem by clicking on the checkbox set the values ​​in hidden fields?

  • rf1234rf1234 Posts: 2,806Questions: 85Answers: 406

    Just take a look at „dependent“. I posted a code example above. You can set the value of the hidden field dependent on the user clicking the checkbox.

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

    But what worked right here for me was this example:

     editor.on('open', function(e, mode, action) {
                   if ( action === 'edit' || action === 'remove' ) {
                       this.set( { 'adicDiaAnterior'   : this.val('dataDespesa') } );
                       this.set( { 'adicValorAnterior' : this.val('valorDespesa') } );
                       this.set( { 'adicPagamento' : this.val('pagamento') } );
                    }
            });
            
    

    not the dependent;

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

    Even using the example, it does not show the value in the console nor does it arrow the value in the data output!
    editor.dependent("pagamento", function (val) { console.log(val); editor.field("adicPagamento").set(val);

  • allanallan Posts: 61,665Questions: 1Answers: 10,096 Site admin

    Happy to take a look at a test page showing the issue.

    Allan

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

    Follow Allan.
    pass: admin
    login: admin@admin.com
    /ec2-52-21-31-80.compute-1.amazonaws.com:8080/financeiro/despesas/

  • allanallan Posts: 61,665Questions: 1Answers: 10,096 Site admin

    I get an error when attempting to login there:

    Login inv�lido, senha ou nome do usu�rio n�o confere.

    Allan

  • klermannklermann Posts: 277Questions: 67Answers: 1

    login: admin@admin.com
    pass: admin

  • allanallan Posts: 61,665Questions: 1Answers: 10,096 Site admin
    Answer ✓

    It looks like it is a custom field type:

                      {
                          name: "pagamento",
                          type: "recebida",
                          def: 0
                      },
    

    Your plug-in would need to trigger the change event on the input element when the set function is triggered.

    Btw in your spinner plug-in you have:

    '<input id="despesaFixaQuant"

    That id should be avoided since it would mean you can't use that field type more than once on the page (otherwise you would have elements with duplicate ids).

    Allan

This discussion has been closed.