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

Complex header export to CSV


Client-side validation example improvement

$
0
0

In JS code in example i suggest to improve line 34

var firstName = editor.field( 'first_name' );

to

var firstName = this.field( 'first_name' );

because later in example on line 51 you are using this

if ( this.inError() ) {
    return false;
}

When editor.disable() Hide label of field

$
0
0

Hi,
I'm new in Editor but no in DataTables. I'm traying to disable a couple of fields, but I want to show the values.

When: editor.disable( ['idctrlaction','namecontrolator'] );

The field name is hided, not class hidden, the value is in label. Can be trouble with css, because if directly I delete "disabled" over de navegator's debugger it shows. In the images sended it can to see that

Same solution?

Thanks
Josep

The responsive feature won't work if the data table is hidden when declare

$
0
0

My data table is initially in a hidden div. The responsive is not working.
The code is like that:

//The class "tab" is declared with "display:none"
<div class="tab">
   <table id="pending-table" class="table table-condensed table-striped">
      <thead>
         <tr>
           <th class="cell-id">ID</th>
           <th class="cell-date">Date</th>
           <th class="cell-customer">Customer</th>
           <th class="cell-sales">Sales</th>
           <th class="cell-qty">Qty</th>
           <th class="cell-amount">amount</th>
        </tr>
      </thead>
   </table>
</div>

but If I put the div be visible when the page load initially, the data table can be responsive.

Now I add a class "active" to declare the div with display:block and cancel it after 1 second like that.

  setTimeout(
    function(){$('.view-person').removeClass('active');
    },1000);

I would like to know any better solution for solve this. Thanks.

Column groups toggle button?

How to sort datatable by making multiple requests?

$
0
0

Hi all

Below is my script . I am getting multiple JSON responses from differernts server in a loop in jquery and each time I am adding the result in data taable but while sorting I am able to see only the first response sorted in a datatble. I want to auto sort the complete table after appending all the responses in a datatable. Is there any way to do so?

Right now, i have to refresh the page once otr twice or multiple times to see all the responses sorted together.

Below is my script where in a loop m getting multile JSOn responses. Please help :)

$(document).ready(function(){ alert('Hello'); var url=""; var port="33500"; $.getJSON('http://msplwa107:33500/rest/MdtAny_MondayMonitor/services/consumer/_get HTTP/1.1',function(data){ $.each(data.allServers, function(i,a) { url="http://"+a+":"+port+"/rest/MdtAny_MondayMonitor/services/Consumer_schedulers/_get HTTP/1.1"; //url="http://localhost:5555/rest/MdtAny_MondayMonitor/services/Consumer_adapters/_get HTTP/1.1"; $.getJSON(url, function(data) { //console.log(data); var row = $("") $("#person").append(row); $.each(data.final_schedulers, function(i,a) { if(a.status=="NOT_OK") { var row = $("") $("#person").append(row); //this will append tr element to table... keep its reference for a while since we will add cels into it row.append($("" +""+ a.name + "")); row.append($("" + a.exec_state + "")); row.append($("" + a.status + "")); row.append($("" + a.server + "")); } else{ var row = $("") $("#person").append(row); //this will append tr element to table... keep its reference for a while since we will add cels into it row.append($("" + a.name + "")); row.append($("" + a.exec_state + "")); row.append($("" + a.status + "")); row.append($("" + a.server + "")); } }); $("#person").dataTable().fnDestroy(); $(document).ready(function() { $('#person').DataTable( { "order": [[ 0, "asc" ]], bRetrieve: true } ); }); }); }); }) });

SCRIPT5007: Unable to get value of the property 'style': object is null or undefined (on destroy)

$
0
0

I'm using jQuery DataTables 1.10.7

On table destroy, I'm getting the following error.
SCRIPT5007: Unable to get value of the property 'style': object is null or undefined

The root cause is, at the method _fnCalculateColumnWidths (oSettings), the below lines are causing the issue. The headerCells are having lesser elements than visibleColumns. In my case, the visibleColumns are having array of 8 elements, where as the headerCells are having only 5 elements.

My data grid is having 2 hidden columns, but those columns are also retrieved in visibleColumns while destroying, but the headerCells are only having the actual visible columns. That is causing this issue below, please suggest what is the solution.

                    visibleColumns = _fnGetColumns( oSettings, 'bVisible' )
        // Apply custom sizing to the cloned header
        headerCells = _fnGetUniqueThs( oSettings, tmpTable.find('thead')[0] );

        for ( i=0 ; i<visibleColumns.length ; i++ ) {
            column = columns[ visibleColumns[i] ];
            headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !== '' ?
                _fnStringToCss( column.sWidthOrig ) :
                '';
        }

How to store scroller position when use ajax.reload()

$
0
0

Hello all,
I use the last DataTables 1.10.12 and Scroller 1.2.0 , when I use ajax.reload() refresh data, the scroll bar position will move to the top of table . How can I move the scroll bar to the exact row after reload data.

Thanks,
August


Editor - Keyboard Nav Inline edit

$
0
0

I am unable to use arrow keys while editing a cell. The arrows key event causes the control to go out of edit mode and navigates.
Is this a limitation, if so please provide a solution.

Is there a way to Export All while using server side processing?

$
0
0

I am using server side processing for my tables. I have tables that have 60000+ rows with 65+ columns, so using client side is not an option for me. My end users want to pull up the tables and then use the filtering and sorting to narrow down what they are seeing. Then they want to Export All, usually still 30k - 40k rows with the 65+ columns and with the sorting in place too. I have tried a few things that I've found elsewhere and am hoping that you can help. Here's what I've tried so far:

{ extend: 'excel',
    text: 'Export Current Page',
    exportOptions: {
        modifier: {
            page: 'current'
        }
    },
    customize: function (xlsx)
    {
        var sheet = xlsx.xl.worksheets['sheet1.xml'];
        $('row:first c', sheet).attr('s', '7');
    }
}

This does not do what I would like. It exports only the current page (which is why I made the text for it 'Export Current Page')

I've also tried this:

{
    text: 'Export All to Excel',
    action: function (e, dt, button, config)
    {
        dt.one('preXhr', function (e, s, data)
        {
            data.length = -1;
        }).one('draw', function (e, settings, json, xhr)
        {
            var excelButtonConfig = $.fn.DataTable.ext.buttons.excelHtml5;
            var addOptions = { exportOptions: { 'columns': ':all'} };

            $.extend(true, excelButtonConfig, addOptions);
            excelButtonConfig.action(e, dt, button, excelButtonConfig);
        }).draw();
    }
}

This simply sends the whole table to the screen instead of sending it to an excel file. Though it does pull the whole data set.

I'm sure that through the two of these I'm missing something that would allow me to Export the whole data set without sending it to the screen first.

Data Table xls not export in safari

$
0
0

Hello,

I have implemented the data data-tables buttons csv and xls & I am passing additional parameters as additional row at top of my header and for safari its ot comming in safari but for the chrome and firefox additional rows comming properly.

Also I am triggering the xls and csv button by the jquery trigger function. For some reason csv working fine but not XLS.

Please provide me some pointers.

Nested readonly `leftJoin` in `Join`

$
0
0

Just like a lot of others, I had the need of a leftJoin on a joined table. It turns out this is quite easy to do when both the joined table and the nested leftjoined table are readonly.

Implementation

All we have to do is copy the relevant leftJoin code form Editor.php to Join.php:
- the _leftJoin[] array
- the leftJoin($table, $field1, $operator, $field2) function to add a left join
- the private _perform_left_join($query) function
- Now, we need to append the join to the query statement in the public data function. The way to do this is to put

$this->_perform_left_join(stmt);
  just before the call to `$res = $stmt->exec();`.

Usage

Now you can do something like

$editor = Editor::inst( $db, 'A', 'A.id')
$editor->Join(
    MJoin('B')
    ->link('B.id', 'A.b_id')
    ->leftJoin('C', 'C.id', '=', 'B.c_id')
    ->fields(
           Field::inst('B.id')->set(Field::SET_NONE),
           Field::inst('C.some_nice_property')->set(Field::SET_NONE)
     )
     ->set(Field::SET_NONE)
);

Make sure that you use an alias for C if C is also leftjoined to A directly.

@allan, this might be a nice feature for future Editor versions as well, because I think this is quite useful, even without support for editing them.

how to set dynamically searchable to true or false in columndefs

$
0
0

i was trying dynamically set "searchable" to true to a specific column inside a custom filter function.

Will the below line work ?

table.column('columnIndex').searchable(true);

please advise how to set to ture dynamically based on some condition. or any other idea , please guide me. am stuck here.

Thanks in advance.

row toggle plug in

$
0
0

Hello,

I am completely new to this forum and to developing plug-ins, so please go easy on me.

I have followed the 'Sliding child rows' tutorial here and have used this functionality in my own web pages. But it occurred to me that I could create a plug-in to do some of the work for me.

Below is what I have come up with so far. Before I go any further with it (if indeed I do, depending on feedback), I though I'd open it up to the forum for discussion.

(function($) {
    var ToggleRow = function ( dt ) {
        this.toggle = function( dtRow ) {
            // if row already showing, close it.
            if (dtRow.child.isShown()) {
                this.closeRow( dtRow );
            }
            else {
                showRowData( dtRow );
            }
        };
        // code borrowed from the resource at: https://datatables.net/blog/2014-10-02
        this.closeRow = function ( dtRow ) {
            var showingRow = $(dtRow.node());

            $('div.slider', dtRow.child()).slideUp(function () {
                dtRow.child.remove();
                showingRow.removeClass('shown');

                $(dt.table().node()).trigger('rowClosed', [dtRow]);
            });
        };
        var showRow = this.showRow = function ( dtRow, data ) {
            var selectedRow = $(dtRow.node());
            dtRow.child(data).show();

            $('div.slider', dtRow.child()).slideDown(function () {
                selectedRow.addClass('shown');

                $(dt.table().node()).trigger('rowShown', [dtRow]);
            });
        };
        // relies on data attributes being present for the row being toggled
        var showRowData = function ( dtRow ) {
            var row = $(dtRow.node());
            var requestType = row.data('request-type') || "GET";
            var requestUrl = row.data('request-url');
            var requestData = row.data('request-data') || null;
            var contentType = row.data('content-type') || "application/json; charset=utf-8";
            var dataType = row.data('data-type') || "json";
            var callback = row.data('callback');
            $.ajax({
                type: requestType,
                url: requestUrl,
                data: requestData,
                contentType: contentType,
                dataType: dataType,
                success: function ( response ) {
                    var data = response;
                    if (callback) {
                        var fn = window[callback];
                        if (fn) data = fn(response);
                    }
                    showRow( dtRow, data );
                },
                error: function (response) { showRow( dtRow, response ); }
            });
        };
    };

    $.fn.dataTable.ToggleRow = ToggleRow;
    $.fn.DataTable.ToggleRow = ToggleRow;
}(jQuery));

Thanks in advance to anyone who cares to comment on this endeavour

Currency column automatically rounding to the nearest dollar

$
0
0

I have been searching for a while now and can't find where to fix this. I have 2 columns in editor that hold currency but every time I enter a dollar amount with decimals it rounds to the full dollar. I need it to do that at the penny level or not at all. I am sure it is just a setting somewhere but can't find it. Can someone please point me in the right direction. Thanks.


List New Improvements

$
0
0

Hello,

Is there a list of future improvements?

I would like to know among other things when implementing the group by, or the real-time search on the server use php

Thank you

PD: My English is disastrous

DataTable Pipeline Failed to load resource: the server responded with a status of 400 (Bad Request)

$
0
0

Please find below the jquery functions that I have customized for my requirement ,

$.fn.dataTable.pipeline = function ( opts ) {
// Configuration options

var conf = $.extend( {
    pages:10,
    //pages: 10,     // number of pages to cache
    url: '',      // script url
    data: null,   // function or object with parameters to send to the server
                  // matching how `ajax.data` works in DataTables
    method: 'POST' // Ajax HTTP method

}, opts );

console.log(conf.data);

// Private variables for storing the cache
var cacheLower = -1;
var cacheUpper = null;
var cacheLastRequest = null;
var cacheLastJson = null;

return function ( request, drawCallback, settings ) {

    console.log(request);
    var ajax          = false;
    var requestStart  = request.start;
    var drawStart     = request.start;
    var requestLength = request.length;
    var requestEnd    = requestStart + requestLength;

    if ( settings.clearCache ) {
        // API requested that the cache be cleared
        alert("ajax true first");
        ajax = true;
        settings.clearCache = false;
    }
    else if ( cacheLower < 0 || requestStart < cacheLower || requestEnd > cacheUpper ) {
        // outside cached data - need to make a request
        ajax = true;
        alert("ajax true seccond");
    }
    else if ( JSON.stringify( request.order )   !== JSON.stringify( cacheLastRequest.order ) ||
              JSON.stringify( request.columns ) !== JSON.stringify( cacheLastRequest.columns ) ||
              JSON.stringify( request.search )  !== JSON.stringify( cacheLastRequest.search )
    ) {
        // properties changed (ordering, columns, searching)
        alert("ajax true third");
        ajax = true;
    }

    // Store the request for checking next time around
    cacheLastRequest = $.extend( true, {}, request );

    if ( ajax ) {
        // Need data from the server
        if ( requestStart < cacheLower ) {
            requestStart = requestStart - (requestLength*(conf.pages-1));

            if ( requestStart < 0 ) {
                requestStart = 0;
            }
        }

        cacheLower = requestStart;
        cacheUpper = requestStart + (requestLength * conf.pages);

        request.start = requestStart;
        request.length = requestLength*conf.pages;

        // Provide the same `data` options as DataTables.

        console.log(conf.data);
        if ( $.isFunction ( conf.data ) ) {
            // As a function it is executed with the data object as an arg
            // for manipulation. If an object is returned, it is used as the
            // data object to submit
            alert("first condition");
            var d = conf.data( request );
            if ( d ) {
                $.extend( request, d );
            }
        }
        else if ( $.isPlainObject( conf.data ) ) {
            alert("second condition");
            // As an object, the data given extends the default
            $.extend( request, conf.data );
        }

                settings.jqXHR = $.ajax( {
                    "type":     conf.method,
                    "url":      conf.url+'?'+$.param(request),
                    "data":     JSON.stringify(conf.data),
                    "processData": false,
                     "contentType" : "application/json",
                    /* "dataType": "json", */
                    "cache":    false,
                    "success":  function ( json ) {

                cacheLastJson = $.extend(true, {}, json);

                if ( cacheLower != drawStart ) {
                    json.data.splice( 0, drawStart-cacheLower );
                }
                if ( requestLength >= -1 ) {
                    json.data.splice( requestLength, json.data.length );
                }

                drawCallback( json );
            }
        } );
    }
    else {
        json = $.extend( true, {}, cacheLastJson );
        json.draw = request.draw; // Update the echo for each response
        json.data.splice( 0, requestStart-cacheLower );
        json.data.splice( requestLength, json.data.length );

        drawCallback(json);
    }
}

};

// Register an API method that will empty the pipelined data, forcing an Ajax
// fetch on the next draw (i.e. table.clearPipeline().draw())
$.fn.dataTable.Api.register( 'clearPipeline()', function () {
return this.iterator( 'table', function ( settings ) {
settings.clearCache = true;
} );
} );

javascript code for DataTable Initialization ,

str='{"tableName":"table_name","fromDate":"'+frmDateDrillDown+'","toDate":"'+toDateDrillDown+'","draw":"0","start":"0"}';

$('#popupGridTableRaw').DataTable( {
"processing": true,
"serverSide": true,
"bLengthChange": false,
"pageLength": 100,
"searching": false,
"ordering": false,
columns : [ {
"data" : "arafImsi"
},
{
"data" : "arafMsisdn"
},
{
"data" : "arafIccid"
},
{
"data" : "arafSubStatus"
},
{
"data" : "arafSubStsRsnCd"
},
{
"data" : "arafSubType"
},
{
"data" : "arafMarket"
},
{
"data" : "arafSubmkt"
},
{
"data" : "arafFilterInd"
},
{
"data" : "arafDuplicateInd"
},
{
"data" : "arafTimestamp"
},

    ],
    "ajax": $.fn.dataTable.pipeline( {

         type:"POST",
        url:"${hostConfig.applicationUrl}/rawDataBucket",
        data:str,

         dataType: "json",
        async: true,
        crossDomain: true,
        pages: 10 // number of pages to cache
    } )
} );

Kindly help me in resolving this issue. Thanks in advance.

Extending one-to-many join with another table in the middle

$
0
0

I'm trying to extend the one-to-many join example and manual page to match my database structure. I have an intermediate table in order to provide an inheritance mechanism to the database. I have a main 'tasks' table (similar to 'users' in the example), a 'task_application_types' table (similar to the 'user_permission' table), and an 'application_types' table (like the 'permission' table).

Below is a representation of a portion of my database from MySQL Workbench:

I have also created a SQL Fiddle that has a small dataset populated.

With this structure, I am able to create tasks that have a single Sel_Application_TypeID, which is used to create a specific set of Application_Type_Names for the task using the task_application_types linking table. In this way I can clone tasks or make child tasks, and still have the same selection for Application_Type_Names. This structure seems to work well for the rest of my site, but I'm struggling with how to get DataTables to show a comma separated list of the Application_Type_Names, like the Permissions column in the example. I'm sure I need to use Mjoin, and the example makes sense, but how can I incorporate the additional table?

Thanks,
Jordan

Still, Column Ordering Will Not Clear - implement with DataTables API

$
0
0

DataTables version: 1.10.13
Included libraries:
- DataTables 1.10.13
- Buttons 1.2.4
- Column visibility 1.2.4
- ColReorder 1.3.2
- FixedColumns 3.2.2
- FixedHeader 3.1.2
- KeyTable 2.2.0
- Responsive 2.1.0
- jQuery v1.11.1 (don't ask . . . we'll be here all day, yes it's outdated but not the problem)
Browsers: any
Using the DataTables API, not the object oriented dataTables

The problem: Once a user selects a column sorting, none of the clear methods on either reload or action on a button clear the column sorting selection. We just want to set it back to the natural order output server side.
For example the default ordering is column 2, the created date. Using the arrows in the table headers in DataTables I reorder by column 3, last modified. When I reload the page or hit the "clear filters" button, the method colReorder.reset() should clear the selected ordering. It does nothing.

I have been at this all day, mostly on this site, and it's still broken. I started with 1.10.0 and tried to use the fnSortNeutral plugin, threw various errors depending on how we tried to implement it.

Where we are now: Version 1.10.13 with the above build, no errors but it just doesn't DO anything. :-) All advice would be appreciated.

Task 1: On document ready, per the documentation,

https://datatables.net/reference/api/colReorder.reset()

this should clear the column selections, it does not. This snippet is loaded on document ready:

DT = jQuery('#tbl-wrap table').DataTable({
        **"colReorder": true,**
        "processing": true,
        "serverSide": true,
    "stateSave": true,
    "bAutoWidth":false,
    "deferRender": true,
    "oLanguage": {
    "sLengthMenu": "Show: _MENU_ ",
    "sSearch": "_INPUT_"
    },
      "ajax": sOurAjaxUrl,
    "columns": [
        { "data": "id", "name": "id" },
        { "data": "cr_date", "name": "cr_date" },
        { "data": "last_modified" , "name": "last_modified" },
        // ETC. : all our columns
    ],
    // To search via the filter form, the columns must be on the page. Set these hidden.
    "columnDefs" : [
        { "targets": [9, 10, 11, 12, 13, 14, 15], "visible": false, },
    ],
    "search": {
        "regex": true
    },
    // Once a column has been selected, this is not honored on reload!
    "order" : [[1, 'desc']],
    "fnDrawCallback": function(oSettings, oData) {
        // We do some stuff to the DOM here
    } // fnDrawCallBack
}).colReorder.reset(); // <--------- FAILS, but otherwise draws

Task 2: Alrighty then, that doesn't work, we have a clear filters button that works fine to clear all of our custom search fields across the column headers. This works great, but the reset() method doesn't work on the sort order. On load of the document, we attach the event to the button like so:

// Clear Filters button - clickEvent is either 'click' or 'touchstart' depending

jQuery('#clear-filters').on(clickEvent, function(e) {

    // The filter code which all works perfectly here

    DT.colReorder.reset().draw(); // <-------- FAILS, but otherwise draws

    return false;
});

It will draw the changes to the column search headers but will NOT include the changes to ordering.

Can someone please let me know what we're doing wrong here?

Datatable removing plus icon if childrow has no data

Viewing all 81396 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>