Quantcast
Channel: Recent Discussions — DataTables forums
Viewing all 82258 articles
Browse latest View live

Upload file

$
0
0

I have two problems with the upload, where I'm pretty at a loss now. It's a simple upload. Upload file, when all ok close window done.
I use my own server file that does the filehandling. The file is uploaded and can be found in the intended directory, but I always get an error message that the file was not uploaded.

My server script sends the correct answer, as you can read in your documentation. I am at a loss as to what is going wrong here.

{"files":{
 "tticket":{
  "MEMBERSo.xlsx":{
   "id":0
  }
 }
},
"upload":{
 "filename": "MEMBERSo.xlsx"
}}

The second problem, once something has been done with the frame, it won't work again. So if I get the error message back at the first call, wrong file format and I close the from and start again, then the error message remains. If you ignore the message and try to upload another file, nothing works anymore. In the browser debugger you can see that the ajax is not called. An ajax is then sent when I reload the page.
Enclosed my js script and a screenshot of the error message and the json that comes from the script

Can you help me in my problem?

Andreas

Link to test case: is local on my PC, not external.
Debugger code (debug.datatables.net): I tried to generate the debugger code, but the given link did not work,
https://debug.datatables.net/izodiy
Error messages shown: see above

var editor;

$( document ).ready( function() {
    var dtButtons = [];

    editor = new $.fn.dataTable.Editor( {
        ajax: 'php/atw-core/server-process.php?tt=2',
        table: '#file-tbl',
        display: 'bootstrap',
        /*template: '#fileForm',*/
        fields: [
            {
                label: 'Filename:',
                name: 'filename',
                type: 'upload',
                dragDrop: false
            }
        ]
    } );

    dtButtons.push( {
        extend: 'create',
        editor: editor,
        text: '<i class="fas fa-upload text-red-900"></i>',
        titleAttr: 'Upload file',
        className: 'btn-atw btn-dt',
        formButtons: [
            { text: 'up', action: function() { this.submit(); }, className: 'btn-danger btn-dt' },
            { text: 'Cancel', action: function() { this.close(); }, className: 'btn-light btn-dt' }
        ],
        formTitle: '<i class="fas fa-upload text-red-900"></i> <span class="text-red-900">Upload file</span>'
    } );

    dtButtons.push( {
        extend: 'remove',
        editor: editor,
        text: '<i class="fas fa-trash text-red-900"></i>',
        titleAttr: 'delete selected file',
        className: 'btn-atw btn-dt',
        formButtons: [
            { text: 'Remove', action: function() { this.submit(); }, className: 'btn-danger btn-dt' },
            { text: 'Cancel', action: function() { this.close(); }, className: 'btn-light btn-dt' }
        ],
        formTitle: '<i class="fas fa-trash text-red-900"></i> <span class="text-red-900">remove selected file</span>'
    } );

    var tticket = $( '#file-tbl' ).DataTable( {
        ajax: {
            url: 'php/atw-core/server-process.php?tt=1',
            type: 'POST'
        },
        autoWidth: false,
        select: true,
        serverSide: true,
        processing: true,
        ordering: false,
        pagingType: 'numbers',
        pageLength: 15,
        dom: "<'row'<'col-sm-4 DT_Buttons_Style'B><'col-sm-4'><'col-sm-4'>>rt<'row'<'col-sm-6'i><'col-sm-6'p>>",
        columnDefs: [
            { targets: 0, visible: true, className: 'text-right w--30' },
            { targets: 1, visible: true, className: 'text-left' },
            { targets: 2, visible: true, className: 'text-left' },
            { targets: 3, visible: true, className: 'text-right' },
            { targets: 4, visible: true, className: 'text-right w--180' },
            { targets: '_all', visible: false, searchable: false, orderable: false }
        ],
        columns: [
            {
                data: '_index'
            },{
                data: 'filename'
            },{
                data: 'fileext'
            },{
                data: 'filesize', render: function( data ) {
                    return formatBytes( data );
                }
            },{
                data: 'filedate'
            }
        ],
        buttons: {
            dom: {
                container: {
                    className: 'dt-buttons btn-group flex-wrap'
                }
            },
            buttons: dtButtons
        },
        initComplete: function( data ) {
            $( '#file-tbl' ).removeClass( 'd-none' );
        }
    } );

    editor.on( 'uploadXhrSuccess uploadXhrError', function( e, b, json ) {
        console.log( json );

        //editor.close();
        //tticket.ajax.reload( null, false );
    } );
} );

$.extend( true, $.fn.dataTable.Editor.classes, {
    field: {
        label: 'col-md-12 col-form-label pa-label',
        input: 'col-md-12 pa-form'
    }
} );

function formatBytes( bytes, decimals = 2 ) {
    if ( 0 === bytes ) return '0 Bytes';

    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

    const i = Math.floor( Math.log( bytes ) / Math.log( k ) );

    return parseFloat( (bytes / Math.pow( k, i ) ).toFixed( dm ) ) + ' ' + sizes[i];
}

Datatable sorting with input cells values and empty values

$
0
0

Hello ,

My scenario is as below

EMPTY_CELL
123
345
EMPTY_CELL
EMPTY_CELL
567
EMPTY_CELL

upon ascending it should sort by

123
345
567
EMPTY_CELL
EMPTY_CELL
EMPTY_CELL
EMPTY_CELL

Where are descending goes by

EMPTY_CELL
EMPTY_CELL
EMPTY_CELL
EMPTY_CELL
567
345
123

Currently im using this code/
$.fn.dataTable.ext.order['dom-text-numeric'] = function ( settings, col )
{
return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
return $('input', td).val() * 1;
} );
}

Any help appreciated !!

How to use your own html and css structure and include only the javaScript datatable?

$
0
0

How to use your own html and css structure and include only the js attributes for search and pagination to work?

I would like to use this html and css below made by me and include only javaScript Datatable for features like search and page, is it possible?

Table jumps back to first row when row click expands

$
0
0

My table will jump back to the top row when I click on an row to expand. How do I prevent this from happening.

var table = $('#timeLogTable_Vacation').DataTable( {
    rowCallback: function(row, data, index){  
            if(data['time_log_date_yyyymmdd'] <= date){
                $(row).find('td:eq(0)').css('color', 'red');
                $(row).find('td:eq(1)').css('color', 'red');
                $(row).find('td:eq(2)').css('color', 'red');
            }
    },
    displayLength:100,
    scrollY: '495px',
    scrollCollapse: true,
    paging: false,
    dom: 'Bfrtip',
    language: {  sSearch: 'Table Search: '},
    buttons: {
        buttons: [ 
                   { text: 'Create Vacation Day',
                     attr: { id: 'displayVacationDayModalButton'},
                     action: function ( e, dt, node, config ) {displayVacationDayModal() }
                  },
                  { text: 'Remove Vacation Entry',
                    className: 'btn-danger',
                    attr: { id: 'removeVacationDayModalButton'},
                    action: function ( e, dt, node, config ) {removeVacationDayModal() },
                    enabled: false
                   }
              ],
                dom: {
                      button: { className: 'btn btn-primary'},
                      buttonLiner: { tag: null }
                     }
    },
    processing: true,
    serverSide: true,
    ajax: {
        url: "ssp_TimeLogTable_Vacation.php",
        dataType: 'json',
        data: {employeeNumber: employeeNumber,
               employeeDepartmentCode: employeeDepartmentCode },
    },
         columns: [
                      { data: 'time_log_year', visible: false},
                          { data: 'employee_last_name', visible: false},
                          { data: 'employee_full_name', visible: false},
                          { data: 'employee_manager_number', visible: false},
                          { data: 'sort_date', visible: false},
                          { data: 'created_by', visible: false},
                          { data: 'created_on', visible: false},
                          { data: 'time_log_date_yyyymmdd', visible: false},
                          { data: 'out_of_office', orderable: false},
                          { data: 'time_log_date', orderable: false },
                      { data: 'total_hours', orderable: false}
                  ],
   select: {style: 'single'},  
   
   order: [[1, 'asc'],[2, 'asc'],[4, 'asc']],
   
   rowGroup: {
               dataSrc: [ 'time_log_year', 'employee_full_name'],
               startRender: function (rows, group, level) {
                   var all;

                   if (level === 0) {
                       top = group;
                       all = group;
                   } else {
                       // if parent collapsed, nothing to do
                       if (!!collapsedGroups[top]) {
                           return;
                       }
                       all = top + group;
                   }
                   
                   var collapsed = !!collapsedGroups[all];

                   rows.nodes().each(function (r) {
                       r.style.display = 'none';
                       if (collapsed) {
                         r.style.display = '';
                       }});

                  //fontawsome + and - 
                  var toggleClass = collapsed ? 'fa fa-minus-circle' : 'fa fa-plus-circle';
                  var groupTD = '';

                    if(level == 0){
                                  groupTD = '<td colspan="' + rows.columns()[0].length +'">' + group + '</td>'
                    }else{
                                  groupTD = '<td colspan="' + rows.columns()[0].length +'">' + '<span style="color:#007bff;" class="fa fa-fw ' + toggleClass + ' toggler"/> ' + group + ' (' + rows.count() + ')</td>'
                     }

                // Add category name to the <tr>
                return $('<tr/>')
                
                  .append(groupTD)
                  .attr('data-name', all)
                  .toggleClass('collapsed', collapsed);

               }
    },
 });//END .dataTable

  $('#timeLogTable_Vacation tbody').on('click', 'tr.dtrg-start', function() {
      var name = $(this).data('name');
      collapsedGroups[name] = !collapsedGroups[name];
      table.buttons(1).disable();
      table.draw(false);
  });
  
  table.on( 'select deselect', function (e, dt, type, indexes) {

     //reset button to disabled
      var selectedRows = table.rows( { selected: true } ).count();
      table.button( 1 ).disable( selectedRows > 0 );
    
      var data = table.rows(indexes).data();
      var timeLogDate = data[0]['time_log_date_yyyymmdd'];
      var createdBy = data[0]['created_by'];
      var employeeManagerNumber = data[0]['employee_manager_number'];

      var surrogateFound = surrogateManagers.includes(employeeManagerNumber);

     if( (createdBy.trim() == userProfile.trim() && timeLogDate <= date) || (surrogateFound == false ))
        {  
           return
          
        }else{
              var selectedRows = table.rows( { selected: true } ).count();
              table.button( 1 ).enable( selectedRows > 0 );
        }
 
  });
  
  $('#timeLogTable_Vacation').on( 'page.dt', function () {
      table.buttons(1).disable();
    });

option with label linked

$
0
0

Hello, I have a particular database structure. With a translation of all the labels. So to display a select I have to go through 2 tables. How to display in the option label the translation which would be "profile_lib.translation"?

Editor::inst( $db, 'usr', 'id_usr' )
->fields(Field::inst( 'usr.id_usr')
->set(false)
,Field::inst( 'usr.name')
,Field::inst( 'usr.forname')
,Field::inst( 'usr.id_profile')
->options( Options::inst()
                ->table( 'profile' )
                ->value( 'id_profile' )
                ->label( 'id_translate' )
                   
            )
            ->validator( Validate::dbValues() )
,Field::inst( 'usr.activate')
->setFormatter( function ( $val, $data, $opts ) {
                        return ! $val ? 0 : 1;
                    } )

)                    
->leftJoin("profile","usr.id_profile=profile.id_profile","","")
->leftJoin("profile_lib", "translate_language.id_translate=profile.id_translate and translate_language.id_language= ".$_GET['langue'],"","")
->debug( true )
->process( $_POST )
->json();

struct : usr is linked to profile by id_profile and profile is linked to translate language by id_translate

Need to update old code about responsive

$
0
0

I need to update this function to work with newest Datatables version.
I don't know why it's no longuer work, any clue ?

function responsiveToggle(dt) {
            $(dt.table().header()).find('th').toggleClass('all');
            dt.responsive.rebuild();
            dt.responsive.recalc();
        }

SearchPanes Clear All Button

$
0
0

Description of problem:
I am using Search Panes and have the SP set to left side of table. When user resizes browser window, the button stays pretty large, so I was hoping to make it btn-xs since I am using Bootstrap 3 styling. I tried adding the class to the button after the fact but I am wondering if there is an initComplete on Search Panes like for the tables, because the selector appears to have no effect on the button. Or is there a better way to accomplish what I want to do? Thanks for the Search Panes, really love it.

Need a column that totals the data in each row

$
0
0

I've got a table with the following columns:

  • Checkbox (allows users to select a row)
  • Description
  • Budget
  • Invoice 1
  • Invoice 2
  • Invoice 3
  • Invoice 4
  • Invoice 5
  • Invoice Total

I need the Invoice Total column to be a total of Invoices 1 - 5.

I've got something working that creates a total row in the footer, but I see no documentation on how to make an additional column that totals like this.

Here's my JS

var editor; // use a global for the submit and return data rendering in the examples
 
$(document).ready(function() {
    // Get the table data
    var clientId = $("#clientId").val();    
    var myUrl = site_url + "costAnalysis/getAnalysis/" + clientId;
    $.ajax({
        url: myUrl
    }).done(function(data) {
        var tableData = JSON.parse(data);
        console.log(data);
        // Make the dataTables editor function
        editor = new $.fn.dataTable.Editor({
            data: tableData,
            table: "#example",
            idSrc:  'Trade_Class_ID',
            fields: [ {
                    label: "Description",
                    name: "Description",
                    type: "readonly"
                }, {
                    label: "Budget",
                    name: "Budget"
                }, {
                    label: "Invoice 1",
                    name: "Invoice1"
                }, {
                    label: "Invoice 2",
                    name: "Invoice2"
                }, {
                    label: "Invoice 3",
                    name: "Invoice3"
                }, {
                    label: "Invoice 4",
                    name: "Invoice4",                
                }, {
                    label: "Invoice 5",
                    name: "Invoice5"
                }, {
                    lable: "Invoice Total",
                    name: "InvoiceTotal",
                    type: "readonly"
                }, {
                    lable: "Trade Class ID",
                    name: "Trade_Class_ID",
                    type: "hidden"
                }
            ]
        });
        // When they change a cell, update the table
        editor.on( 'edit', function ( e, type ) {
            // Type is 'main', 'bubble' or 'inline'
            var payload = editor.get();
            payload.clientId = $("#clientId").val();            
            console.log(payload);
            $.ajax({
                url: site_url + "costAnalysis/updateRow",
                data: payload,
                type: "POST"
            });
        });
        // Create the dataTable
        var table = $('#example').DataTable( {
            dom: "Bfrtip",
            data: tableData,
            columns: [
                {
                    data: null,
                    defaultContent: '',
                    className: 'select-checkbox',
                    orderable: false
                },
                { data: "Description" },
                { data: "Budget",   render: $.fn.dataTable.render.number( ',', '.', 0, '$' ) },
                { data: "Invoice1", render: $.fn.dataTable.render.number( ',', '.', 0, '$' ) },
                { data: "Invoice2", render: $.fn.dataTable.render.number( ',', '.', 0, '$' ) },
                { data: "Invoice3", render: $.fn.dataTable.render.number( ',', '.', 0, '$' ) },
                { data: "Invoice4", render: $.fn.dataTable.render.number( ',', '.', 0, '$' ) },
                { data: "Invoice5", render: $.fn.dataTable.render.number( ',', '.', 0, '$' ) },
                { data: "InvoiceTotal", render: $.fn.dataTable.render.number( ',', '.', 0, '$' ) }
            ],
            columnDefs: [
                {
                    targets: [2, 3, 4, 5, 6, 7, 8],
                    className:'dt-body-right'
                }
            ],
            keys: {
                columns: ':not(:first-child)',
                editor:  editor
            },
            select: {
                style:    'os',
                selector: 'td:first-child',
                blurable: true
            },
            buttons: [
                { extend: "edit",   editor: editor }
            ], 
            // Totals for footer
            "footerCallback": function ( row, data, start, end, display ) {
                var api = this.api(), data;
     
                // Remove the formatting to get integer data for summation
                var intVal = function ( i ) {
                    return typeof i === 'string' ?
                        i.replace(/[\$,]/g, '')*1 :
                        typeof i === 'number' ?
                            i : 0;
                };
     
                // Budget total
                budgetTotal = api
                    .column( 2 )
                    .data()
                    .reduce( function (a, b) {
                        return intVal(a) + intVal(b);
                    }, 0 );
     
                // Update footer
                $( api.column( 2 ).footer() ).html(
                    '$'+budgetTotal
                );

                // Invoice total
                invoiceTotal = api
                    .column( 8 )
                    .data()
                    .reduce( function (a, b) {
                        return intVal(a) + intVal(b);
                    }, 0 );
     
                // Update footer
                $( api.column( 8 ).footer() ).html(
                    '$'+invoiceTotal
                );
            }            
        } );        
    });

} );

Here's the HTML

<!-- Content -->
<div id="main" class="extraPadding">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
            <input type="hidden" id="clientId" value="<?=$Client_ID?>">            
                <h4>Cost Analysis for...</h4>
                <table id="example" class="display" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th></th>
                            <th class="text-left">Description</th>
                            <th class="text-right">Budget</th>
                            <th class="text-right">Invoice 1</th>
                            <th class="text-right">Invoice 2</th>
                            <th class="text-right">Invoice 3</th>
                            <th class="text-right">Invoice 4</th>
                            <th class="text-right">Invoice 5</th>
                            <th class="text-right">Invoice Total</th>
                        </tr>
                    </thead>
                    <tfoot>
                        <tr>
                            <th colspan="2" class="text-right"></th>
                            <th class="text-right"></th>
                            <th class="text-right"></th>
                            <th class="text-right"></th>
                            <th class="text-right"></th>  
                            <th class="text-right"></th>  
                            <th class="text-right"></th>   
                            <th class="text-right"></th>                                                    
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
</div>

Explode data in ssp and search foreign key

$
0
0

Hi,
How can i explode data in ssp. I have save my data in database with ',' and these data is a foreign key.
And search is not working for foreign key. Ex: foreign key is 526, and its value is "PHP" so i want to search 'PHP'.
I have a lots of foreign key row and i want to search with actual value.

Sorry for my English.

$columns = array(
    array( 'db' => 'r_id', 'dt' => 0 ),    
    array(
        'db'        => 'receiving_date',
        'dt'        => 1,
        'formatter' => function( $d, $row ) {            
            return date( 'd-m-Y', strtotime($d));
        }
    ),    
    array(
        'db'        => 'invoice_no',
        'dt'        => 2,
        'formatter' => function( $d, $row ) {              
            return return_invoice_no($d);
        }
    ),  
    array( 'db' => 'job_no',   'dt' => 3 ),    
    array(
        'db'        => 'client',
        'dt'        => 4,
        'formatter' => function( $d, $row ) {
            return return_clients_name($d);
        }
    ),

    // Java script

    $(document).ready(function(){
      var dataTable = $('#dataTable').DataTable({               
          "bProcessing": true,
          "bServerSide": true, 
          "order": [[0, 'desc']],           
          "ajax":{
              url:"server_side/fetch_payment_receiving.php",
              type:"post"
          },
          "fnRowCallback" : function(nRow, aData, iDisplayIndex){
              $("td:first", nRow).html(iDisplayIndex +1);
             return nRow;
          }

      });

  });

Database image

Is there a way to get all the data from an object? (symfony)

$
0
0

Hi,

I am using the Symfony DataTable Bundle from Omines to generate my datatable. So I generate my columns using this bundle, and my datatable is based on my Event entity.

Is it possible to recover all the data of this entity? Not just the data from the generated columns?

Thank you.

Read only Distinct Values from serverside

$
0
0

I want to only display distinct values in my table(two columns) on client side. :

The data that gets displayed atm looks like this:

# Column1 Column2
Car 1oct '19 - 30sep '20
Car 1oct '19 - 30sep '20
Car 1oct '19 - 30sep '20
Bus 1Nov'19 - 31Oct'20
Bus 1Nov'19 - 31Oct'20
Bus 1Nov'19 - 31Oct'20

Is it possible to display only distinct values, so my table looks like this?

Car 1oct '19 - 30sep '20
Bus 1Nov'19 - 31Oct'20

Is this achievable without using RAW SQL query and select distinct values?

Thank you

Way to sort by row color?

$
0
0

Cannot link to a test case, the code is all contained on an intranet application and I am confused on getting it to work.

The general idea of the page:
User has a CSV file of serial numbers, make, model, etc
*The page has the user select a CSV file from their system
*A client side datatable is generated from the csv file
*User clicks submit to submit to the database
---
First checks if the client side table has duplicate serial numbers
---* Second if first passes, checks against database for duplicate serial numbers
---* Highlights the duplicate serial numbers and alerts user to fix

My question is, how would you go about doing the above? The client side duplicate check is easy. The server side duplicate check, I return an array of serial numbers that are already in the database. What to do with this array, I am stuck on. My hope would be to 'sort' the client side table to have the 'matches' at the top and highlight the offending rows. My hope would be to not have to make another column in the template csv file that is sorted by but that might be my only option.

footerCallback on a of a child table

$
0
0

Good afternoon,
I have a child table built from a function:

function createChild ( row ) {
var table = $('<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tfoot>'+
'<tr>'+
'<th colspan="4" style="text-align:right">'+
'Suma:'+
'</th>'+
'</tr>'+
'</tfoot>'+        
'</table>');
 
 row.child( table ).show();
...

The fields are mounted from the columns:

        columns: [
            { title: 'Tipo', data: 'tb_objeto.objeto' },
            { title: 'Item', data: 'tb_item.item' }
    …

To fill the Sum of the <tfoot> I use a "footerCallback": function
The question is: How can I pass the data from the footerCallback to the <tfoot>
Thank you.

Add SearchPanes filter count to custom button?

$
0
0

Hi,

I've added a button to collapse the .searchPanes div without collapsing the whole SearchPanes container (which is why I'm avoiding the default searchPanes button). However, I would like to add the functionality of the active filter count in the button text (e.g. "Advanced Filters (2 Active)" ). Is there a way to use the searchPane button language options on my custom button, or do I need a special function update the button text? I'm not sure how to approach this.

I would also like to remove the default title div from SearchPanes. I'm currently hiding it in css, but if there's a way to eliminate it entirely in the searchPane options, that would be preferable.

http://live.datatables.net/jigixuqe/1/edit

Thanks!

Issues with Ajax array of objects

$
0
0

Link to test case: http://dkoy.org/ql/index.html?guild=active%20players&server=GLOBAL
Debugger code (-): https://debug.datatables.net/ojuwuc
Error messages shown: DataTables warning: table id=example - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
Description of problem:
I am fairly new to js and JSON and have been smashing my face against this trial-and-error style for 2 nights and it's time to concede and ask for assistance. I feel like my raw JSON is formatted similarly to the example on https://datatables.net/examples/ajax/objects. The correct number of rows are being returned but I am receiving the above error. I am able to log the returned json to the console and access individual attributes using:

table.on( 'xhr', function () {
        var json = table.ajax.json();
        console.log(json);
        console.log(json.heroPlans[0].id);
        alert( json.heroPlans.length +' row(s) were loaded' );
    } );

Here is the js

  var table = $('#example').DataTable({

        "ajax": {
            "url": "js/guild_plan.json" + "?server=" + server + "&guild=" + guild,
            "dataSrc": "heroPlans",
        },
        columns: [
            {"heroPlans": "id"},
            {"heroPlans": "name"},
            {"heroPlans": "heroPower"},
            {"heroPlans": "health"},
            {"heroPlans": "battleEventMulti"},
            {"heroPlans": "row1Bonus"},
            {"heroPlans": "row2Bonus"},
            {"heroPlans": "row3Bonus"},
            {"heroPlans": "row4Bonus"}            
        ],
        paging: false,
    });

Here is a sample of the JSON

{
    "guildId": 52073,
    "name": "ACTIVE PLAYERS",
    "heroPlans": [{
        "id": 1876241,
        "name": "SIRSARGE",
        "heroPower": 3940131,
        "health": 1073890,
        "attack": 1276726,
        "defense": 762637,
        "magic": 826878,
        "battleEventMulti": 0.0,
        "row1Bonus": null,
        "row2Bonus": null,
        "row3Bonus": null,
        "row4Bonus": null
    }, {
        "id": 2073569,
        "name": "ODDPANDA",
        "heroPower": 3138061,
        "health": 856366,
        "attack": 979995,
        "defense": 614617,
        "magic": 687083,
        "battleEventMulti": 0.0,
        "row1Bonus": null,
        "row2Bonus": null,
        "row3Bonus": null,
        "row4Bonus": null
    }
    ...
}

Thanks much in advance


Can not trigger column(s) visibility.

$
0
0

Fairly new to all of this so patience and help appreciated.

I have a table working, as well as this code here:

$('#leadTable').on( 'length.dt', function ( e, settings, len ) {setTimeout(bindME,2000);});

$('#leadTable').on( 'page.dt', function () {setTimeout(bindME,1000);});

What I am wanting to do is a create an event that upon clicking an element, hide columns 6,7,8,9 in my table.

I tried the example code on this page - https://datatables.net/examples/api/show_hide.html

But I seem to get nowhere. I have a variable for my table called "tommy" -

`

var tommy = $("#callsTable").dataTable({
    searchPane: {
        columns: [':contains("Market")'], threshold: 0
    },
    "order": [],
    "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
    "columnDefs": [
        { "visible": false, "targets": 9, "searchable": true, "orderable": true },
        { "visible": false, "targets": 10, "searchable": true, "orderable": true },
        { "visible": false, "targets": 11, "searchable": true, "orderable": true },     
        { "visible": false, "targets": 12, "searchable": false, "orderable": false }

        //{ "visible": false, "targets": 15 },
        // { "visible": true, "targets": 0, "searchable": true }
    ],
    "language": {
        "lengthMenu": "_MENU_ Rows",
        "searchPlaceholder": "Search Client Leads",
        "info": "Rows _START_ to _END_ of _TOTAL_"
    },
    "oLanguage": {
        "sSearch": "<i class='fal fa-search fa-1ax'></i>"
    },
    //colReorder: true,
    dom: "<'#cLeads.row be-datatable-header'lfBi>" +
        "<'row be-datatable-body'<'col-sm-12'tr>>" +
        "<'row be-datatable-footer'<'col-sm-12'p>>",
    buttons: [
        { extend: 'colvis', text: 'Columns' },
        {
            extend: 'collection',
            text: 'Export',
            buttons: [
                'excel',
                'csv',
                'pdf',
                'print'
            ]
        }

    ]
});

`
But this code gets me nowhere

$('a.toggle-vis').on( 'click', function (e) {
e.preventDefault();

    // Get the column API object
    var column = tommy.column( $(this).attr('data-column') );

    // Toggle the visibility
    column.visible( ! column.visible() );
} );

How to disable/enable buttons when no row is selected in checkbox selection?

$
0
0

Hello,

I've created this Submit button outside of my datatable and am having trouble on how to enable/disable the button when no row is selected. The Submit button is disabled at initial load but when the user selects any rows, the button should be enabled.

$("#submit").prop('disabled', true);
var myTable = $('#mytable').DataTable({
                  'data': result,
                  'paging': false,
                  'searching': false,
                  'columns': [
                     {
                        'data': 'ID',
                        'checkboxes': true
                     },
                     { 'data': 'PRODUCT_CATEGORY' },
                     { 'data': 'PRODUCT_NAME' },
                     { 'data': 'PRODUCT_DETAILS' }
                  ],
                  'select':{
                        'style':'multi'
                    },
                  'order': [[1, 'asc']],
                });

I found few solutions but they are mostly related to button API with select extension which I don't use in this case. If button API supports what I try to do here, can I get examples on how to do that with checkbox selection?

New Button not working

$
0
0

Link to test case:
https://aquaone.cloud/cloud/ocapp/staff_newyork2.html
Debugger code (debug.datatables.net):
Error messages shown:

Description of problem:
I have a very simple integration of Editor running on a test server. It's using the staff_newyork table from examples. The Edit and Delete buttons work fine and update correctly in the Database and browser but for some reason, the New and Duplicate buttons won't work. The popup form appears with the correct fields however when submitted nothing happens. With Duplicate, the fields are all populated correctly but once again when submitted nothing happens. No error message is recorded in console or PHP error log. Any help would be appreciated, thanks.

There is a samesite cookie warning given as follows:

Indicate whether to send a cookie in a cross-site request by specifying its SameSite attribute
Because a cookie's SameSite attribute was not set or is invalid, it defaults to SameSite=Lax, which prevents the cookie from being sent in a cross-site request. This behavior protects user data from accidentally leaking to third parties and cross-site request forgery.

Resolve this issue by updating the attributes of the cookie:
Specify SameSite=None and Secure if the cookie should be sent in cross-site requests. This enables third-party use.
Specify SameSite=Strict or SameSite=Lax if the cookie should not be sent in cross-site requests

3 cookies
Name    Domain & Path
PHPSESSID   .datatables.net/
Vanilla .datatables.net/
Vanilla-tk  .datatables.net/
Learn more: SameSite cookies explained

This is the staff_newyor2.html code:

        <!doctype html>
        <html>
            <head>
                <meta http-equiv="content-type" content="text/html; charset=utf-8" />

                <title>DataTables Editor - staff_newyork</title>
                <script
                        src="https://code.jquery.com/jquery-3.5.1.js"
                        integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
                        crossorigin="anonymous"></script>



                <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/moment-2.18.1/jszip-2.5.0/pdfmake-0.1.36/dt-1.10.21/af-2.3.5/b-1.6.3/b-colvis-1.6.3/b-html5-1.6.3/b-print-1.6.3/cr-1.5.2/fc-3.3.1/fh-3.1.7/kt-2.5.2/r-2.2.5/rg-1.1.2/rr-1.2.7/sc-2.0.2/sp-1.1.1/sl-1.3.1/datatables.min.css">
                <link rel="stylesheet" type="text/css" href="css/generator-base.css">
                <link rel="stylesheet" type="text/css" href="css/editor.dataTables.min.css">

                <script type="text/javascript" charset="utf-8" src="https://cdn.datatables.net/v/dt/moment-2.18.1/jszip-2.5.0/pdfmake-0.1.36/dt-1.10.21/af-2.3.5/b-1.6.3/b-colvis-1.6.3/b-html5-1.6.3/b-print-1.6.3/cr-1.5.2/fc-3.3.1/fh-3.1.7/kt-2.5.2/r-2.2.5/rg-1.1.2/rr-1.2.7/sc-2.0.2/sp-1.1.1/sl-1.3.1/datatables.min.js"></script>
                <script type="text/javascript" charset="utf-8" src="js/dataTables.editor.min.js"></script>


                <link rel="stylesheet" type="text/css" href="css/editor.dataTables.min.css">

                <script type="text/javascript" charset="utf-8" src="js/table.staff_newyork.js"></script>
            </head>
            <body class="jqueryui">
                <div class="container">

                    <h1>
                        DataTables Editor <span>staff_newyork</span>
                    </h1>

                    <table cellpadding="0" cellspacing="0" border="0" class="display" id="staff_newyork" width="100%">
                        <thead>
                            <tr>
                                <th>first_name</th>
                                <th>last_name</th>
                                <th>phone</th>
                                <th>city</th>
                            </tr>
                        </thead>
                    </table>

                </div>
            </body>
        </html>

table.staff_newyork.js is the only other file I have modified. modified to use Duplicate button.

    /*
     * Editor client script for DB table staff_newyork
     * Created by http://editor.datatables.net/generator
     */

        (function($){

        $(document).ready(function() {
            var editor = new $.fn.dataTable.Editor( {
                ajax: 'php/table.staff_newyork.php',
                table: '#staff_newyork',
                fields: [
                    {
                        "label": "first_name:",
                        "name": "first_name"
                    },
                    {
                        "label": "last_name:",
                        "name": "last_name"
                    },
                    {
                        "label": "phone:",
                        "name": "phone"
                    },
                    {
                        "label": "city:",
                        "name": "city"
                    }
                ]
            } );

            var table = $('#staff_newyork').DataTable( {
                dom: 'Bfrtip',
                ajax: 'php/table.staff_newyork.php',
                columns: [
                    {
                        "data": "first_name"
                    },
                    {
                        "data": "last_name"
                    },
                    {
                        "data": "phone"
                    },
                    {
                        "data": "city"
                    }
                ],
                select: true,
                lengthChange: false,
                buttons: [
                    { extend: "create", editor: editor },
                    { extend: "edit",   editor: editor },
                    {
                        extend: "selected",
                        text: 'Duplicate',
                        action: function ( e, dt, node, config ) {
                            // Start in edit mode, and then change to create
                            editor
                                .edit( table.rows( {selected: true} ).indexes(), {
                                    title: 'Duplicate record',
                                    buttons: 'Create from existing'
                                } )
                                .mode( 'create' );
                        }
                    },
                    { extend: "remove", editor: editor }
                ]
            } );
        } );

        }(jQuery));

wat does datatables net 7 mean

$
0
0

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem:

Symfony 5 Search on a DateTimeColumn datatables

$
0
0

Hello,

I've been looking for a way to filter my "start" and "end" fields from my datatable for hours now. These are two DateTimeColumn type fields.

I am using the Symfony DataTables Bundle.

I understood apparently that we cannot filter on a DateTimeColumn because the returned data is of type DateTime Object, so I cannot compare a string and an object.

So, how to do ?

Can't we make sure to convert my DateTime objects to be able to do the filtering?

Or transform the value typed in the search field into DateTime?

Thanks for your help.

Here is a screen:

My code (PHP) :

->createAdapter(ORMAdapter::class, [
    'entity' => Event::class,
    'query' => function (QueryBuilder $builder) use ($eventStatus) {
        $builder
            ->select('e')    
            ->addSelect('ca')
            ->addSelect('ci')
            ->addSelect('u')  
            ->from(Event::class, 'e')
            ->join('e.category', 'ca')
            ->join('e.city', 'ci')
            ->join('e.user', 'u')
            ->andWhere('e.status = :status')
            ->setParameter('status', $eventStatus)
            ->orderBy('e.id', 'DESC')
        ;
    },
])

startDate column:

->add('startDate', DateTimeColumn::class, ['label' => 'Début', 'field' => 'e.startDate', 'format' => 'd/m/Y',  'render' => function($value, $context) {
    return sprintf(
        '%s<br>
        %s',
        $context->getStartDate()->format('d/m/Y'),
        $context->getStartAt()->format('H\hi'),
    );
}])

(JS) :

$('#events').initDataTables({{ datatable_settings(datatable) }}, { 
    // processing: true,
    // serverSide: true,
    searching: true, 
    ordering: false,
    searchDelay: 200,
    dom: 'Bfrtip',
    buttons: [
        {
            text: 'Réinitialiser',
            action: function (e, dt, node, config) {
                location.reload();
            }
        },
        {
            extend: 'columnsToggle',
            columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        }
    ],
    initComplete: function(settings, json) {
        var api = this.api();

        // Get number of total records
        var recordsTotal = api.context[0].fnRecordsTotal();
        $('#events_list h5 span').text(recordsTotal);

        // Hide some columns
        api.columns([4,9]).visible(false);

        // Create tr filter
        var tr = $('<tr id="filter_search"></tr>');
        // Count number of cells in a row
        var nbCells = document.getElementById('dt').rows[0].cells.length;
        // Generate cells to #filter_search row 
        for (var i = 0; i < nbCells; i++) {
            if (i == 1 || i == 8 || i == 11) {
                tr.append('<th></th>');
            } else {
                tr.append('<th><input type="search" onclick="stopPropagation(event);" placeholder="Rechercher"></th>');
            }
        }

        var firstHeaderRow = $('tr', api.table().header());
        tr.insertAfter(firstHeaderRow);

        $("#filter_search th").eq(5).find('input').datepicker({
            autoclose: true,
            todayHighlight: true,
            language: "fr",
            dateFormat: "dd/mm/yy",
        });

        $("#filter_search input").on('keyup change', function(e) {
            if (e.keyCode == 13) {
                api
                    .column($(this).parent().index()+':visible')
                    .search(this.value)
                    .draw();
            }
        });

        $('.buttons-columnVisibility').each(function(index, element) {
            $(element).click(function() {
                if (api.column(index).visible() === true) {
                    $('#filter_search th').eq(index).show();
                } else {
                    $('#filter_search th').eq(index).hide();
                }
            });
        });
    },
});

Thank you.

Viewing all 82258 articles
Browse latest View live